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.

230 lines
7.8 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. # This module implements the Content Directory Service (CDS) service
  7. # type as documented in the ContentDirectory:1 Service Template
  8. # Version 1.01
  9. #
  10. #
  11. # TODO: Figure out a nicer pattern for debugging soap server calls as
  12. # twisted swallows the tracebacks. At the moment I'm going:
  13. #
  14. # try:
  15. # ....
  16. # except:
  17. # traceback.print_exc(file = log.logfile)
  18. #
  19. from twisted.python import log
  20. from twisted.web import resource, static
  21. from elementtree.ElementTree import Element, SubElement, tostring
  22. from upnp import UPnPPublisher
  23. from DIDLLite import DIDLElement, Container, Movie, Resource, MusicTrack
  24. import traceback
  25. from urllib import quote
  26. class ContentDirectoryControl(UPnPPublisher, dict):
  27. """This class implements the CDS actions over SOAP."""
  28. def getnextID(self):
  29. ret = str(self.nextID)
  30. self.nextID += 1
  31. return ret
  32. def addContainer(self, parent, title, klass = Container, **kwargs):
  33. ret = self.addItem(parent, klass, title, **kwargs)
  34. self.children[ret] = []
  35. return ret
  36. def addItem(self, parent, klass, *args, **kwargs):
  37. assert isinstance(self[parent], Container)
  38. nid = self.getnextID()
  39. i = klass(nid, parent, *args, **kwargs)
  40. self.children[parent].append(i)
  41. self[i.id] = i
  42. return i.id
  43. def getchildren(self, item):
  44. assert isinstance(self[item], Container)
  45. return self.children[item][:]
  46. def __init__(self, title, *args):
  47. super(ContentDirectoryControl, self).__init__(*args)
  48. fakeparent = '-1'
  49. self.nextID = 0
  50. self.children = { fakeparent: []}
  51. self.needupdate = False
  52. self.updateId = 0
  53. self[fakeparent] = Container(None, '-1', 'fake')
  54. root = self.addContainer(fakeparent, title)
  55. assert root == '0'
  56. del self[fakeparent]
  57. del self.children[fakeparent]
  58. def doupdate(self):
  59. if self.needupdate:
  60. self.needupdate += 1
  61. self.needupdate = False
  62. # Required actions
  63. def soap_GetSearchCapabilities(self, *args, **kwargs):
  64. """Required: Return the searching capabilities supported by the device."""
  65. log.msg('GetSearchCapabilities()')
  66. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  67. def soap_GetSortCapabilities(self, *args, **kwargs):
  68. """Required: Return the CSV list of meta-data tags that can be used in
  69. sortCriteria."""
  70. log.msg('GetSortCapabilities()')
  71. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  72. def soap_GetSystemUpdateID(self, *args, **kwargs):
  73. """Required: Return the current value of state variable SystemUpdateID."""
  74. log.msg('GetSystemUpdateID()')
  75. self.needupdate = True
  76. return { 'SystemUpdateIdResponse': { 'Id': self.updateId }}
  77. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  78. def soap_Browse(self, *args):
  79. """Required: Incrementally browse the native heirachy of the Content
  80. Directory objects exposed by the Content Directory Service."""
  81. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  82. SortCriteria) = args
  83. StartingIndex = int(StartingIndex)
  84. RequestedCount = int(RequestedCount)
  85. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  86. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' %
  87. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  88. `RequestedCount`, `SortCriteria`))
  89. didl = DIDLElement()
  90. result = {}
  91. try:
  92. if BrowseFlag == 'BrowseDirectChildren':
  93. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  94. filter(lambda x, s = self, d = didl: d.addItem(s[x.id]) and None, ch)
  95. else:
  96. didl.addItem(self[ObjectID])
  97. result = {'BrowseResponse': {'Result': didl.toString() ,
  98. 'NumberReturned': didl.numItems(),
  99. 'TotalMatches': didl.numItems(),
  100. 'UpdateID': 0}}
  101. except:
  102. traceback.print_exc(file=log.logfile)
  103. log.msg('Returning: %s' % result)
  104. return result
  105. # Optional actions
  106. def soap_Search(self, *args, **kwargs):
  107. """Search for objects that match some search criteria."""
  108. (ContainerID, SearchCriteria, Filter, StartingIndex,
  109. RequestedCount, SortCriteria) = args
  110. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  111. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  112. (`ContainerID`, `SearchCriteria`, `Filter`,
  113. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  114. def soap_CreateObject(self, *args, **kwargs):
  115. """Create a new object."""
  116. (ContainerID, Elements) = args
  117. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  118. (`ContainerID`, `Elements`))
  119. def soap_DestroyObject(self, *args, **kwargs):
  120. """Destroy the specified object."""
  121. (ObjectID) = args
  122. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  123. def soap_UpdateObject(self, *args, **kwargs):
  124. """Modify, delete or insert object metadata."""
  125. (ObjectID, CurrentTagValue, NewTagValue) = args
  126. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  127. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  128. `NewTagValue`))
  129. def soap_ImportResource(self, *args, **kwargs):
  130. """Transfer a file from a remote source to a local
  131. destination in the Content Directory Service."""
  132. (SourceURI, DestinationURI) = args
  133. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  134. (`SourceURI`, `DestinationURI`))
  135. def soap_ExportResource(self, *args, **kwargs):
  136. """Transfer a file from a local source to a remote
  137. destination."""
  138. (SourceURI, DestinationURI) = args
  139. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  140. (`SourceURI`, `DestinationURI`))
  141. def soap_StopTransferResource(self, *args, **kwargs):
  142. """Stop a file transfer initiated by ImportResource or
  143. ExportResource."""
  144. (TransferID) = args
  145. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  146. def soap_GetTransferProgress(self, *args, **kwargs):
  147. """Query the progress of a file transfer initiated by
  148. an ImportResource or ExportResource action."""
  149. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  150. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  151. 'TransferLength=%s, TransferTotal=%s)' %
  152. (`TransferId`, `TransferStatus`, `TransferLength`,
  153. `TransferTotal`))
  154. def soap_DeleteResource(self, *args, **kwargs):
  155. """Delete a specified resource."""
  156. (ResourceURI) = args
  157. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  158. def soap_CreateReference(self, *args, **kwargs):
  159. """Create a reference to an existing object."""
  160. (ContainerID, ObjectID) = args
  161. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  162. (`ContainerID`, `ObjectID`))
  163. class ContentDirectoryServer(resource.Resource):
  164. def __init__(self, title):
  165. resource.Resource.__init__(self)
  166. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  167. self.control = ContentDirectoryControl(title)
  168. self.putChild('control', self.control)