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.

211 lines
5.8 KiB

  1. #!/usr/bin/env python
  2. # Licensed under the MIT license
  3. # http://opensource.org/licenses/mit-license.php
  4. # Copyright 2005, Tim Potter <tpot@samba.org>
  5. # Copyright 2006-2009 John-Mark Gurney <jmg@funkthat.com>
  6. __version__ = '$Change$'
  7. # $Id$
  8. # make sure debugging is initalized first, other modules can be pulled in
  9. # before the "real" debug stuff is setup. (hmm I could make this a two
  10. # stage, where we simulate a namespace to either be thrown away when the
  11. # time comes, or merge into the correct one)
  12. import debug # my debugging module
  13. debug.doDebugging(True) # open up debugging port
  14. # Modules to import, maybe config file or something?
  15. def tryloadmodule(mod):
  16. try:
  17. return __import__(mod)
  18. except ImportError:
  19. #import traceback
  20. #traceback.print_exc()
  21. pass
  22. # ZipStorage w/ tar support should be last as it will gobble up empty files.
  23. # These should be sorted by how much work they do, the least work the earlier.
  24. # mpegtsmod can be really expensive.
  25. modules = [
  26. 'shoutcast',
  27. 'Clip',
  28. 'pyvr',
  29. 'item',
  30. 'dvd',
  31. 'ZipStorage',
  32. 'mpegtsmod',
  33. ]
  34. modmap = {}
  35. for i in modules:
  36. modmap[i] = tryloadmodule(i)
  37. for i in modules:
  38. debug.insertnamespace(i, modmap[i])
  39. from FSStorage import FSDirectory
  40. import os
  41. import os.path
  42. import random
  43. import socket
  44. import string
  45. import urlparse
  46. from twisted.application import internet, service
  47. from twisted.python import usage
  48. def generateuuid():
  49. return ''.join([ 'uuid:'] + map(lambda x: random.choice(string.letters), xrange(20)))
  50. class Options(usage.Options):
  51. checkpath = True
  52. optParameters = [
  53. [ 'title', 't', 'My Media Server', 'Title of the server.', ],
  54. [ 'path', 'p', 'media', 'Root path of the media to be served.', ],
  55. ]
  56. def postOptions(self):
  57. p = self['path']
  58. if self.checkpath and not os.path.isdir(p):
  59. raise usage.UsageError, 'path %s does not exist' % `p`
  60. def parseArgs(self, *args):
  61. # XXX - twisted doesn't let you provide a message on what
  62. # arguments are required, so we will do our own work in here.
  63. if len(args) not in (1, 2):
  64. raise usage.UsageError, 'Arguments: addr [ port ]'
  65. self['addr'] = args[0]
  66. if len(args) == 1:
  67. port = random.randint(10000, 65000)
  68. else:
  69. port = int(args[1])
  70. if port < 1024 or port > 65535:
  71. raise ValueError(
  72. 'port must be between 1024 and 65535')
  73. self['port'] = port
  74. def fixupmimetypes():
  75. # Purely to ensure some sane mime-types. On MacOSX I need these.
  76. # XXX - There isn't any easier way to get to the mime-type dict
  77. # that I know of.
  78. from twisted.web import static
  79. medianode = static.File('pymediaserv')
  80. medianode.contentTypes.update( {
  81. # From: http://support.microsoft.com/kb/288102
  82. '.asf': 'video/x-ms-asf',
  83. '.asx': 'video/x-ms-asf',
  84. '.wma': 'audio/x-ms-wma',
  85. '.wax': 'audio/x-ms-wax',
  86. '.wmv': 'video/x-ms-wmv',
  87. '.wvx': 'video/x-ms-wvx',
  88. '.wm': 'video/x-ms-wm',
  89. '.wmx': 'video/x-ms-wmx',
  90. # From: http://www.matroska.org/technical/specs/notes.html
  91. '.mkv': 'video/x-matroska',
  92. '.mka': 'audio/x-matroska',
  93. #'.ts': 'video/mp2t',
  94. '.ts': 'video/mpeg', # we may want this instead of mp2t
  95. '.m2t': 'video/mpeg',
  96. '.m2ts': 'video/mpeg',
  97. '.mp4': 'video/mp4',
  98. #'.mp4': 'video/mpeg',
  99. '.dat': 'video/mpeg', # VCD tracks
  100. '.ogm': 'application/ogg',
  101. '.vob': 'video/mpeg',
  102. #'.m4a': 'audio/mp4', # D-Link can't seem to play AAC files.
  103. })
  104. def makeService(config):
  105. listenAddr = config['addr']
  106. listenPort = config['port']
  107. uuid = config.get('uuid', None)
  108. if uuid is None:
  109. uuid = generateuuid()
  110. urlbase = 'http://%s:%d/' % (listenAddr, listenPort)
  111. # Create SOAP server and content server
  112. from twisted.web import server, resource, static
  113. from ContentDirectory import ContentDirectoryServer
  114. from ConnectionManager import ConnectionManagerServer
  115. class WebServer(resource.Resource):
  116. def __init__(self):
  117. resource.Resource.__init__(self)
  118. class RootDevice(static.Data):
  119. def __init__(self):
  120. r = {
  121. 'hostname': socket.gethostname(),
  122. 'uuid': uuid,
  123. 'urlbase': urlbase,
  124. }
  125. d = file('root-device.xml').read() % r
  126. static.Data.__init__(self, d, 'text/xml')
  127. root = WebServer()
  128. debug.insertnamespace('root', root)
  129. content = resource.Resource()
  130. # This sets up the root to be the media dir so we don't have to
  131. # enumerate the directory.
  132. cds = ContentDirectoryServer(config['title'], klass=FSDirectory,
  133. path=config['path'], urlbase=urlparse.urljoin(urlbase, 'content'),
  134. webbase=content)
  135. debug.insertnamespace('cds', cds)
  136. root.putChild('ContentDirectory', cds)
  137. cds = cds.control
  138. root.putChild('ConnectionManager', ConnectionManagerServer())
  139. root.putChild('root-device.xml', RootDevice())
  140. root.putChild('content', content)
  141. fixupmimetypes()
  142. site = server.Site(root)
  143. # Create SSDP server
  144. from SSDP import SSDPServer, SSDP_PORT
  145. s = SSDPServer()
  146. debug.insertnamespace('s', s)
  147. class PyMedS(service.MultiService):
  148. def startService(self):
  149. service.MultiService.startService(self)
  150. rdxml = urlparse.urljoin(urlbase, 'root-device.xml')
  151. s.register('%s::upnp:rootdevice' % uuid,
  152. 'upnp:rootdevice', rdxml)
  153. s.register(uuid,
  154. uuid,
  155. rdxml)
  156. s.register('%s::urn:schemas-upnp-org:device:MediaServer:1' % uuid,
  157. 'urn:schemas-upnp-org:device:MediaServer:1', rdxml)
  158. s.register('%s::urn:schemas-upnp-org:service:ConnectionManager:1' % uuid,
  159. 'urn:schemas-upnp-org:device:ConnectionManager:1', rdxml)
  160. s.register('%s::urn:schemas-upnp-org:service:ContentDirectory:1' % uuid,
  161. 'urn:schemas-upnp-org:device:ContentDirectory:1', rdxml)
  162. def stopService(self):
  163. # Some reason stopProtocol isn't called
  164. s.doStop()
  165. service.MultiService.stopService(self)
  166. import pickle
  167. pickle.dump(cds, open('test.pickle', 'wb'), -1)
  168. serv = PyMedS()
  169. internet.TCPServer(listenPort, site).setServiceParent(serv)
  170. internet.MulticastServer(SSDP_PORT, s,
  171. listenMultiple=True).setServiceParent(serv)
  172. return serv