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.

339 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-2008 John-Mark Gurney <jmg@funkthat.com>
  5. __version__ = '$Change$'
  6. # $Id$
  7. #
  8. # This module implements the Content Directory Service (CDS) service
  9. # type as documented in the ContentDirectory:1 Service Template
  10. # Version 1.01
  11. #
  12. #
  13. # TODO: Figure out a nicer pattern for debugging soap server calls as
  14. # twisted swallows the tracebacks. At the moment I'm going:
  15. #
  16. # try:
  17. # ....
  18. # except:
  19. # traceback.print_exc(file = log.logfile)
  20. #
  21. reqname = 'requests'
  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 debug
  30. import traceback
  31. from urllib import quote
  32. class doRecall(defer.Deferred):
  33. '''A class that will upon any callback from the Deferred object passed
  34. in, recall fun(*args, **kwargs), just as if a maybeDeferred has been
  35. processed.
  36. The idea is to let something deeper called by something sync "abort"
  37. the call until it's ready, and then reattempt. This isn't the best
  38. method as we throw away work, but it can be easier to implement.
  39. Example:
  40. def wrapper(five):
  41. try:
  42. return doacall(five)
  43. except defer.Deferred, x:
  44. return doRecallgen(x, wrapper, five)
  45. If doacall works, everything is fine, but if a Deferred object is
  46. raised, we put it in a doRecall class and return the deferred object
  47. generated by doRecall.'''
  48. def __init__(self, argdef, fun, *args, **kwargs):
  49. self.fun = fun
  50. self.args = args
  51. self.kwargs = kwargs
  52. self.defer = defer.Deferred()
  53. argdef.addCallback(self._done)
  54. def _done(self, *args, **kwargs):
  55. ret = self.fun(*self.args, **self.kwargs)
  56. if isinstance(ret, failure.Failure):
  57. self.defer.errback(ret)
  58. elif isinstance(ret, defer.Deferred):
  59. # We are fruther delayed, continue.
  60. ret.addCallback(self._done)
  61. else:
  62. self.defer.callback(ret)
  63. def doRecallgen(defer, fun, *args, **kwargs):
  64. i = doRecall(defer, fun, *args, **kwargs)
  65. return i.defer
  66. class ContentDirectoryControl(UPnPPublisher, dict):
  67. """This class implements the CDS actions over SOAP."""
  68. namespace = 'urn:schemas-upnp-org:service:ContentDirectory:1'
  69. updateID = property(lambda x: x['0'].updateID)
  70. urlbase = property(lambda x: x._urlbase)
  71. def getnextID(self):
  72. ret = str(self.nextID)
  73. self.nextID += 1
  74. return ret
  75. def addContainer(self, parent, title, klass = Container, *args, **kwargs):
  76. ret = self.addObject(parent, klass, title, *args, **kwargs)
  77. self.children[ret] = self[ret]
  78. return ret
  79. def addItem(self, parent, klass, title, *args, **kwargs):
  80. if issubclass(klass, Container):
  81. return self.addContainer(parent, title, klass, *args, **kwargs)
  82. else:
  83. return self.addObject(parent, klass, title, *args, **kwargs)
  84. def addObject(self, parent, klass, title, *args, **kwargs):
  85. '''If the generated object (by klass) has an attribute content, it is installed into the web server.'''
  86. assert isinstance(self[parent], Container)
  87. nid = self.getnextID()
  88. i = klass(self, nid, parent, title, *args, **kwargs)
  89. if hasattr(i, 'content'):
  90. self.webbase.putChild(nid, i.content)
  91. #log.msg('children:', `self.children[parent]`, `i`)
  92. self.children[parent].append(i)
  93. self[i.id] = i
  94. return i.id
  95. def has_key(self, key):
  96. return dict.has_key(self, key)
  97. def delItem(self, id):
  98. if not self.has_key(id):
  99. log.msg('already removed:', id)
  100. return
  101. #log.msg('removing:', id)
  102. if isinstance(self[id], Container):
  103. #log.msg('children:', Container.__repr__(self.children[id]), map(None, self.children[id]))
  104. while self.children[id]:
  105. self.delItem(self.children[id][0].id)
  106. assert len(self.children[id]) == 0
  107. del self.children[id]
  108. # Remove from parent
  109. self.children[self[id].parentID].remove(self[id])
  110. # Remove content
  111. if hasattr(self[id], 'content'):
  112. self.webbase.delEntity(id)
  113. del self[id]
  114. def getchildren(self, item):
  115. assert isinstance(self[item], Container)
  116. return self.children[item][:]
  117. def __init__(self, title, *args, **kwargs):
  118. debug.insertringbuf(reqname)
  119. super(ContentDirectoryControl, self).__init__(*args)
  120. self.webbase = kwargs['webbase']
  121. self._urlbase = kwargs['urlbase']
  122. del kwargs['webbase'], kwargs['urlbase']
  123. fakeparent = '-1'
  124. self.nextID = 0
  125. self.children = { fakeparent: []}
  126. self[fakeparent] = Container(None, None, '-1', 'fake')
  127. root = self.addContainer(fakeparent, title, **kwargs)
  128. assert root == '0'
  129. del self[fakeparent]
  130. del self.children[fakeparent]
  131. # Required actions
  132. def soap_GetSearchCapabilities(self, *args, **kwargs):
  133. """Required: Return the searching capabilities supported by the device."""
  134. log.msg('GetSearchCapabilities()')
  135. return { 'SearchCaps': '' }
  136. def soap_GetSortCapabilities(self, *args, **kwargs):
  137. """Required: Return the CSV list of meta-data tags that can be used in
  138. sortCriteria."""
  139. log.msg('GetSortCapabilities()')
  140. return { 'SortCaps': '' }
  141. def soap_GetSystemUpdateID(self, *args, **kwargs):
  142. """Required: Return the current value of state variable SystemUpdateID."""
  143. return { 'Id': self.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. # return error code if we don't exist anymore
  168. if ObjectID not in self:
  169. raise errorCode(701)
  170. # check to see if object needs to be updated
  171. self[ObjectID].checkUpdate()
  172. # make sure we still exist, we could of deleted ourself
  173. if ObjectID not in self:
  174. raise errorCode(701)
  175. if BrowseFlag == 'BrowseDirectChildren':
  176. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  177. for i in ch:
  178. if i.needupdate:
  179. i.checkUpdate()
  180. didl.addItem(i)
  181. total = len(self.getchildren(ObjectID))
  182. else:
  183. didl.addItem(self[ObjectID])
  184. total = 1
  185. r = { 'Result': didl.toString(), 'TotalMatches': total,
  186. 'NumberReturned': didl.numItems(), }
  187. if hasattr(self[ObjectID], 'updateID'):
  188. r['UpdateID'] = self[ObjectID].updateID
  189. else:
  190. r['UpdateID'] = self.updateID
  191. return r
  192. # Optional actions
  193. def soap_Search(self, *args, **kwargs):
  194. """Search for objects that match some search criteria."""
  195. (ContainerID, SearchCriteria, Filter, StartingIndex,
  196. RequestedCount, SortCriteria) = args
  197. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  198. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  199. (`ContainerID`, `SearchCriteria`, `Filter`,
  200. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  201. def soap_CreateObject(self, *args, **kwargs):
  202. """Create a new object."""
  203. (ContainerID, Elements) = args
  204. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  205. (`ContainerID`, `Elements`))
  206. def soap_DestroyObject(self, *args, **kwargs):
  207. """Destroy the specified object."""
  208. (ObjectID) = args
  209. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  210. def soap_UpdateObject(self, *args, **kwargs):
  211. """Modify, delete or insert object metadata."""
  212. (ObjectID, CurrentTagValue, NewTagValue) = args
  213. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  214. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  215. `NewTagValue`))
  216. def soap_ImportResource(self, *args, **kwargs):
  217. """Transfer a file from a remote source to a local
  218. destination in the Content Directory Service."""
  219. (SourceURI, DestinationURI) = args
  220. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  221. (`SourceURI`, `DestinationURI`))
  222. def soap_ExportResource(self, *args, **kwargs):
  223. """Transfer a file from a local source to a remote
  224. destination."""
  225. (SourceURI, DestinationURI) = args
  226. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  227. (`SourceURI`, `DestinationURI`))
  228. def soap_StopTransferResource(self, *args, **kwargs):
  229. """Stop a file transfer initiated by ImportResource or
  230. ExportResource."""
  231. (TransferID) = args
  232. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  233. def soap_GetTransferProgress(self, *args, **kwargs):
  234. """Query the progress of a file transfer initiated by
  235. an ImportResource or ExportResource action."""
  236. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  237. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  238. 'TransferLength=%s, TransferTotal=%s)' %
  239. (`TransferId`, `TransferStatus`, `TransferLength`,
  240. `TransferTotal`))
  241. def soap_DeleteResource(self, *args, **kwargs):
  242. """Delete a specified resource."""
  243. (ResourceURI) = args
  244. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  245. def soap_CreateReference(self, *args, **kwargs):
  246. """Create a reference to an existing object."""
  247. (ContainerID, ObjectID) = args
  248. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  249. (`ContainerID`, `ObjectID`))
  250. def __repr__(self):
  251. return '<ContentDirectoryControl: cnt: %d, urlbase: %s, nextID: %d>' % (len(self), `self.urlbase`, self.nextID)
  252. class ContentDirectoryServer(resource.Resource):
  253. def __init__(self, title, *args, **kwargs):
  254. resource.Resource.__init__(self)
  255. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  256. self.control = ContentDirectoryControl(title, *args, **kwargs)
  257. self.putChild('control', self.control)