A Python UPnP Media Server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

256 lines
7.8 KiB

  1. # Licensed under the MIT license
  2. # http://opensource.org/licenses/mit-license.php
  3. # Copyright 2005, Tim Potter <tpot@samba.org>
  4. # Copyright 2006 John-Mark Gurney <gurney_j@resnet.uoregon.edu>
  5. #
  6. # $Id$
  7. #
  8. #
  9. # This module implements the Content Directory Service (CDS) service
  10. # type as documented in the ContentDirectory:1 Service Template
  11. # Version 1.01
  12. #
  13. #
  14. # TODO: Figure out a nicer pattern for debugging soap server calls as
  15. # twisted swallows the tracebacks. At the moment I'm going:
  16. #
  17. # try:
  18. # ....
  19. # except:
  20. # traceback.print_exc(file = log.logfile)
  21. #
  22. from twisted.python import log
  23. from twisted.web import resource, static
  24. from elementtree.ElementTree import Element, SubElement, tostring
  25. from upnp import UPnPPublisher, errorCode
  26. from DIDLLite import DIDLElement, Container, Movie, Resource, MusicTrack
  27. import traceback
  28. from urllib import quote
  29. class ContentDirectoryControl(UPnPPublisher, dict):
  30. """This class implements the CDS actions over SOAP."""
  31. urlbase = property(lambda x: x._urlbase)
  32. def getnextID(self):
  33. ret = str(self.nextID)
  34. self.nextID += 1
  35. return ret
  36. def addContainer(self, parent, title, klass = Container, *args, **kwargs):
  37. ret = self.addObject(parent, klass, title, *args, **kwargs)
  38. self.children[ret] = self[ret]
  39. return ret
  40. def addItem(self, parent, klass, title, *args, **kwargs):
  41. if issubclass(klass, Container):
  42. return self.addContainer(parent, title, klass, *args, **kwargs)
  43. else:
  44. return self.addObject(parent, klass, title, *args, **kwargs)
  45. def addObject(self, parent, klass, title, *args, **kwargs):
  46. '''If the generated object (by klass) has an attribute content, it is installed into the web server.'''
  47. assert isinstance(self[parent], Container)
  48. nid = self.getnextID()
  49. i = klass(self, nid, parent, title, *args, **kwargs)
  50. if hasattr(i, 'content'):
  51. self.webbase.putChild(nid, i.content)
  52. self.children[parent].append(i)
  53. self[i.id] = i
  54. return i.id
  55. def delItem(self, id):
  56. if not self.has_key(id):
  57. log.msg('already removed:', id)
  58. return
  59. log.msg('removing:', id)
  60. if isinstance(self[id], Container):
  61. while self.children[id]:
  62. self.delItem(self.children[id][0])
  63. assert len(self.children[id]) == 0
  64. del self.children[id]
  65. # Remove from parent
  66. self.children[self[id].parentID].remove(self[id])
  67. del self[id]
  68. def getchildren(self, item):
  69. assert isinstance(self[item], Container)
  70. return self.children[item][:]
  71. def __init__(self, title, *args, **kwargs):
  72. super(ContentDirectoryControl, self).__init__(*args)
  73. self.webbase = kwargs['webbase']
  74. self._urlbase = kwargs['urlbase']
  75. del kwargs['webbase'], kwargs['urlbase']
  76. fakeparent = '-1'
  77. self.nextID = 0
  78. self.children = { fakeparent: []}
  79. self[fakeparent] = Container(None, None, '-1', 'fake')
  80. root = self.addContainer(fakeparent, title, **kwargs)
  81. assert root == '0'
  82. del self[fakeparent]
  83. del self.children[fakeparent]
  84. # Required actions
  85. def soap_GetSearchCapabilities(self, *args, **kwargs):
  86. """Required: Return the searching capabilities supported by the device."""
  87. log.msg('GetSearchCapabilities()')
  88. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  89. def soap_GetSortCapabilities(self, *args, **kwargs):
  90. """Required: Return the CSV list of meta-data tags that can be used in
  91. sortCriteria."""
  92. log.msg('GetSortCapabilities()')
  93. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  94. def soap_GetSystemUpdateID(self, *args, **kwargs):
  95. """Required: Return the current value of state variable SystemUpdateID."""
  96. log.msg('GetSystemUpdateID()')
  97. return { 'SystemUpdateIdResponse': { 'Id': self['0'].updateID }}
  98. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  99. def soap_Browse(self, *args):
  100. """Required: Incrementally browse the native heirachy of the Content
  101. Directory objects exposed by the Content Directory Service."""
  102. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  103. SortCriteria) = args
  104. StartingIndex = int(StartingIndex)
  105. RequestedCount = int(RequestedCount)
  106. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  107. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' %
  108. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  109. `RequestedCount`, `SortCriteria`))
  110. didl = DIDLElement()
  111. result = {}
  112. # check to see if object needs to be updated
  113. self[ObjectID].checkUpdate()
  114. # return error code if we don't exist
  115. if ObjectID not in self:
  116. raise errorCode(701)
  117. if BrowseFlag == 'BrowseDirectChildren':
  118. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  119. filter(lambda x, d = didl: d.addItem(x) and None, filter(lambda x, s = self: s[x.id].checkUpdate(), ch))
  120. else:
  121. didl.addItem(self[ObjectID])
  122. result = {'BrowseResponse': {'Result': didl.toString() ,
  123. 'NumberReturned': didl.numItems(),
  124. 'TotalMatches': didl.numItems(),
  125. 'UpdateID': self[ObjectID].updateID }}
  126. #log.msg('Returning: %s' % result)
  127. return result
  128. # Optional actions
  129. def soap_Search(self, *args, **kwargs):
  130. """Search for objects that match some search criteria."""
  131. (ContainerID, SearchCriteria, Filter, StartingIndex,
  132. RequestedCount, SortCriteria) = args
  133. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  134. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  135. (`ContainerID`, `SearchCriteria`, `Filter`,
  136. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  137. def soap_CreateObject(self, *args, **kwargs):
  138. """Create a new object."""
  139. (ContainerID, Elements) = args
  140. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  141. (`ContainerID`, `Elements`))
  142. def soap_DestroyObject(self, *args, **kwargs):
  143. """Destroy the specified object."""
  144. (ObjectID) = args
  145. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  146. def soap_UpdateObject(self, *args, **kwargs):
  147. """Modify, delete or insert object metadata."""
  148. (ObjectID, CurrentTagValue, NewTagValue) = args
  149. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  150. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  151. `NewTagValue`))
  152. def soap_ImportResource(self, *args, **kwargs):
  153. """Transfer a file from a remote source to a local
  154. destination in the Content Directory Service."""
  155. (SourceURI, DestinationURI) = args
  156. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  157. (`SourceURI`, `DestinationURI`))
  158. def soap_ExportResource(self, *args, **kwargs):
  159. """Transfer a file from a local source to a remote
  160. destination."""
  161. (SourceURI, DestinationURI) = args
  162. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  163. (`SourceURI`, `DestinationURI`))
  164. def soap_StopTransferResource(self, *args, **kwargs):
  165. """Stop a file transfer initiated by ImportResource or
  166. ExportResource."""
  167. (TransferID) = args
  168. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  169. def soap_GetTransferProgress(self, *args, **kwargs):
  170. """Query the progress of a file transfer initiated by
  171. an ImportResource or ExportResource action."""
  172. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  173. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  174. 'TransferLength=%s, TransferTotal=%s)' %
  175. (`TransferId`, `TransferStatus`, `TransferLength`,
  176. `TransferTotal`))
  177. def soap_DeleteResource(self, *args, **kwargs):
  178. """Delete a specified resource."""
  179. (ResourceURI) = args
  180. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  181. def soap_CreateReference(self, *args, **kwargs):
  182. """Create a reference to an existing object."""
  183. (ContainerID, ObjectID) = args
  184. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  185. (`ContainerID`, `ObjectID`))
  186. class ContentDirectoryServer(resource.Resource):
  187. def __init__(self, title, *args, **kwargs):
  188. resource.Resource.__init__(self)
  189. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  190. self.control = ContentDirectoryControl(title, *args, **kwargs)
  191. self.putChild('control', self.control)