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.

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