A Python UPnP Media Server

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