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.

193 lines
5.4 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. from twisted.application import internet, service
  44. from twisted.python import usage
  45. def generateuuid():
  46. if False:
  47. return 'uuid:asdflkjewoifjslkdfj'
  48. return ''.join([ 'uuid:'] + map(lambda x: random.choice(string.letters), xrange(20)))
  49. class Options(usage.Options):
  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 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 makeService(config):
  73. listenAddr = config['addr']
  74. listenPort = config['port']
  75. serv = service.MultiService()
  76. # Create SSDP server
  77. from SSDP import SSDPServer, SSDP_PORT
  78. s = SSDPServer()
  79. debug.insertnamespace('s', s)
  80. internet.MulticastServer(SSDP_PORT, s,
  81. listenMultiple=True).setServiceParent(serv)
  82. uuid = generateuuid()
  83. urlbase = 'http://%s:%d/' % (listenAddr, listenPort)
  84. # Create SOAP server and content server
  85. from twisted.web import server, resource, static
  86. from ContentDirectory import ContentDirectoryServer
  87. from ConnectionManager import ConnectionManagerServer
  88. class WebServer(resource.Resource):
  89. def __init__(self):
  90. resource.Resource.__init__(self)
  91. class RootDevice(static.Data):
  92. def __init__(self):
  93. r = {
  94. 'hostname': socket.gethostname(),
  95. 'uuid': uuid,
  96. 'urlbase': urlbase,
  97. }
  98. d = file('root-device.xml').read() % r
  99. static.Data.__init__(self, d, 'text/xml')
  100. root = WebServer()
  101. debug.insertnamespace('root', root)
  102. content = resource.Resource()
  103. # This sets up the root to be the media dir so we don't have to enumerate
  104. # the directory
  105. cds = ContentDirectoryServer(config['title'], klass=FSDirectory,
  106. path=config['path'], urlbase=os.path.join(urlbase, 'content'),
  107. webbase=content)
  108. debug.insertnamespace('cds', cds)
  109. root.putChild('ContentDirectory', cds)
  110. cds = cds.control
  111. root.putChild('ConnectionManager', ConnectionManagerServer())
  112. root.putChild('root-device.xml', RootDevice())
  113. root.putChild('content', content)
  114. # Purely to ensure some sane mime-types. On MacOSX I need these.
  115. # XXX - There isn't any easier way to get to the mime-type dict that I know of.
  116. medianode = static.File('pymediaserv')
  117. medianode.contentTypes.update( {
  118. # From: http://support.microsoft.com/kb/288102
  119. '.asf': 'video/x-ms-asf',
  120. '.asx': 'video/x-ms-asf',
  121. '.wma': 'audio/x-ms-wma',
  122. '.wax': 'audio/x-ms-wax',
  123. '.wmv': 'video/x-ms-wmv',
  124. '.wvx': 'video/x-ms-wvx',
  125. '.wm': 'video/x-ms-wm',
  126. '.wmx': 'video/x-ms-wmx',
  127. # From: http://www.matroska.org/technical/specs/notes.html
  128. '.mkv': 'video/x-matroska',
  129. '.mka': 'audio/x-matroska',
  130. #'.ts': 'video/mp2t',
  131. '.ts': 'video/mpeg', # we may want this instead of mp2t
  132. '.m2t': 'video/mpeg',
  133. '.m2ts': 'video/mpeg',
  134. '.mp4': 'video/mp4',
  135. #'.mp4': 'video/mpeg',
  136. '.dat': 'video/mpeg', # VCD tracks
  137. '.ogm': 'application/ogg',
  138. '.vob': 'video/mpeg',
  139. #'.m4a': 'audio/mp4', # D-Link can't seem to play AAC files.
  140. })
  141. del medianode
  142. site = server.Site(root)
  143. internet.TCPServer(listenPort, site).setServiceParent(serv)
  144. # we need to do this after the children are there, since we send notifies
  145. import urlparse
  146. rdxml = urlparse.urljoin(urlbase, 'root-device.xml')
  147. s.register('%s::upnp:rootdevice' % uuid,
  148. 'upnp:rootdevice', rdxml)
  149. s.register(uuid,
  150. uuid,
  151. rdxml)
  152. s.register('%s::urn:schemas-upnp-org:device:MediaServer:1' % uuid,
  153. 'urn:schemas-upnp-org:device:MediaServer:1', rdxml)
  154. s.register('%s::urn:schemas-upnp-org:service:ConnectionManager:1' % uuid,
  155. 'urn:schemas-upnp-org:device:ConnectionManager:1', rdxml)
  156. s.register('%s::urn:schemas-upnp-org:service:ContentDirectory:1' % uuid,
  157. 'urn:schemas-upnp-org:device:ContentDirectory:1', rdxml)
  158. return serv