Enigma2 plugin to to play various online streams (mostly Latvian).

livestreamersrv.py 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #!/usr/bin/python
  2. """ Livestreamer Deamon """
  3. import os
  4. import sys
  5. import time
  6. import atexit
  7. import re
  8. from signal import SIGTERM
  9. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
  10. from SocketServer import ThreadingMixIn
  11. from livestreamer import Livestreamer
  12. from urllib import unquote
  13. HOST_NAME = ""
  14. PORT_NUMBER = 88
  15. LIVESTREAMER = None
  16. def Stream(wfile, url, quality):
  17. try:
  18. Streamer(wfile, url, quality)
  19. except Exception as e:
  20. print "Got Exception: ", str(e)
  21. wfile.write(open("offline.mp4", "r").read())
  22. wfile.close()
  23. def Streamer(wfile, url, quality):
  24. global LIVESTREAMER
  25. channel = LIVESTREAMER.resolve_url(url)
  26. streams = channel.get_streams()
  27. if not streams:
  28. raise Exception("No Stream Found!")
  29. print "Streams:", streams.keys()
  30. stream = streams[quality]
  31. if "rtmp" in stream.params:
  32. for p in re.findall(r"\+(\w+)(=([^\+]+))*",stream.params["rtmp"]): #
  33. if p[2]:
  34. stream.params[p[0]]=p[2]
  35. else:
  36. stream.params[p[0]]=True
  37. stream.params["rtmp"] = stream.params["rtmp"].split("+")[0]
  38. print str(stream)
  39. fd = stream.open()
  40. while True:
  41. buff = fd.read(4096)
  42. if not buff:
  43. raise Exception("No Data!")
  44. wfile.write(buff)
  45. fd.close()
  46. fd = None
  47. raise Exception("End Of Data!")
  48. class StreamHandler(BaseHTTPRequestHandler):
  49. def do_HEAD(s):
  50. s.send_response(200)
  51. s.s("Server", "Enigma2 Livestreamer")
  52. s.s("Content-type", "text/html")
  53. s.end_headers()
  54. def do_GET(s):
  55. """Respond to a GET request."""
  56. s.send_response(200)
  57. s.s("Server", "Enigma2 Livestreamer")
  58. s.s("Content-type", "text/html")
  59. s.end_headers()
  60. url=unquote(s.path[1:])
  61. quality="best"
  62. if url.startswith("q=") and url.index("/") > 0:
  63. i = url.index("/")
  64. quality = url[2:i]
  65. url = url[i+1:]
  66. s.log_message("URL: %s Quality: %s", url, quality)
  67. Stream(s.wfile, url, quality)
  68. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  69. """Handle requests in a separate thread."""
  70. def start():
  71. global LIVESTREAMER
  72. LIVESTREAMER = Livestreamer()
  73. httpd = ThreadedHTTPServer((HOST_NAME, PORT_NUMBER), StreamHandler)
  74. print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
  75. try:
  76. httpd.serve_forever()
  77. except KeyboardInterrupt:
  78. pass
  79. httpd.server_close()
  80. print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
  81. class Daemon:
  82. """
  83. A generic daemon class.
  84. Usage: subclass the Daemon class and override the run() method
  85. """
  86. def __init__(self, pidfile, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
  87. self.stdin = stdin
  88. self.stdout = stdout
  89. self.stderr = stderr
  90. self.pidfile = pidfile
  91. def daemonize(self):
  92. """
  93. do the UNIX double-fork magic, see Stevens' "Advanced
  94. Programming in the UNIX Environment" for details (ISBN 0201563177)
  95. http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
  96. """
  97. try:
  98. pid = os.fork()
  99. if pid > 0:
  100. # exit first parent
  101. sys.exit(0)
  102. except OSError, e:
  103. sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
  104. sys.exit(1)
  105. # decouple from parent environment
  106. os.chdir("/")
  107. os.setsid()
  108. os.umask(0)
  109. # do second fork
  110. try:
  111. pid = os.fork()
  112. if pid > 0:
  113. # exit from second parent
  114. sys.exit(0)
  115. except OSError, e:
  116. sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
  117. sys.exit(1)
  118. # redirect standard file descriptors
  119. sys.stdout.flush()
  120. sys.stderr.flush()
  121. si = file(self.stdin, "r")
  122. so = file(self.stdout, "a+")
  123. se = file(self.stderr, "a+", 0)
  124. os.dup2(si.fileno(), sys.stdin.fileno())
  125. os.dup2(so.fileno(), sys.stdout.fileno())
  126. os.dup2(se.fileno(), sys.stderr.fileno())
  127. # write pidfile
  128. atexit.register(self.delpid)
  129. pid = str(os.getpid())
  130. file(self.pidfile,"w+").write("%s\n" % pid)
  131. def delpid(self):
  132. os.remove(self.pidfile)
  133. def start(self):
  134. """
  135. Start the daemon
  136. """
  137. # Check for a pidfile to see if the daemon already runs
  138. try:
  139. pf = file(self.pidfile,"r")
  140. pid = int(pf.read().strip())
  141. pf.close()
  142. except IOError:
  143. pid = None
  144. if pid:
  145. message = "pidfile %s already exist. Daemon already running?\n"
  146. sys.stderr.write(message % self.pidfile)
  147. sys.exit(1)
  148. # Start the daemon
  149. self.daemonize()
  150. self.run()
  151. def stop(self):
  152. """
  153. Stop the daemon
  154. """
  155. # Get the pid from the pidfile
  156. try:
  157. pf = file(self.pidfile,"r")
  158. pid = int(pf.read().strip())
  159. pf.close()
  160. except IOError:
  161. pid = None
  162. if not pid:
  163. message = "pidfile %s does not exist. Daemon not running?\n"
  164. sys.stderr.write(message % self.pidfile)
  165. return # not an error in a restart
  166. # Try killing the daemon process
  167. try:
  168. while 1:
  169. os.kill(pid, SIGTERM)
  170. time.sleep(0.1)
  171. except OSError, err:
  172. err = str(err)
  173. if err.find("No such process") > 0:
  174. if os.path.exists(self.pidfile):
  175. os.remove(self.pidfile)
  176. else:
  177. print str(err)
  178. sys.exit(1)
  179. def restart(self):
  180. """
  181. Restart the daemon
  182. """
  183. self.stop()
  184. self.start()
  185. def run(self):
  186. """
  187. You should override this method when you subclass Daemon. It will be called after the process has been
  188. daemonized by start() or restart().
  189. """
  190. class LivestreamerDaemon(Daemon):
  191. def run(self):
  192. start()
  193. if __name__ == "__main__":
  194. daemon = LivestreamerDaemon("/var/run/livestream.pid")
  195. if len(sys.argv) == 2:
  196. if "start" == sys.argv[1]:
  197. daemon.start()
  198. elif "stop" == sys.argv[1]:
  199. daemon.stop()
  200. elif "restart" == sys.argv[1]:
  201. daemon.restart()
  202. elif "manualstart" == sys.argv[1]:
  203. start()
  204. else:
  205. print "Unknown command"
  206. sys.exit(2)
  207. sys.exit(0)
  208. else:
  209. print "usage: %s start|stop|restart|manualstart" % sys.argv[0]
  210. sys.exit(2)