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.

398 lines
10 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2006 John-Mark Gurney <gurney_j@resnet.uoregon.edu>
  3. '''Shoutcast Radio Feed'''
  4. __version__ = '$Change$'
  5. # $Id$
  6. # The handling of defers and state in this module is not very good. It
  7. # needs some work to ensure that error cases are properly handled. What
  8. # do we do if we get no URLs for a PLS? Do we delete ourselves just to be
  9. # readded (when we get PLS refeshing working)? Do we set a content-length
  10. # to zero till we get one?
  11. import ConfigParser
  12. import StringIO
  13. import os.path
  14. import random
  15. import traceback
  16. from py_shoutcast import *
  17. from DIDLLite import Container, MusicGenre, Item, AudioItem, Resource
  18. from FSStorage import registerklassfun
  19. from twisted.protocols import shoutcast
  20. from twisted.python import log, threadable
  21. from twisted.internet import defer, protocol, reactor
  22. from twisted.web import error, http, resource, server
  23. from twisted.web.client import getPage, _parse
  24. PLSsection = 'playlist'
  25. def cmpStation(a, b, keys = ( 'MimeType', 'Name', 'PLS_URL', 'Bitrate' )):
  26. if filter(lambda k, x = a, y = b: x[k] != y[k], keys):
  27. return False
  28. return True
  29. def stationwbitratecmp(x, y):
  30. x, y = map(lambda a: a.title.split('-', 1)[1], (x, y))
  31. return cmp(x, y)
  32. class GenreFeedAsync(feeds.GenreFeed):
  33. genre_url = 'http://www.shoutcast.com/sbin/newxml.phtml'
  34. def __init__(self, *args, **kwargs):
  35. self.havegenre = False
  36. self.fetchinggenre = None
  37. feeds.GenreFeed.__init__(self, *args, **kwargs)
  38. def gotGenre(self, page):
  39. self.genre = page
  40. self.havegenre = True
  41. # Wake everyone up
  42. self.fetchinggenre.callback(1)
  43. def errGenre(self, failure):
  44. raise NotImplementedError, failure
  45. def fetch_genres(self):
  46. if self.havegenre:
  47. return self.genre
  48. if not self.fetchinggenre:
  49. # Need to start fetching
  50. getPage(self.genre_url.encode('ascii')) \
  51. .addCallbacks(self.gotGenre, self.errGenre)
  52. self.fetchinggenre = defer.Deferred()
  53. # Always raise this if we are waiting.
  54. raise self.fetchinggenre
  55. synchronized = ['fetch_genres', 'gotGenre', ]
  56. threadable.synchronize(GenreFeedAsync)
  57. class ShoutcastFeedAsync(feeds.ShoutcastFeed):
  58. def __init__(self, *args, **kwargs):
  59. feeds.ShoutcastFeed.__init__(self, *args, **kwargs)
  60. self.shout_url = \
  61. 'http://www.shoutcast.com/sbin/newxml.phtml?genre=' + \
  62. self.genre
  63. self.havestations = False
  64. self.fetchingstations = None
  65. def gotStations(self, page):
  66. self.stations = page
  67. self.havestations = True
  68. # Wake everyone up
  69. self.fetchingstations.callback(1)
  70. def errStations(self, failure):
  71. raise NotImplementedError, failure
  72. def fetch_stations(self):
  73. if self.havestations:
  74. return self.stations
  75. if not self.fetchingstations:
  76. # Need to start fetching
  77. getPage(self.shout_url.encode('ascii')) \
  78. .addCallbacks(self.gotStations, self.errStations)
  79. self.fetchingstations = defer.Deferred()
  80. # Always raise this if we are waiting.
  81. raise self.fetchingstations
  82. synchronized = ['fetch_stations', 'gotStations', ]
  83. threadable.synchronize(ShoutcastFeedAsync)
  84. class ShoutTransfer(shoutcast.ShoutcastClient):
  85. def __init__(self, request, passback):
  86. shoutcast.ShoutcastClient.__init__(self)
  87. self.request = request
  88. self.passback = passback
  89. request.registerProducer(self, 1)
  90. def connectionLost(self, reason):
  91. log.msg('connectionLost:', `self.request`, `self.passback`)
  92. shoutcast.ShoutcastClient.connectionLost(self, reason)
  93. if self.request:
  94. self.request.unregisterProducer()
  95. if self.passback:
  96. self.passback(self.request)
  97. self.passback = None
  98. self.request = None
  99. def handleResponse(self, response):
  100. #Drop the data, the parts get the important data, if we got
  101. #here, the connection closed and we are going to die anyways.
  102. pass
  103. def stopProducing(self):
  104. shoutcast.ShoutcastClient.stopProducing(self)
  105. self.request = None
  106. self.passback = None
  107. def gotMP3Data(self, data):
  108. self.request.write(data)
  109. def gotMetaData(self, data):
  110. log.msg("meta:", `data`)
  111. pass
  112. # Remotely relay producer interface.
  113. def view_resumeProducing(self, issuer):
  114. self.resumeProducing()
  115. def view_pauseProducing(self, issuer):
  116. self.pauseProducing()
  117. def view_stopProducing(self, issuer):
  118. self.stopProducing()
  119. synchronized = ['resumeProducing', 'stopProducing']
  120. threadable.synchronize(ShoutTransfer)
  121. class ShoutProxy(resource.Resource):
  122. # We should probably expire the PLS after a while.
  123. # setResponseCode(self, code, message=None)
  124. # setHeader(self, k, v)
  125. # write(self, data)
  126. # finish(self)
  127. isLeaf = True
  128. def __init__(self, url, mt):
  129. resource.Resource.__init__(self)
  130. self.shoutpls = url
  131. self.mt = mt
  132. self.urls = None
  133. self.fetchingurls = False
  134. def dump_exc(self):
  135. exc = StringIO.StringIO()
  136. traceback.print_exc(file=exc)
  137. exc.seek(0)
  138. self.request.setHeader('content-type', 'text/html')
  139. self.request.write(error.ErrorPage(http.INTERNAL_SERVER_ERROR,
  140. http.RESPONSES[http.INTERNAL_SERVER_ERROR],
  141. '<pre>%s</pre>' % exc.read()).render(self.request))
  142. self.request.finish()
  143. self.request = None
  144. def startNextConnection(self, request):
  145. url = self.urls[self.urlpos]
  146. self.urlpos = (self.urlpos + 1) % len(self.urls)
  147. scheme, host, port, path = _parse(url)
  148. protocol.ClientCreator(reactor, ShoutTransfer, request,
  149. self.startNextConnection).connectTCP(host, port)
  150. def triggerdefered(self, fun):
  151. map(fun, self.afterurls)
  152. self.afterurls = None
  153. def gotPLS(self, page):
  154. self.fetchingurls = False
  155. try:
  156. pls = ConfigParser.SafeConfigParser()
  157. pls.readfp(StringIO.StringIO(page))
  158. assert pls.getint(PLSsection, 'Version') == 2
  159. assert pls.has_option(PLSsection, 'numberofentries')
  160. cnt = pls.getint(PLSsection, 'numberofentries')
  161. self.urls = []
  162. for i in range(cnt):
  163. i += 1 # stupid one based arrays
  164. self.urls.append(pls.get(PLSsection,
  165. 'File%d' % i))
  166. self.urlpos = random.randrange(len(self.urls))
  167. except:
  168. self.dump_exc()
  169. self.urls = None
  170. self.triggerdefered(lambda x: x.errback(1))
  171. return
  172. self.triggerdefered(lambda x: x.callback(1))
  173. def errPLS(self, failure):
  174. self.fetchingurls = False
  175. self.triggerdefered(lambda x: x.errback(1))
  176. def processRequest(self, ign, request):
  177. self.startNextConnection(request)
  178. def errRequest(self, ign, request):
  179. request.write(failure.render(self.request))
  180. request.finish()
  181. def render(self, request):
  182. request.setHeader('content-type', self.mt)
  183. if request.method == 'HEAD':
  184. return ''
  185. # need to start the state machine
  186. # a) fetch the playlist
  187. # b) choose a random starting point
  188. # c) connect to the server
  189. # d) select next server and goto c
  190. # return data
  191. if self.urls is None:
  192. if not self.fetchingurls:
  193. # Get the PLS
  194. self.fetchingurls = True
  195. # Not really sure if ascii is the correct one,
  196. # shouldn't getPage do proper escaping for me?
  197. getPage(self.shoutpls.encode('ascii')) \
  198. .addCallbacks(self.gotPLS, self.errPLS)
  199. self.afterurls = [ defer.Deferred() ]
  200. else:
  201. self.afterurls.append(defer.Deferred())
  202. # Always add the callback if we don't have urls
  203. self.afterurls[-1].addCallbacks(self.processRequest,
  204. errback=self.errRequest, callbackArgs=(request, ),
  205. errbackArgs=(request, ))
  206. else:
  207. self.startNextConnection(request)
  208. # and make sure the connection doesn't get closed
  209. return server.NOT_DONE_YET
  210. synchronized = [ 'gotPLS', 'render', 'startNextConnection',
  211. 'triggerdefered', ]
  212. threadable.synchronize(ShoutProxy)
  213. class ShoutStation(AudioItem):
  214. def __init__(self, *args, **kwargs):
  215. self.station = kwargs['station']
  216. del kwargs['station']
  217. kwargs['content'] = ShoutProxy(self.station['PLS_URL'],
  218. self.station['MimeType'].encode('ascii'))
  219. AudioItem.__init__(self, *args, **kwargs)
  220. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  221. self.res = Resource(self.url, 'http-get:*:%s:*' % \
  222. self.station['MimeType'].encode('ascii'))
  223. self.bitrate = self.station['Bitrate'] * 128 # 1024k / 8bit
  224. class ShoutGenre(MusicGenre):
  225. def __init__(self, *args, **kwargs):
  226. self.genre = kwargs['genre']
  227. del kwargs['genre']
  228. self.feeds = ShoutcastFeedAsync(self.genre)
  229. self.sl = None
  230. self.pathObjmap = {}
  231. MusicGenre.__init__(self, *args, **kwargs)
  232. def genStations(self, stations):
  233. ret = {}
  234. dupcnt = {}
  235. for i in stations:
  236. name = i['Name']
  237. if name in ret:
  238. # got a dup
  239. if name not in dupcnt:
  240. dupcnt[name] = 2
  241. ret['%s - %d' % (name, dupcnt[name])] = i
  242. dupcnt[name] += 1
  243. else:
  244. ret[name] = i
  245. return ret
  246. def checkUpdate(self):
  247. self.doUpdate()
  248. return self
  249. def doUpdate(self):
  250. #traceback.print_stack(file=log.logfile)
  251. stations = self.feeds.parse_stations()
  252. if stations == self.sl:
  253. return
  254. nl = self.genStations(stations)
  255. doupdate = False
  256. for i in self.pathObjmap.keys():
  257. if i not in nl:
  258. # delete
  259. doupdate = True
  260. self.cd.delItem(self.pathObjmap[i])
  261. del self.pathObjmap[i]
  262. for name, i in nl.iteritems():
  263. if name in self.pathObjmap:
  264. if cmpStation(i, self.cd[self.pathObjmap[name]].station):
  265. continue
  266. # Didn't match, readd
  267. self.cd.delItem(self.pathObjmap[name])
  268. del self.pathObjmap[name]
  269. doupdate = True
  270. self.pathObjmap[name] = self.cd.addItem(self.id,
  271. ShoutStation, '%sk-%s' % (i['Bitrate'], name),
  272. station = i)
  273. self.sl = stations
  274. # sort our children
  275. self.sort(lambda *a: stationwbitratecmp(*a))
  276. if doupdate:
  277. Container.doUpdate(self)
  278. class ShoutCast(Container):
  279. def __init__(self, *args, **kwargs):
  280. Container.__init__(self, *args, **kwargs)
  281. self.genres = GenreFeedAsync()
  282. self.genre_list = None
  283. self.pathObjmap = {}
  284. def checkUpdate(self):
  285. self.doUpdate()
  286. return self
  287. def doUpdate(self):
  288. #traceback.print_stack(file=log.logfile)
  289. nl = self.genres.parse_genres()
  290. if nl == self.genre_list:
  291. return
  292. doupdate = False
  293. for i in self.pathObjmap.keys():
  294. if i not in nl:
  295. # delete
  296. doupdate = True
  297. self.cd.delItem(self.pathObjmap[i])
  298. del self.pathObjmap[i]
  299. for i in nl:
  300. if i in self.pathObjmap:
  301. continue
  302. doupdate = True
  303. self.pathObjmap[i] = self.cd.addItem(self.id,
  304. ShoutGenre, i, genre = i)
  305. self.genre_list = nl
  306. # sort our children
  307. self.sort(lambda x, y: cmp(x.title, y.title))
  308. if doupdate:
  309. Container.doUpdate(self)
  310. def detectshoutcastfile(path, fobj):
  311. path = os.path.basename(path)
  312. if path == 'SHOUTcast Radio':
  313. return ShoutCast, { }
  314. return None, None
  315. registerklassfun(detectshoutcastfile)