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.

340 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-2007 John-Mark Gurney <gurney_j@resnet.uoregon.edu>
  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. log.msg('GetSystemUpdateID()')
  144. return { 'Id': self.updateID }
  145. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  146. def soap_Browse(self, *args):
  147. l = {}
  148. debug.appendnamespace(reqname, l)
  149. if self.has_key(args[0]):
  150. l['object'] = self[args[0]]
  151. l['query'] = 'Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, ' \
  152. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' % \
  153. tuple(map(repr, args))
  154. try:
  155. ret = self.thereal_soap_Browse(*args)
  156. except defer.Deferred, x:
  157. ret = doRecallgen(x, self.soap_Browse, *args)
  158. l['response'] = ret
  159. return ret
  160. def thereal_soap_Browse(self, *args):
  161. """Required: Incrementally browse the native heirachy of the Content
  162. Directory objects exposed by the Content Directory Service."""
  163. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  164. SortCriteria) = args
  165. StartingIndex = int(StartingIndex)
  166. RequestedCount = int(RequestedCount)
  167. didl = DIDLElement()
  168. # return error code if we don't exist anymore
  169. if ObjectID not in self:
  170. raise errorCode(701)
  171. # check to see if object needs to be updated
  172. self[ObjectID].checkUpdate()
  173. # make sure we still exist, we could of deleted ourself
  174. if ObjectID not in self:
  175. raise errorCode(701)
  176. if BrowseFlag == 'BrowseDirectChildren':
  177. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  178. for i in ch:
  179. if i.needupdate:
  180. i.checkUpdate()
  181. didl.addItem(i)
  182. total = len(self.getchildren(ObjectID))
  183. else:
  184. didl.addItem(self[ObjectID])
  185. total = 1
  186. r = { 'Result': didl.toString(), 'TotalMatches': total,
  187. 'NumberReturned': didl.numItems(), }
  188. if hasattr(self[ObjectID], 'updateID'):
  189. r['UpdateID'] = self[ObjectID].updateID
  190. else:
  191. r['UpdateID'] = self.updateID
  192. return r
  193. # Optional actions
  194. def soap_Search(self, *args, **kwargs):
  195. """Search for objects that match some search criteria."""
  196. (ContainerID, SearchCriteria, Filter, StartingIndex,
  197. RequestedCount, SortCriteria) = args
  198. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  199. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  200. (`ContainerID`, `SearchCriteria`, `Filter`,
  201. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  202. def soap_CreateObject(self, *args, **kwargs):
  203. """Create a new object."""
  204. (ContainerID, Elements) = args
  205. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  206. (`ContainerID`, `Elements`))
  207. def soap_DestroyObject(self, *args, **kwargs):
  208. """Destroy the specified object."""
  209. (ObjectID) = args
  210. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  211. def soap_UpdateObject(self, *args, **kwargs):
  212. """Modify, delete or insert object metadata."""
  213. (ObjectID, CurrentTagValue, NewTagValue) = args
  214. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  215. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  216. `NewTagValue`))
  217. def soap_ImportResource(self, *args, **kwargs):
  218. """Transfer a file from a remote source to a local
  219. destination in the Content Directory Service."""
  220. (SourceURI, DestinationURI) = args
  221. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  222. (`SourceURI`, `DestinationURI`))
  223. def soap_ExportResource(self, *args, **kwargs):
  224. """Transfer a file from a local source to a remote
  225. destination."""
  226. (SourceURI, DestinationURI) = args
  227. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  228. (`SourceURI`, `DestinationURI`))
  229. def soap_StopTransferResource(self, *args, **kwargs):
  230. """Stop a file transfer initiated by ImportResource or
  231. ExportResource."""
  232. (TransferID) = args
  233. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  234. def soap_GetTransferProgress(self, *args, **kwargs):
  235. """Query the progress of a file transfer initiated by
  236. an ImportResource or ExportResource action."""
  237. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  238. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  239. 'TransferLength=%s, TransferTotal=%s)' %
  240. (`TransferId`, `TransferStatus`, `TransferLength`,
  241. `TransferTotal`))
  242. def soap_DeleteResource(self, *args, **kwargs):
  243. """Delete a specified resource."""
  244. (ResourceURI) = args
  245. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  246. def soap_CreateReference(self, *args, **kwargs):
  247. """Create a reference to an existing object."""
  248. (ContainerID, ObjectID) = args
  249. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  250. (`ContainerID`, `ObjectID`))
  251. def __repr__(self):
  252. return '<ContentDirectoryControl: cnt: %d, urlbase: %s, nextID: %d>' % (len(self), `self.urlbase`, self.nextID)
  253. class ContentDirectoryServer(resource.Resource):
  254. def __init__(self, title, *args, **kwargs):
  255. resource.Resource.__init__(self)
  256. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  257. self.control = ContentDirectoryControl(title, *args, **kwargs)
  258. self.putChild('control', self.control)