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

euronews.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/env python
  2. # coding=utf8
  3. #
  4. # This file is part of PlayStream - enigma2 plugin to play video streams from various sources
  5. # Copyright (c) 2016 ivars777 (ivars777@gmail.com)
  6. # Distributed under the GNU GPL v3. For full terms see http://www.gnu.org/licenses/gpl-3.0.en.html
  7. #
  8. try:
  9. import json
  10. except:
  11. import simplejson as json
  12. import urllib2, urllib
  13. import datetime, time,re, sys,os
  14. from collections import OrderedDict
  15. from SourceBase import SourceBase
  16. headers2dict = lambda h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
  17. import HTMLParser
  18. h = HTMLParser.HTMLParser()
  19. class Source(SourceBase):
  20. def __init__(self,language="en"):
  21. self.name = "euronews"
  22. self.title = "Euronews"
  23. self.img = "http://pbs.twimg.com/profile_images/732665354242150400/tZsCnjuh_400x400.jpg"
  24. self.desc = "Euronews live and archive"
  25. self.headers = headers2dict("""
  26. User-Agent: Euronews/4.0.126
  27. Content-Type: application/json
  28. Connection: keep-alive
  29. """)
  30. #self.language=language
  31. cur_directory = os.path.dirname(os.path.abspath(__file__))
  32. self.config_file = os.path.join(cur_directory,self.name+".cfg")
  33. self.options = OrderedDict([("language","en")])
  34. self.options_read()
  35. self.vid={"1": "News", "2": "European Affairs", "3": "Lifestyle", "4": "Knowledge"}
  36. self.languages = []
  37. try:
  38. self.get_languages()
  39. except:
  40. pass
  41. def login(self,user="",password=""):
  42. return True
  43. def get_content(self, data):
  44. print "[%s] get_content:"%self.name, data
  45. source,data,path,plist,clist,params,qs = self.parse_data(data)
  46. #lang = qs["lang"] if "lang" in qs else self.language
  47. lang = self.options["language"]
  48. if not lang in self.get_languages():
  49. raise Exception("Not valid default language - '%s'"%lang)
  50. content=[]
  51. content.append(("..return", "back","","Return back"))
  52. if clist=="home":
  53. content.extend([
  54. ("Search", "euronews::content/getSearch?lang=%s&byPage=40&page=1&text={0}"%lang,self.img,"Top stories timeline"),
  55. ("Live stream", "euronews::live?lang=%s"%lang,self.img,"Euronews live stream"),
  56. ("Just in", "euronews::content/getTimeline?lang=%s&byPage=40&page=1"%lang,self.img,"News timeline"),
  57. ("Top stories", "euronews::content/getTopStories?lang=%s"%lang,self.img,"Top stories timeline"),
  58. ("Category - News", "euronews::content/getVertical?lang=%s&byPage=40&page=1&vId=1"%lang,self.img,"Category - News"),
  59. ("Category - European Affairs", "euronews::content/getVertical?lang=%s&byPage=40&page=1&vId=2"%lang,self.img,"Category - European Affairs"),
  60. ("Category - Lifestyle", "euronews::content/getVertical?lang=%s&byPage=40&page=1&vId=3"%lang,self.img,"Category - Lifestyle"),
  61. ("Category - Knowledge", "euronews::content/getVertical?lang=%s&byPage=40&page=1&vId=4"%lang,self.img,"Category - Knowledge"),
  62. ("Latest programs", "euronews::content/getLatestPrograms?lang=%s&byPage=40&page=1"%lang,self.img,"Latest programs"),
  63. ("Programs list", "euronews::content/getPrograms?lang=%s"%lang,self.img,"Programs list"),
  64. ])
  65. return content
  66. ### Video arhīvs ###
  67. elif clist=="content":
  68. if "lang" in qs:
  69. del qs["lang"]
  70. params = json.dumps(qs)
  71. req = '{"methodName":"content.%s","apiKey":"androidPhoneEuronews-1.0","params":%s,"language":"%s"}'%(plist[1],params,lang)
  72. r = self.call(req)
  73. if not r:
  74. return content
  75. lst = r["timeline"] if "timeline" in r else\
  76. r["topstorieslist"] if "topstorieslist" in r else\
  77. r["programs"] if "programs" in r else\
  78. r["programDetailsList"] if "programDetailsList" in r else\
  79. r["programlist"] if "programlist" in r else\
  80. r["articlelist"] if "articlelist" in r else\
  81. r["verticals"] if "verticals" in r else\
  82. []
  83. if not lst:
  84. return content
  85. for item in lst:
  86. if plist[1] in ("getTimeline"):
  87. article = item["article"]
  88. atype = item["type"]
  89. #if item["type"] == "wire":
  90. #continue # TODO
  91. else:
  92. article = item
  93. atype = "article"
  94. if plist[1]=="getPrograms":
  95. title = article["title"]
  96. id = article["pId"]
  97. desc = title
  98. img = "http://static.euronews.com/articles/programs/533x360_%s"%article["img"]
  99. data2 = "content/getProgramDetails?lang=%s&byPage=40&page=1&pId=%s"%(lang,id)
  100. content.append((title,self.name+"::"+data2,img,desc))
  101. else:
  102. title = article["title"] if "title" in article else article["text"] if "text" in article else "No title"
  103. if atype <> "article":
  104. title = "[%s] %s"%(atype,title)
  105. atime = datetime.datetime.fromtimestamp(int(article["uts"]))
  106. #atime = datetime.datetime.fromtimestamp(int(article["uts"])-time.altzone)
  107. atime = atime.strftime("%Y-%m-%d %H:%M")
  108. vert = self.vid[article["vId"]] if "vId" in article else ""
  109. ptitle = article["pTitle"] if "pTitle" in article else ""
  110. id = article["id"]
  111. desc = "%s\n%s\n%s %s"%(title,atime,vert,ptitle)
  112. img = "http://static.euronews.com/articles/%s/399x225_%s.jpg"%(id,id)
  113. if not atype in ("breakingnews","wire"):
  114. data2 = "content/getArticle?lang=%s&id=%s"%(lang,id)
  115. else:
  116. data2 = ""
  117. content.append((title,self.name+"::"+data2,img,desc))
  118. if "page=" in data:
  119. data2 = re.sub("page=\d+","page=%s"%(int(qs["page"])+1),data)
  120. content.append(("Next page",self.name+"::"+data2,self.img,"Next page"))
  121. return content
  122. def is_video(self,data):
  123. source,data,path,plist,clist,params,qs = self.parse_data(data)
  124. if path == "live":
  125. return True
  126. elif clist=="content" and plist[1]=="getArticle":
  127. return True
  128. else:
  129. return False
  130. def get_streams(self, data):
  131. print "[euronews] get_streams:", data
  132. if not self.is_video(data):
  133. return []
  134. source,data,path,plist,clist,params,qs = self.parse_data(data)
  135. #lang = qs["lang"] if "lang" in qs else self.language
  136. lang = self.options["language"]
  137. if not lang in self.get_languages():
  138. raise Exception("Not valid default language - '%s'"%lang)
  139. streams = []
  140. if path == "live":
  141. url = "http://www.euronews.com/api/watchlive.json"
  142. r = self._http_request(url)
  143. try:
  144. js = json.loads(r)
  145. url = js["url"]
  146. except:
  147. raise Exception("No live stream found")
  148. r = self._http_request(url)
  149. try:
  150. js = json.loads(r)
  151. if not js["status"]=="ok":
  152. raise Exception("No live stream found")
  153. except:
  154. raise Exception("No live stream found")
  155. slist = js["primary"]
  156. for l in slist:
  157. stream = self.get_stream0()
  158. stream["url"]=slist[l]["hls"]
  159. stream["lang"]=l
  160. stream["quality"]="variant"
  161. stream["name"]="Euronews live [%s]"%l
  162. stream["desc"]=stream["name"]
  163. stream["type"]="hls" #stream_type(url)
  164. streams.append(stream)
  165. elif clist=="content" and plist[1] == "getArticle":
  166. if "lang" in qs:
  167. del qs["lang"]
  168. languages = self.get_languages()
  169. for lang in languages:
  170. id = qs["id"]
  171. req = '{"methodName":"content.getArticle","apiKey":"androidPhoneEuronews-1.0","params":{"id":"%s"},"language":"%s"}'%(id,lang)
  172. r = self.call(req)
  173. if not r:
  174. raise Exception("No live stream found")
  175. if not "articlelist" in r:
  176. msg = r["label"] if "label" in r else "No article finde"
  177. raise Exception(msg)
  178. article = r["articlelist"]
  179. stream = self.get_stream0()
  180. stream["url"]=article["videoUri"] if "videoUri" in article else ""
  181. if not stream["url"]:
  182. return []
  183. stream["lang"]=lang
  184. stream["quality"]="?"
  185. stream["name"]= article["title"]
  186. stream["desc"]=article["text"] if "text" in article else article["title"]
  187. stream["type"]="http" #stream_type(url)
  188. streams.append(stream)
  189. else:
  190. raise Exception("No live stream found")
  191. ### TODO - sakārtot sarakstu, lai pirmais ir labakais video
  192. qlist = ["???","lq","mq","hq","hd","variant"]
  193. llist = ["fr","en","ru","lv"]
  194. for s in streams:
  195. if s["lang"]==self.options["language"]:
  196. s["order"] = 10000
  197. continue
  198. lv = llist.index(s["lang"])*10 if s["lang"] in llist else 0
  199. qv=qlist.index(s["quality"]) if s["quality"] in qlist else 0
  200. s["order"] = lv+qv
  201. streams = sorted(streams,key=lambda item: item["order"],reverse=True)
  202. return streams
  203. def get_languages(self):
  204. if self.languages: return self.languages
  205. url = "http://www.euronews.com/api/watchlive.json"
  206. r = self._http_request(url)
  207. try:
  208. js = json.loads(r)
  209. url = js["url"]
  210. except:
  211. raise Exception("Can not get languages list")
  212. r = self._http_request(url)
  213. try:
  214. js = json.loads(r)
  215. if not js["status"]=="ok":
  216. raise Exception("Can not get languages list")
  217. except:
  218. raise Exception("Can not get languages list")
  219. slist = js["primary"]
  220. self.languages=slist.keys()
  221. return self.languages
  222. def call(self, data,params = None, headers=None):
  223. if not headers: headers = self.headers
  224. #if not lang: lang = self.country
  225. url = "http://api.euronews.com/ipad/"
  226. headers = headers2dict("""
  227. User-Agent: Euronews/4.0.126
  228. Content-Type: multipart/form-data, boundary=AaB03xBounDaRy; charset=UTF-8
  229. Host: api.euronews.com
  230. Connection: Keep-Alive
  231. """)
  232. params = """
  233. --AaB03xBounDaRy
  234. content-disposition: form-data; name=request
  235. %s
  236. --AaB03xBounDaRy--
  237. """%data
  238. content = self._http_request(url, params, headers)
  239. if content:
  240. try:
  241. result = json.loads(content)
  242. return result
  243. except Exception, ex:
  244. return None
  245. else:
  246. return None
  247. if __name__ == "__main__":
  248. language= "en"
  249. c = Source(language)
  250. data = '{"methodName":"content.getTimeline","apiKey":"androidPhoneEuronews-1.0","params":{"page":"1","byPage":"30"},"language":"en"}'
  251. r = c.call(data)
  252. if len(sys.argv)>1:
  253. data= sys.argv[1]
  254. else:
  255. data = "home"
  256. content = c.get_content(data)
  257. for item in content:
  258. print item
  259. pass