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.

252 lines
7.7 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 isinstance(self[id], Container):
  57. while self.children[id]:
  58. self.delItem(self.children[id][0])
  59. assert len(self.children[id]) == 0
  60. del self.children[id]
  61. # Remove from parent
  62. self.children[self[id].parentID].remove(self[id])
  63. del self[id]
  64. def getchildren(self, item):
  65. assert isinstance(self[item], Container)
  66. return self.children[item][:]
  67. def __init__(self, title, *args, **kwargs):
  68. super(ContentDirectoryControl, self).__init__(*args)
  69. self.webbase = kwargs['webbase']
  70. self._urlbase = kwargs['urlbase']
  71. del kwargs['webbase'], kwargs['urlbase']
  72. fakeparent = '-1'
  73. self.nextID = 0
  74. self.children = { fakeparent: []}
  75. self[fakeparent] = Container(None, None, '-1', 'fake')
  76. root = self.addContainer(fakeparent, title, **kwargs)
  77. assert root == '0'
  78. del self[fakeparent]
  79. del self.children[fakeparent]
  80. # Required actions
  81. def soap_GetSearchCapabilities(self, *args, **kwargs):
  82. """Required: Return the searching capabilities supported by the device."""
  83. log.msg('GetSearchCapabilities()')
  84. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  85. def soap_GetSortCapabilities(self, *args, **kwargs):
  86. """Required: Return the CSV list of meta-data tags that can be used in
  87. sortCriteria."""
  88. log.msg('GetSortCapabilities()')
  89. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  90. def soap_GetSystemUpdateID(self, *args, **kwargs):
  91. """Required: Return the current value of state variable SystemUpdateID."""
  92. log.msg('GetSystemUpdateID()')
  93. return { 'SystemUpdateIdResponse': { 'Id': self['0'].updateID }}
  94. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  95. def soap_Browse(self, *args):
  96. """Required: Incrementally browse the native heirachy of the Content
  97. Directory objects exposed by the Content Directory Service."""
  98. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  99. SortCriteria) = args
  100. StartingIndex = int(StartingIndex)
  101. RequestedCount = int(RequestedCount)
  102. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  103. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' %
  104. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  105. `RequestedCount`, `SortCriteria`))
  106. didl = DIDLElement()
  107. result = {}
  108. # check to see if object needs to be updated
  109. self[ObjectID].checkUpdate()
  110. # return error code if we don't exist
  111. if ObjectID not in self:
  112. raise errorCode(701)
  113. if BrowseFlag == 'BrowseDirectChildren':
  114. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  115. filter(lambda x, d = didl: d.addItem(x) and None, filter(lambda x, s = self: s[x.id].checkUpdate(), ch))
  116. else:
  117. didl.addItem(self[ObjectID])
  118. result = {'BrowseResponse': {'Result': didl.toString() ,
  119. 'NumberReturned': didl.numItems(),
  120. 'TotalMatches': didl.numItems(),
  121. 'UpdateID': self[ObjectID].updateID }}
  122. #log.msg('Returning: %s' % result)
  123. return result
  124. # Optional actions
  125. def soap_Search(self, *args, **kwargs):
  126. """Search for objects that match some search criteria."""
  127. (ContainerID, SearchCriteria, Filter, StartingIndex,
  128. RequestedCount, SortCriteria) = args
  129. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  130. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  131. (`ContainerID`, `SearchCriteria`, `Filter`,
  132. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  133. def soap_CreateObject(self, *args, **kwargs):
  134. """Create a new object."""
  135. (ContainerID, Elements) = args
  136. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  137. (`ContainerID`, `Elements`))
  138. def soap_DestroyObject(self, *args, **kwargs):
  139. """Destroy the specified object."""
  140. (ObjectID) = args
  141. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  142. def soap_UpdateObject(self, *args, **kwargs):
  143. """Modify, delete or insert object metadata."""
  144. (ObjectID, CurrentTagValue, NewTagValue) = args
  145. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  146. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  147. `NewTagValue`))
  148. def soap_ImportResource(self, *args, **kwargs):
  149. """Transfer a file from a remote source to a local
  150. destination in the Content Directory Service."""
  151. (SourceURI, DestinationURI) = args
  152. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  153. (`SourceURI`, `DestinationURI`))
  154. def soap_ExportResource(self, *args, **kwargs):
  155. """Transfer a file from a local source to a remote
  156. destination."""
  157. (SourceURI, DestinationURI) = args
  158. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  159. (`SourceURI`, `DestinationURI`))
  160. def soap_StopTransferResource(self, *args, **kwargs):
  161. """Stop a file transfer initiated by ImportResource or
  162. ExportResource."""
  163. (TransferID) = args
  164. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  165. def soap_GetTransferProgress(self, *args, **kwargs):
  166. """Query the progress of a file transfer initiated by
  167. an ImportResource or ExportResource action."""
  168. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  169. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  170. 'TransferLength=%s, TransferTotal=%s)' %
  171. (`TransferId`, `TransferStatus`, `TransferLength`,
  172. `TransferTotal`))
  173. def soap_DeleteResource(self, *args, **kwargs):
  174. """Delete a specified resource."""
  175. (ResourceURI) = args
  176. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  177. def soap_CreateReference(self, *args, **kwargs):
  178. """Create a reference to an existing object."""
  179. (ContainerID, ObjectID) = args
  180. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  181. (`ContainerID`, `ObjectID`))
  182. class ContentDirectoryServer(resource.Resource):
  183. def __init__(self, title, *args, **kwargs):
  184. resource.Resource.__init__(self)
  185. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  186. self.control = ContentDirectoryControl(title, *args, **kwargs)
  187. self.putChild('control', self.control)