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.

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