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.

206 lines
5.7 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 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. 'pyvr',
  28. 'dvd',
  29. 'ZipStorage',
  30. 'mpegtsmod',
  31. ]
  32. modmap = {}
  33. for i in modules:
  34. modmap[i] = tryloadmodule(i)
  35. for i in modules:
  36. debug.insertnamespace(i, modmap[i])
  37. from FSStorage import FSDirectory
  38. import os
  39. import os.path
  40. import random
  41. import socket
  42. import string
  43. import urlparse
  44. from twisted.application import internet, service
  45. from twisted.python import usage
  46. def generateuuid():
  47. return ''.join([ 'uuid:'] + map(lambda x: random.choice(string.letters), xrange(20)))
  48. class Options(usage.Options):
  49. checkpath = True
  50. optParameters = [
  51. [ 'title', 't', 'My Media Server', 'Title of the server.', ],
  52. [ 'path', 'p', 'media', 'Root path of the media to be served.', ],
  53. ]
  54. def postOptions(self):
  55. p = self['path']
  56. if self.checkpath and not os.path.isdir(p):
  57. raise usage.UsageError, 'path %s does not exist' % `p`
  58. def parseArgs(self, *args):
  59. # XXX - twisted doesn't let you provide a message on what
  60. # arguments are required, so we will do our own work in here.
  61. if len(args) not in (1, 2):
  62. raise usage.UsageError, 'Arguments: addr [ port ]'
  63. self['addr'] = args[0]
  64. if len(args) == 1:
  65. port = random.randint(10000, 65000)
  66. else:
  67. port = int(args[1])
  68. if port < 1024 or port > 65535:
  69. raise ValueError(
  70. 'port must be between 1024 and 65535')
  71. self['port'] = port
  72. def fixupmimetypes():
  73. # Purely to ensure some sane mime-types. On MacOSX I need these.
  74. # XXX - There isn't any easier way to get to the mime-type dict
  75. # that I know of.
  76. from twisted.web import static
  77. medianode = static.File('pymediaserv')
  78. medianode.contentTypes.update( {
  79. # From: http://support.microsoft.com/kb/288102
  80. '.asf': 'video/x-ms-asf',
  81. '.asx': 'video/x-ms-asf',
  82. '.wma': 'audio/x-ms-wma',
  83. '.wax': 'audio/x-ms-wax',
  84. '.wmv': 'video/x-ms-wmv',
  85. '.wvx': 'video/x-ms-wvx',
  86. '.wm': 'video/x-ms-wm',
  87. '.wmx': 'video/x-ms-wmx',
  88. # From: http://www.matroska.org/technical/specs/notes.html
  89. '.mkv': 'video/x-matroska',
  90. '.mka': 'audio/x-matroska',
  91. #'.ts': 'video/mp2t',
  92. '.ts': 'video/mpeg', # we may want this instead of mp2t
  93. '.m2t': 'video/mpeg',
  94. '.m2ts': 'video/mpeg',
  95. '.mp4': 'video/mp4',
  96. #'.mp4': 'video/mpeg',
  97. '.dat': 'video/mpeg', # VCD tracks
  98. '.ogm': 'application/ogg',
  99. '.vob': 'video/mpeg',
  100. #'.m4a': 'audio/mp4', # D-Link can't seem to play AAC files.
  101. })
  102. def makeService(config):
  103. listenAddr = config['addr']
  104. listenPort = config['port']
  105. uuid = config.get('uuid', None)
  106. if uuid is None:
  107. uuid = generateuuid()
  108. urlbase = 'http://%s:%d/' % (listenAddr, listenPort)
  109. # Create SOAP server and content server
  110. from twisted.web import server, resource, static
  111. from ContentDirectory import ContentDirectoryServer
  112. from ConnectionManager import ConnectionManagerServer
  113. class WebServer(resource.Resource):
  114. def __init__(self):
  115. resource.Resource.__init__(self)
  116. class RootDevice(static.Data):
  117. def __init__(self):
  118. r = {
  119. 'hostname': socket.gethostname(),
  120. 'uuid': uuid,
  121. 'urlbase': urlbase,
  122. }
  123. d = file('root-device.xml').read() % r
  124. static.Data.__init__(self, d, 'text/xml')
  125. root = WebServer()
  126. debug.insertnamespace('root', root)
  127. content = resource.Resource()
  128. # This sets up the root to be the media dir so we don't have to
  129. # enumerate the directory.
  130. cds = ContentDirectoryServer(config['title'], klass=FSDirectory,
  131. path=config['path'], urlbase=urlparse.urljoin(urlbase, 'content/'),
  132. webbase=content)
  133. debug.insertnamespace('cds', cds)
  134. root.putChild('ContentDirectory', cds)
  135. cds = cds.control
  136. root.putChild('ConnectionManager', ConnectionManagerServer())
  137. root.putChild('root-device.xml', RootDevice())
  138. root.putChild('content', content)
  139. fixupmimetypes()
  140. site = server.Site(root)
  141. # Create SSDP server
  142. from SSDP import SSDPServer, SSDP_PORT
  143. s = SSDPServer()
  144. debug.insertnamespace('s', s)
  145. class PyMedS(service.MultiService):
  146. def startService(self):
  147. service.MultiService.startService(self)
  148. rdxml = urlparse.urljoin(urlbase, 'root-device.xml')
  149. s.register('%s::upnp:rootdevice' % uuid,
  150. 'upnp:rootdevice', rdxml)
  151. s.register(uuid,
  152. uuid,
  153. rdxml)
  154. s.register('%s::urn:schemas-upnp-org:device:MediaServer:1' % uuid,
  155. 'urn:schemas-upnp-org:device:MediaServer:1', rdxml)
  156. s.register('%s::urn:schemas-upnp-org:service:ConnectionManager:1' % uuid,
  157. 'urn:schemas-upnp-org:device:ConnectionManager:1', rdxml)
  158. s.register('%s::urn:schemas-upnp-org:service:ContentDirectory:1' % uuid,
  159. 'urn:schemas-upnp-org:device:ContentDirectory:1', rdxml)
  160. def stopService(self):
  161. # Some reason stopProtocol isn't called
  162. s.doStop()
  163. service.MultiService.stopService(self)
  164. serv = PyMedS()
  165. internet.TCPServer(listenPort, site).setServiceParent(serv)
  166. internet.MulticastServer(SSDP_PORT, s,
  167. listenMultiple=True).setServiceParent(serv)
  168. return serv