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.

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