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

playstreamproxy0.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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, quote
  13. import urllib,urlparse
  14. import requests
  15. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  16. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  17. HOST_NAME = ""
  18. PORT_NUMBER = 88
  19. LIVESTREAMER = None
  20. headers2dict = lambda h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
  21. sessions = {}
  22. class StreamHandler(BaseHTTPRequestHandler):
  23. def do_HEAD(self):
  24. self.send_response(200)
  25. self.send_header("Server", "StreamProxy")
  26. self.send_header("Content-type", "text/html")
  27. self.end_headers()
  28. def do_GET(self):
  29. """Respond to a GET request."""
  30. #self.send_header("Connection", "keep-alive")
  31. #Content-Type: video/mp4
  32. #self.end_headers()
  33. # http://localhost:88/hls?u=url.com/aaa/bbb.m3u8&h=headers&d=data
  34. # http://localhost:88/http://walterebert.com/playground/video/hls/ts/480x270.m3u8?token=xxxx|User-Agent=Enigma2|Cookie=xxxxx
  35. p = self.path.split("~")
  36. url = urllib.unquote(p[0][1:])
  37. headers = headers2dict("""
  38. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
  39. """)
  40. if len(p)>1:
  41. for h in p[1:]:
  42. headers[h.split("=")[0]]=urllib.unquote(h.split("=")[1])
  43. #self.fetch_offline(self.wfile)
  44. try:
  45. self.fetch_url(self.wfile, url, headers)
  46. except Exception as e:
  47. print "Got Exception: ", str(e)
  48. def fetch_offline(self,wfile):
  49. self.send_response(200)
  50. self.send_header("Server", "StreamProxy")
  51. self.send_header("Content-type", "video/mp4")
  52. self.end_headers()
  53. self.wfile.write(open("offline.mp4", "rb").read())
  54. self.wfile.close()
  55. def fetch_url(self, wfile, url, headers):
  56. self.log_message("fetch_url: %s", url)
  57. #self.log_message("headers: %s", headers)
  58. base_url = "/".join(url.split("/")[0:-1])
  59. if base_url not in sessions:
  60. sessions[base_url] = requests.Session()
  61. sessions[base_url].headers.update(headers)
  62. #print "request headers: ",sessions[base_url].headers
  63. r = sessions[base_url].get(url, stream=True,verify=False)
  64. self.send_response(int(r.status_code))
  65. self.send_header("Content-Type",r.headers["Content-Type"])
  66. for h in r.headers:
  67. if h in ("Content-Type","Server","Set-Cookie"):continue
  68. self.send_header(h, r.headers[h])
  69. #print h,"=",r.headers[h]
  70. self.end_headers()
  71. if r.status_code == 200:
  72. for chunk in r.iter_content(4096):
  73. try:
  74. wfile.write(chunk)
  75. except Exception as e:
  76. print "Exception: ", str(e)
  77. pass
  78. #print ".",
  79. #self.wfile.close()
  80. #print " url streaming finished"
  81. else:
  82. self.send_response(200)
  83. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  84. """Handle requests in a separate thread."""
  85. def start():
  86. #global LIVESTREAMER
  87. #LIVESTREAMER = Livestreamer()
  88. httpd = ThreadedHTTPServer((HOST_NAME, PORT_NUMBER), StreamHandler)
  89. print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
  90. try:
  91. httpd.serve_forever()
  92. except KeyboardInterrupt:
  93. pass
  94. httpd.server_close()
  95. print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
  96. class Daemon:
  97. """
  98. A generic daemon class.
  99. Usage: subclass the Daemon class and override the run() method
  100. """
  101. def __init__(self, pidfile, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
  102. self.stdin = stdin
  103. self.stdout = stdout
  104. self.stderr = stderr
  105. self.pidfile = pidfile
  106. def daemonize(self):
  107. """
  108. do the UNIX double-fork magic, see Stevens' "Advanced
  109. Programming in the UNIX Environment" for details (ISBN 0201563177)
  110. http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
  111. """
  112. try:
  113. pid = os.fork()
  114. if pid > 0:
  115. # exit first parent
  116. sys.exit(0)
  117. except OSError, e:
  118. sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
  119. sys.exit(1)
  120. # decouple from parent environment
  121. os.chdir("/")
  122. os.setsid()
  123. os.umask(0)
  124. # do second fork
  125. try:
  126. pid = os.fork()
  127. if pid > 0:
  128. # exit from second parent
  129. sys.exit(0)
  130. except OSError, e:
  131. sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
  132. sys.exit(1)
  133. # redirect standard file descriptors
  134. sys.stdout.flush()
  135. sys.stderr.flush()
  136. si = file(self.stdin, "r")
  137. so = file(self.stdout, "a+")
  138. se = file(self.stderr, "a+", 0)
  139. os.dup2(si.fileno(), sys.stdin.fileno())
  140. os.dup2(so.fileno(), sys.stdout.fileno())
  141. os.dup2(se.fileno(), sys.stderr.fileno())
  142. # write pidfile
  143. atexit.register(self.delpid)
  144. pid = str(os.getpid())
  145. file(self.pidfile,"w+").write("%s\n" % pid)
  146. def delpid(self):
  147. os.remove(self.pidfile)
  148. def start(self):
  149. """
  150. Start the daemon
  151. """
  152. # Check for a pidfile to see if the daemon already runs
  153. try:
  154. pf = file(self.pidfile,"r")
  155. pid = int(pf.read().strip())
  156. pf.close()
  157. except IOError:
  158. pid = None
  159. if pid:
  160. message = "pidfile %s already exist. Daemon already running?\n"
  161. sys.stderr.write(message % self.pidfile)
  162. sys.exit(1)
  163. # Start the daemon
  164. self.daemonize()
  165. self.run()
  166. def stop(self):
  167. """
  168. Stop the daemon
  169. """
  170. # Get the pid from the pidfile
  171. try:
  172. pf = file(self.pidfile,"r")
  173. pid = int(pf.read().strip())
  174. pf.close()
  175. except IOError:
  176. pid = None
  177. if not pid:
  178. message = "pidfile %s does not exist. Daemon not running?\n"
  179. sys.stderr.write(message % self.pidfile)
  180. return # not an error in a restart
  181. # Try killing the daemon process
  182. try:
  183. while 1:
  184. os.kill(pid, SIGTERM)
  185. time.sleep(0.1)
  186. except OSError, err:
  187. err = str(err)
  188. if err.find("No such process") > 0:
  189. if os.path.exists(self.pidfile):
  190. os.remove(self.pidfile)
  191. else:
  192. print str(err)
  193. sys.exit(1)
  194. def restart(self):
  195. """
  196. Restart the daemon
  197. """
  198. self.stop()
  199. self.start()
  200. def run(self):
  201. """
  202. You should override this method when you subclass Daemon. It will be called after the process has been
  203. daemonized by start() or restart().
  204. """
  205. class ProxyDaemon(Daemon):
  206. def run(self):
  207. start()
  208. if __name__ == "__main__":
  209. daemon = ProxyDaemon("/var/run/streamproxy.pid")
  210. if len(sys.argv) == 2:
  211. if "start" == sys.argv[1]:
  212. daemon.start()
  213. elif "stop" == sys.argv[1]:
  214. daemon.stop()
  215. elif "restart" == sys.argv[1]:
  216. daemon.restart()
  217. elif "manualstart" == sys.argv[1]:
  218. start()
  219. else:
  220. print "Unknown command"
  221. sys.exit(2)
  222. sys.exit(0)
  223. else:
  224. print "usage: %s start|stop|restart|manualstart" % sys.argv[0]
  225. sys.exit(2)