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.

326 lines
10 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. from twisted.internet import defer
  28. from twisted.python import failure
  29. import traceback
  30. from urllib import quote
  31. class doRecall(defer.Deferred):
  32. '''A class that will upon any callback from the Deferred object passed
  33. in, recall fun(*args, **kwargs), just as if a maybeDeferred has been
  34. processed.
  35. The idea is to let something deeper called by something sync "abort"
  36. the call until it's ready, and then reattempt. This isn't the best
  37. method as we throw away work, but it can be easier to implement.
  38. Example:
  39. def wrapper(five):
  40. try:
  41. return doacall(five)
  42. except defer.Deferred, x:
  43. return doRecallgen(x, wrapper, five)
  44. If doacall works, everything is fine, but if a Deferred object is
  45. raised, we put it in a doRecall class and return the deferred object
  46. generated by doRecall.'''
  47. def __init__(self, argdef, fun, *args, **kwargs):
  48. self.fun = fun
  49. self.args = args
  50. self.kwargs = kwargs
  51. self.defer = defer.Deferred()
  52. argdef.addCallback(self._done)
  53. def _done(self, *args, **kwargs):
  54. ret = self.fun(*self.args, **self.kwargs)
  55. if isinstance(ret, failure.Failure):
  56. self.defer.errback(ret)
  57. elif isinstance(ret, defer.Deferred):
  58. # We are fruther delayed, continue.
  59. ret.addCallback(self._done)
  60. else:
  61. self.defer.callback(ret)
  62. def doRecallgen(defer, fun, *args, **kwargs):
  63. i = doRecall(defer, fun, *args, **kwargs)
  64. return i.defer
  65. class ContentDirectoryControl(UPnPPublisher, dict):
  66. """This class implements the CDS actions over SOAP."""
  67. urlbase = property(lambda x: x._urlbase)
  68. def getnextID(self):
  69. ret = str(self.nextID)
  70. self.nextID += 1
  71. return ret
  72. def addContainer(self, parent, title, klass = Container, *args, **kwargs):
  73. ret = self.addObject(parent, klass, title, *args, **kwargs)
  74. self.children[ret] = self[ret]
  75. return ret
  76. def addItem(self, parent, klass, title, *args, **kwargs):
  77. if issubclass(klass, Container):
  78. return self.addContainer(parent, title, klass, *args, **kwargs)
  79. else:
  80. return self.addObject(parent, klass, title, *args, **kwargs)
  81. def addObject(self, parent, klass, title, *args, **kwargs):
  82. '''If the generated object (by klass) has an attribute content, it is installed into the web server.'''
  83. assert isinstance(self[parent], Container)
  84. nid = self.getnextID()
  85. i = klass(self, nid, parent, title, *args, **kwargs)
  86. if hasattr(i, 'content'):
  87. self.webbase.putChild(nid, i.content)
  88. self.children[parent].append(i)
  89. self[i.id] = i
  90. return i.id
  91. def delItem(self, id):
  92. if not self.has_key(id):
  93. log.msg('already removed:', id)
  94. return
  95. log.msg('removing:', id)
  96. if isinstance(self[id], Container):
  97. while self.children[id]:
  98. self.delItem(self.children[id][0])
  99. assert len(self.children[id]) == 0
  100. del self.children[id]
  101. # Remove from parent
  102. self.children[self[id].parentID].remove(self[id])
  103. # Remove content
  104. if hasattr(self[id], 'content'):
  105. self.webbase.delEntity(id)
  106. del self[id]
  107. def getchildren(self, item):
  108. assert isinstance(self[item], Container)
  109. return self.children[item][:]
  110. def __init__(self, title, *args, **kwargs):
  111. super(ContentDirectoryControl, self).__init__(*args)
  112. self.webbase = kwargs['webbase']
  113. self._urlbase = kwargs['urlbase']
  114. del kwargs['webbase'], kwargs['urlbase']
  115. fakeparent = '-1'
  116. self.nextID = 0
  117. self.children = { fakeparent: []}
  118. self[fakeparent] = Container(None, None, '-1', 'fake')
  119. root = self.addContainer(fakeparent, title, **kwargs)
  120. assert root == '0'
  121. del self[fakeparent]
  122. del self.children[fakeparent]
  123. # Required actions
  124. def soap_GetSearchCapabilities(self, *args, **kwargs):
  125. """Required: Return the searching capabilities supported by the device."""
  126. log.msg('GetSearchCapabilities()')
  127. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  128. def soap_GetSortCapabilities(self, *args, **kwargs):
  129. """Required: Return the CSV list of meta-data tags that can be used in
  130. sortCriteria."""
  131. log.msg('GetSortCapabilities()')
  132. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  133. def soap_GetSystemUpdateID(self, *args, **kwargs):
  134. """Required: Return the current value of state variable SystemUpdateID."""
  135. log.msg('GetSystemUpdateID()')
  136. return { 'SystemUpdateIdResponse': { 'Id': self['0'].updateID }}
  137. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  138. def soap_Browse(self, *args):
  139. try:
  140. return self.thereal_soap_Browse(*args)
  141. except defer.Deferred, x:
  142. return doRecallgen(x, self.soap_Browse, *args)
  143. def thereal_soap_Browse(self, *args):
  144. """Required: Incrementally browse the native heirachy of the Content
  145. Directory objects exposed by the Content Directory Service."""
  146. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  147. SortCriteria) = args
  148. StartingIndex = int(StartingIndex)
  149. RequestedCount = int(RequestedCount)
  150. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  151. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' %
  152. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  153. `RequestedCount`, `SortCriteria`))
  154. didl = DIDLElement()
  155. result = {}
  156. # check to see if object needs to be updated
  157. self[ObjectID].checkUpdate()
  158. # return error code if we don't exist
  159. if ObjectID not in self:
  160. raise errorCode(701)
  161. if BrowseFlag == 'BrowseDirectChildren':
  162. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  163. # filter out the ones that don't exist anymore, we need
  164. # to check against None, since some dirs might be empty
  165. # (of valid content) but exist.
  166. # XXX - technically if list changed, we need to get
  167. # some new ones by looping till we have a complete
  168. # list.
  169. ochup = filter(lambda x, s = self:
  170. s[x.id].checkUpdate() is not None, ch)
  171. # XXX - are we suppose to be calling addContainer
  172. # for Containers instead of always addItem?
  173. #log.msg('ochup:', `ochup`)
  174. filter(lambda x, d = didl: d.addItem(x) and None, ochup)
  175. total = len(self.getchildren(ObjectID))
  176. else:
  177. didl.addItem(self[ObjectID])
  178. total = 1
  179. result = {'BrowseResponse': {'Result': didl.toString() ,
  180. 'NumberReturned': didl.numItems(),
  181. 'TotalMatches': total,
  182. 'UpdateID': self[ObjectID].updateID }}
  183. #log.msg('Returning: %s' % result)
  184. return result
  185. # Optional actions
  186. def soap_Search(self, *args, **kwargs):
  187. """Search for objects that match some search criteria."""
  188. (ContainerID, SearchCriteria, Filter, StartingIndex,
  189. RequestedCount, SortCriteria) = args
  190. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  191. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  192. (`ContainerID`, `SearchCriteria`, `Filter`,
  193. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  194. def soap_CreateObject(self, *args, **kwargs):
  195. """Create a new object."""
  196. (ContainerID, Elements) = args
  197. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  198. (`ContainerID`, `Elements`))
  199. def soap_DestroyObject(self, *args, **kwargs):
  200. """Destroy the specified object."""
  201. (ObjectID) = args
  202. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  203. def soap_UpdateObject(self, *args, **kwargs):
  204. """Modify, delete or insert object metadata."""
  205. (ObjectID, CurrentTagValue, NewTagValue) = args
  206. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  207. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  208. `NewTagValue`))
  209. def soap_ImportResource(self, *args, **kwargs):
  210. """Transfer a file from a remote source to a local
  211. destination in the Content Directory Service."""
  212. (SourceURI, DestinationURI) = args
  213. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  214. (`SourceURI`, `DestinationURI`))
  215. def soap_ExportResource(self, *args, **kwargs):
  216. """Transfer a file from a local source to a remote
  217. destination."""
  218. (SourceURI, DestinationURI) = args
  219. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  220. (`SourceURI`, `DestinationURI`))
  221. def soap_StopTransferResource(self, *args, **kwargs):
  222. """Stop a file transfer initiated by ImportResource or
  223. ExportResource."""
  224. (TransferID) = args
  225. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  226. def soap_GetTransferProgress(self, *args, **kwargs):
  227. """Query the progress of a file transfer initiated by
  228. an ImportResource or ExportResource action."""
  229. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  230. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  231. 'TransferLength=%s, TransferTotal=%s)' %
  232. (`TransferId`, `TransferStatus`, `TransferLength`,
  233. `TransferTotal`))
  234. def soap_DeleteResource(self, *args, **kwargs):
  235. """Delete a specified resource."""
  236. (ResourceURI) = args
  237. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  238. def soap_CreateReference(self, *args, **kwargs):
  239. """Create a reference to an existing object."""
  240. (ContainerID, ObjectID) = args
  241. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  242. (`ContainerID`, `ObjectID`))
  243. def __repr__(self):
  244. return '<ContentDirectoryControl: cnt: %d, urlbase: %s, nextID: %d>' % (len(self), `self.urlbase`, self.nextID)
  245. class ContentDirectoryServer(resource.Resource):
  246. def __init__(self, title, *args, **kwargs):
  247. resource.Resource.__init__(self)
  248. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  249. self.control = ContentDirectoryControl(title, *args, **kwargs)
  250. self.putChild('control', self.control)