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