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.

403 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. if self.transport is not None:
  105. shoutcast.ShoutcastClient.stopProducing(self)
  106. self.request = None
  107. self.passback = None
  108. def gotMP3Data(self, data):
  109. if self.request is not None:
  110. self.request.write(data)
  111. def gotMetaData(self, data):
  112. log.msg("meta:", `data`)
  113. pass
  114. # Remotely relay producer interface.
  115. def view_resumeProducing(self, issuer):
  116. self.resumeProducing()
  117. def view_pauseProducing(self, issuer):
  118. self.pauseProducing()
  119. def view_stopProducing(self, issuer):
  120. self.stopProducing()
  121. synchronized = ['resumeProducing', 'stopProducing']
  122. threadable.synchronize(ShoutTransfer)
  123. class ShoutProxy(resource.Resource):
  124. # We should probably expire the PLS after a while.
  125. # setResponseCode(self, code, message=None)
  126. # setHeader(self, k, v)
  127. # write(self, data)
  128. # finish(self)
  129. isLeaf = True
  130. def __init__(self, url, mt):
  131. resource.Resource.__init__(self)
  132. self.shoutpls = url
  133. self.mt = mt
  134. self.urls = None
  135. self.fetchingurls = False
  136. def dump_exc(self):
  137. exc = StringIO.StringIO()
  138. traceback.print_exc(file=exc)
  139. exc.seek(0)
  140. self.request.setHeader('content-type', 'text/html')
  141. self.request.write(error.ErrorPage(http.INTERNAL_SERVER_ERROR,
  142. http.RESPONSES[http.INTERNAL_SERVER_ERROR],
  143. '<pre>%s</pre>' % exc.read()).render(self.request))
  144. self.request.finish()
  145. self.request = None
  146. def startNextConnection(self, request):
  147. url = self.urls[self.urlpos]
  148. self.urlpos = (self.urlpos + 1) % len(self.urls)
  149. scheme, host, port, path = _parse(url)
  150. protocol.ClientCreator(reactor, ShoutTransfer, request,
  151. self.startNextConnection).connectTCP(host, port)
  152. def triggerdefered(self, fun):
  153. map(fun, self.afterurls)
  154. self.afterurls = None
  155. def gotPLS(self, page):
  156. self.fetchingurls = False
  157. try:
  158. pls = ConfigParser.SafeConfigParser()
  159. pls.readfp(StringIO.StringIO(page))
  160. assert pls.getint(PLSsection, 'Version') == 2
  161. assert pls.has_option(PLSsection, 'numberofentries')
  162. cnt = pls.getint(PLSsection, 'numberofentries')
  163. self.urls = []
  164. for i in range(cnt):
  165. i += 1 # stupid one based arrays
  166. self.urls.append(pls.get(PLSsection,
  167. 'File%d' % i))
  168. #log.msg('pls urls:', self.urls)
  169. self.urlpos = random.randrange(len(self.urls))
  170. except:
  171. self.dump_exc()
  172. self.urls = None
  173. self.triggerdefered(lambda x: x.errback(1))
  174. return
  175. self.triggerdefered(lambda x: x.callback(1))
  176. def errPLS(self, failure):
  177. self.fetchingurls = False
  178. self.triggerdefered(lambda x: x.errback(1))
  179. def processRequest(self, ign, request):
  180. self.startNextConnection(request)
  181. def errRequest(self, ign, request):
  182. request.write(failure.render(self.request))
  183. request.finish()
  184. def render(self, request):
  185. request.setHeader('content-type', self.mt)
  186. if request.method == 'HEAD':
  187. return ''
  188. # need to start the state machine
  189. # a) fetch the playlist
  190. # b) choose a random starting point
  191. # c) connect to the server
  192. # d) select next server and goto c
  193. # return data
  194. if self.urls is None:
  195. if not self.fetchingurls:
  196. # Get the PLS
  197. self.fetchingurls = True
  198. # Not really sure if ascii is the correct one,
  199. # shouldn't getPage do proper escaping for me?
  200. getPage(self.shoutpls.encode('ascii')) \
  201. .addCallbacks(self.gotPLS, self.errPLS)
  202. self.afterurls = [ defer.Deferred() ]
  203. else:
  204. self.afterurls.append(defer.Deferred())
  205. # Always add the callback if we don't have urls
  206. self.afterurls[-1].addCallbacks(self.processRequest,
  207. errback=self.errRequest, callbackArgs=(request, ),
  208. errbackArgs=(request, ))
  209. else:
  210. self.startNextConnection(request)
  211. # and make sure the connection doesn't get closed
  212. return server.NOT_DONE_YET
  213. synchronized = [ 'gotPLS', 'render', 'startNextConnection',
  214. 'triggerdefered', ]
  215. threadable.synchronize(ShoutProxy)
  216. class ShoutStation(AudioItem):
  217. def __init__(self, *args, **kwargs):
  218. self.station = kwargs['station']
  219. del kwargs['station']
  220. kwargs['content'] = ShoutProxy(self.station['PLS_URL'],
  221. self.station['MimeType'].encode('ascii'))
  222. AudioItem.__init__(self, *args, **kwargs)
  223. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  224. self.res = Resource(self.url, 'http-get:*:%s:*' % \
  225. self.station['MimeType'].encode('ascii'))
  226. #self.res = Resource(self.url + '/pcm', 'http-get:*:%s:*' % \
  227. # 'audio/x-wav')
  228. self.bitrate = self.station['Bitrate'] * 128 # 1024k / 8bit
  229. class ShoutGenre(MusicGenre):
  230. def __init__(self, *args, **kwargs):
  231. self.genre = kwargs['genre']
  232. del kwargs['genre']
  233. self.feeds = ShoutcastFeedAsync(self.genre)
  234. self.sl = None
  235. self.pathObjmap = {}
  236. MusicGenre.__init__(self, *args, **kwargs)
  237. def genStations(self, stations):
  238. ret = {}
  239. dupcnt = {}
  240. for i in stations:
  241. name = i['Name']
  242. if name in ret:
  243. # got a dup
  244. if name not in dupcnt:
  245. dupcnt[name] = 2
  246. ret['%s - %d' % (name, dupcnt[name])] = i
  247. dupcnt[name] += 1
  248. else:
  249. ret[name] = i
  250. return ret
  251. def checkUpdate(self):
  252. self.doUpdate()
  253. return self
  254. def doUpdate(self):
  255. #traceback.print_stack(file=log.logfile)
  256. stations = self.feeds.parse_stations()
  257. if stations == self.sl:
  258. return
  259. nl = self.genStations(stations)
  260. doupdate = False
  261. for i in self.pathObjmap.keys():
  262. if i not in nl:
  263. # delete
  264. doupdate = True
  265. self.cd.delItem(self.pathObjmap[i])
  266. del self.pathObjmap[i]
  267. for name, i in nl.iteritems():
  268. if name in self.pathObjmap:
  269. if cmpStation(i, self.cd[self.pathObjmap[name]].station):
  270. continue
  271. # Didn't match, readd
  272. self.cd.delItem(self.pathObjmap[name])
  273. del self.pathObjmap[name]
  274. doupdate = True
  275. self.pathObjmap[name] = self.cd.addItem(self.id,
  276. ShoutStation, '%sk-%s' % (i['Bitrate'], name),
  277. station = i)
  278. self.sl = stations
  279. # sort our children
  280. self.sort(lambda *a: stationwbitratecmp(*a))
  281. if doupdate:
  282. Container.doUpdate(self)
  283. class ShoutCast(Container):
  284. def __init__(self, *args, **kwargs):
  285. Container.__init__(self, *args, **kwargs)
  286. self.genres = GenreFeedAsync()
  287. self.genre_list = None
  288. self.pathObjmap = {}
  289. def checkUpdate(self):
  290. self.doUpdate()
  291. return self
  292. def doUpdate(self):
  293. #traceback.print_stack(file=log.logfile)
  294. nl = self.genres.parse_genres()
  295. if nl == self.genre_list:
  296. return
  297. doupdate = False
  298. for i in self.pathObjmap.keys():
  299. if i not in nl:
  300. # delete
  301. doupdate = True
  302. self.cd.delItem(self.pathObjmap[i])
  303. del self.pathObjmap[i]
  304. for i in nl:
  305. if i in self.pathObjmap:
  306. continue
  307. doupdate = True
  308. self.pathObjmap[i] = self.cd.addItem(self.id,
  309. ShoutGenre, i, genre = i)
  310. self.genre_list = nl
  311. # sort our children
  312. self.sort(lambda x, y: cmp(x.title, y.title))
  313. if doupdate:
  314. Container.doUpdate(self)
  315. def detectshoutcastfile(path, fobj):
  316. path = os.path.basename(path)
  317. if path == 'SHOUTcast Radio':
  318. return ShoutCast, { }
  319. return None, None
  320. registerklassfun(detectshoutcastfile)