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

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