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.

235 lines
7.1 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, errorCode
  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] = self[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(self, nid, parent, *args, **kwargs)
  40. self.children[parent].append(i)
  41. self[i.id] = i
  42. return i.id
  43. def delItem(self, id):
  44. if isinstance(self[id], Container):
  45. for i in self.children[id]:
  46. self.delItem(i)
  47. assert len(self.children[id]) == 0
  48. del self.children[id]
  49. # Remove from parent
  50. self.children[self[id].parentID].remove(self[id])
  51. del self[id]
  52. def getchildren(self, item):
  53. assert isinstance(self[item], Container)
  54. return self.children[item][:]
  55. def __init__(self, title, *args, **kwargs):
  56. super(ContentDirectoryControl, self).__init__(*args)
  57. fakeparent = '-1'
  58. self.nextID = 0
  59. self.children = { fakeparent: []}
  60. self[fakeparent] = Container(None, None, '-1', 'fake')
  61. root = self.addContainer(fakeparent, title, **kwargs)
  62. assert root == '0'
  63. del self[fakeparent]
  64. del self.children[fakeparent]
  65. # Required actions
  66. def soap_GetSearchCapabilities(self, *args, **kwargs):
  67. """Required: Return the searching capabilities supported by the device."""
  68. log.msg('GetSearchCapabilities()')
  69. return { 'SearchCapabilitiesResponse': { 'SearchCaps': '' }}
  70. def soap_GetSortCapabilities(self, *args, **kwargs):
  71. """Required: Return the CSV list of meta-data tags that can be used in
  72. sortCriteria."""
  73. log.msg('GetSortCapabilities()')
  74. return { 'SortCapabilitiesResponse': { 'SortCaps': '' }}
  75. def soap_GetSystemUpdateID(self, *args, **kwargs):
  76. """Required: Return the current value of state variable SystemUpdateID."""
  77. log.msg('GetSystemUpdateID()')
  78. return { 'SystemUpdateIdResponse': { 'Id': self['0'].updateID }}
  79. BrowseFlags = ('BrowseMetaData', 'BrowseDirectChildren')
  80. def soap_Browse(self, *args):
  81. """Required: Incrementally browse the native heirachy of the Content
  82. Directory objects exposed by the Content Directory Service."""
  83. (ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,
  84. SortCriteria) = args
  85. StartingIndex = int(StartingIndex)
  86. RequestedCount = int(RequestedCount)
  87. log.msg('Browse(ObjectID=%s, BrowseFlags=%s, Filter=%s, '
  88. 'StartingIndex=%s RequestedCount=%s SortCriteria=%s)' %
  89. (`ObjectID`, `BrowseFlag`, `Filter`, `StartingIndex`,
  90. `RequestedCount`, `SortCriteria`))
  91. didl = DIDLElement()
  92. result = {}
  93. # check to see if object needs to be updated
  94. self[ObjectID].checkUpdate()
  95. # return error code if we don't exist
  96. if ObjectID not in self:
  97. raise errorCode(701)
  98. if BrowseFlag == 'BrowseDirectChildren':
  99. ch = self.getchildren(ObjectID)[StartingIndex: StartingIndex + RequestedCount]
  100. filter(lambda x, d = didl: d.addItem(x) and None, filter(lambda x, s = self: s[x.id].checkUpdate(), ch))
  101. else:
  102. didl.addItem(self[ObjectID])
  103. result = {'BrowseResponse': {'Result': didl.toString() ,
  104. 'NumberReturned': didl.numItems(),
  105. 'TotalMatches': didl.numItems(),
  106. 'UpdateID': self[ObjectID].updateID }}
  107. #log.msg('Returning: %s' % result)
  108. return result
  109. # Optional actions
  110. def soap_Search(self, *args, **kwargs):
  111. """Search for objects that match some search criteria."""
  112. (ContainerID, SearchCriteria, Filter, StartingIndex,
  113. RequestedCount, SortCriteria) = args
  114. log.msg('Search(ContainerID=%s, SearchCriteria=%s, Filter=%s, ' \
  115. 'StartingIndex=%s, RequestedCount=%s, SortCriteria=%s)' %
  116. (`ContainerID`, `SearchCriteria`, `Filter`,
  117. `StartingIndex`, `RequestedCount`, `SortCriteria`))
  118. def soap_CreateObject(self, *args, **kwargs):
  119. """Create a new object."""
  120. (ContainerID, Elements) = args
  121. log.msg('CreateObject(ContainerID=%s, Elements=%s)' %
  122. (`ContainerID`, `Elements`))
  123. def soap_DestroyObject(self, *args, **kwargs):
  124. """Destroy the specified object."""
  125. (ObjectID) = args
  126. log.msg('DestroyObject(ObjectID=%s)' % `ObjectID`)
  127. def soap_UpdateObject(self, *args, **kwargs):
  128. """Modify, delete or insert object metadata."""
  129. (ObjectID, CurrentTagValue, NewTagValue) = args
  130. log.msg('UpdateObject(ObjectID=%s, CurrentTagValue=%s, ' \
  131. 'NewTagValue=%s)' % (`ObjectID`, `CurrentTagValue`,
  132. `NewTagValue`))
  133. def soap_ImportResource(self, *args, **kwargs):
  134. """Transfer a file from a remote source to a local
  135. destination in the Content Directory Service."""
  136. (SourceURI, DestinationURI) = args
  137. log.msg('ImportResource(SourceURI=%s, DestinationURI=%s)' %
  138. (`SourceURI`, `DestinationURI`))
  139. def soap_ExportResource(self, *args, **kwargs):
  140. """Transfer a file from a local source to a remote
  141. destination."""
  142. (SourceURI, DestinationURI) = args
  143. log.msg('ExportResource(SourceURI=%s, DestinationURI=%s)' %
  144. (`SourceURI`, `DestinationURI`))
  145. def soap_StopTransferResource(self, *args, **kwargs):
  146. """Stop a file transfer initiated by ImportResource or
  147. ExportResource."""
  148. (TransferID) = args
  149. log.msg('StopTransferResource(TransferID=%s)' % TransferID)
  150. def soap_GetTransferProgress(self, *args, **kwargs):
  151. """Query the progress of a file transfer initiated by
  152. an ImportResource or ExportResource action."""
  153. (TransferID, TransferStatus, TransferLength, TransferTotal) = args
  154. log.msg('GetTransferProgress(TransferID=%s, TransferStatus=%s, ' \
  155. 'TransferLength=%s, TransferTotal=%s)' %
  156. (`TransferId`, `TransferStatus`, `TransferLength`,
  157. `TransferTotal`))
  158. def soap_DeleteResource(self, *args, **kwargs):
  159. """Delete a specified resource."""
  160. (ResourceURI) = args
  161. log.msg('DeleteResource(ResourceURI=%s)' % `ResourceURI`)
  162. def soap_CreateReference(self, *args, **kwargs):
  163. """Create a reference to an existing object."""
  164. (ContainerID, ObjectID) = args
  165. log.msg('CreateReference(ContainerID=%s, ObjectID=%s)' %
  166. (`ContainerID`, `ObjectID`))
  167. class ContentDirectoryServer(resource.Resource):
  168. def __init__(self, title, *args, **kwargs):
  169. resource.Resource.__init__(self)
  170. self.putChild('scpd.xml', static.File('content-directory-scpd.xml'))
  171. self.control = ContentDirectoryControl(title, *args, **kwargs)
  172. self.putChild('control', self.control)