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.

331 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. #log.msg('children:', `self.children[parent]`, `i`)
  89. self.children[parent].append(i)
  90. self[i.id] = i
  91. return i.id
  92. def has_key(self, key):
  93. return dict.has_key(self, key)
  94. def delItem(self, id):
  95. if not self.has_key(id):
  96. log.msg('already removed:', id)
  97. return
  98. #log.msg('removing:', id)
  99. if isinstance(self[id], Container):
  100. #log.msg('children:', Container.__repr__(self.children[id]), map(None, self.children[id]))
  101. while self.children[id]:
  102. self.delItem(self.children[id][0].id)
  103. assert len(self.children[id]) == 0
  104. del self.children[id]
  105. # Remove from parent
  106. self.children[self[id].parentID].remove(self[id])
  107. # Remove content
  108. if hasattr(self[id], 'content'):
  109. self.webbase.delEntity(id)
  110. del self[id]
  111. def getchildren(self, item):
  112. assert isinstance(self[item], Container)
  113. return self.children[item][:]
  114. def __init__(self, title, *args, **kwargs):
  115. super(ContentDirectoryControl, self).__init__(*args)
  116. self.webbase = kwargs['webbase']
  117. self._urlbase = kwargs['urlbase']
  118. del kwargs['webbase'], kwargs['urlbase']
  119. fakeparent = '-1'
  120. self.nextID = 0
  121. self.children = { fakeparent: []}
  122. self[fakeparent] = Container(None, None, '-1', 'fake')
  123. root = self.addContainer(fakeparent, title, **kwargs)
  124. assert root == '0'
  125. del self[fakeparent]
  126. del self.children[fakeparent]
  127. # Required actions
  128. def soap_GetSearchCapabilities(self, *args, **kwargs):
  129. """Required: Return the searching capabilities supported by the device."""
  130. log.msg('GetSearchCapabilities()')
  131. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  132. def soap_GetSortCapabilities(self, *args, **kwargs):
  133. """Required: Return the CSV list of meta-data tags that can be used in
  134. sortCriteria."""
  135. log.msg('GetSortCapabilities()')
  136. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  137. def soap_GetSystemUpdateID(self, *args, **kwargs):
  138. """Required: Return the current value of state variable SystemUpdateID."""
  139. log.msg('GetSystemUpdateID()')
  140. return { 'SystemUpdateIdResponse': { 'Id': self['0'].updateID }}
  141. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  142. def soap_Browse(self, *args):
  143. try:
  144. return self.thereal_soap_Browse(*args)
  145. except defer.Deferred, x:
  146. return doRecallgen(x, self.soap_Browse, *args)
  147. def thereal_soap_Browse(self, *args):
  148. """Required: Incrementally browse the native heirachy of the Content
  149. Directory objects exposed by the Content Directory Service."""
  150. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  151. SortCriteria) = args
  152. StartingIndex = int(StartingIndex)
  153. RequestedCount = int(RequestedCount)
  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: s.has_key(x.id) and
  170. s[x.id].checkUpdate() is not None, ch)
  171. if len(ochup) != len(ch):
  172. log.msg('ch:', `ch`, 'ochup:', `ochup`)
  173. raise RuntimeError, 'something disappeared'
  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. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  185. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s) = %s' %
  186. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  187. `RequestedCount`, `SortCriteria`, `result`))
  188. return result
  189. # Optional actions
  190. def soap_Search(self, *args, **kwargs):
  191. """Search for objects that match some search criteria."""
  192. (ContainerID, SearchCriteria, Filter, StartingIndex,
  193. RequestedCount, SortCriteria) = args
  194. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  195. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  196. (`ContainerID`, `SearchCriteria`, `Filter`,
  197. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  198. def soap_CreateObject(self, *args, **kwargs):
  199. """Create a new object."""
  200. (ContainerID, Elements) = args
  201. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  202. (`ContainerID`, `Elements`))
  203. def soap_DestroyObject(self, *args, **kwargs):
  204. """Destroy the specified object."""
  205. (ObjectID) = args
  206. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  207. def soap_UpdateObject(self, *args, **kwargs):
  208. """Modify, delete or insert object metadata."""
  209. (ObjectID, CurrentTagValue, NewTagValue) = args
  210. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  211. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  212. `NewTagValue`))
  213. def soap_ImportResource(self, *args, **kwargs):
  214. """Transfer a file from a remote source to a local
  215. destination in the Content Directory Service."""
  216. (SourceURI, DestinationURI) = args
  217. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  218. (`SourceURI`, `DestinationURI`))
  219. def soap_ExportResource(self, *args, **kwargs):
  220. """Transfer a file from a local source to a remote
  221. destination."""
  222. (SourceURI, DestinationURI) = args
  223. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  224. (`SourceURI`, `DestinationURI`))
  225. def soap_StopTransferResource(self, *args, **kwargs):
  226. """Stop a file transfer initiated by ImportResource or
  227. ExportResource."""
  228. (TransferID) = args
  229. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  230. def soap_GetTransferProgress(self, *args, **kwargs):
  231. """Query the progress of a file transfer initiated by
  232. an ImportResource or ExportResource action."""
  233. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  234. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  235. 'TransferLength=%s, TransferTotal=%s)' %
  236. (`TransferId`, `TransferStatus`, `TransferLength`,
  237. `TransferTotal`))
  238. def soap_DeleteResource(self, *args, **kwargs):
  239. """Delete a specified resource."""
  240. (ResourceURI) = args
  241. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  242. def soap_CreateReference(self, *args, **kwargs):
  243. """Create a reference to an existing object."""
  244. (ContainerID, ObjectID) = args
  245. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  246. (`ContainerID`, `ObjectID`))
  247. def __repr__(self):
  248. return '<ContentDirectoryControl: cnt: %d, urlbase: %s, nextID: %d>' % (len(self), `self.urlbase`, self.nextID)
  249. class ContentDirectoryServer(resource.Resource):
  250. def __init__(self, title, *args, **kwargs):
  251. resource.Resource.__init__(self)
  252. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  253. self.control = ContentDirectoryControl(title, *args, **kwargs)
  254. self.putChild('control', self.control)