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

viaplay.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 requests
  13. try:
  14. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  15. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  16. except:
  17. pass
  18. import urlparse, urllib
  19. import datetime, time,re, sys,os
  20. from collections import OrderedDict
  21. from SourceBase import SourceBase
  22. try:
  23. import util
  24. except:
  25. parent = os.path.dirname(os.path.abspath(__file__))
  26. parent = os.sep.join(parent.split(os.sep)[:-1])
  27. sys.path.insert(0,parent)
  28. import util
  29. headers2dict = lambda h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
  30. class Source(SourceBase):
  31. def __init__(self,language="en",cfg_path=None):
  32. self.name = "viaplay"
  33. self.title = "viaplay.lv"
  34. self.img = "https://yt3.ggpht.com/-noVdjbNR-V8/AAAAAAAAAAI/AAAAAAAAAAA/yZ9XNP5urLY/s900-c-k-no-mo-rj-c0xffffff/photo.jpg"
  35. self.desc = "Viaplay.lv saturs"
  36. self.url = "https://viaplay.lv/"
  37. self.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. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  40. Connection: keep-alive
  41. Upgrade-Insecure-Requests: 1
  42. """)
  43. #self.language=language
  44. cur_directory = os.path.dirname(os.path.abspath(__file__))
  45. if not cfg_path: cfg_path = cur_directory
  46. self.config_file = os.path.join(cfg_path,self.name+".cfg")
  47. self.options = OrderedDict([("user","change_user"),("password","change_password"),("device","")])
  48. self.options_read()
  49. self.device = self.options["device"]
  50. self.r = None # requests
  51. self.play_session = None
  52. self.s = None
  53. def login(self,user="",password=""):
  54. self.options_read()
  55. if not user: user=self.options["user"]
  56. if not password: password = self.options["password"]
  57. self.s = requests.Session()
  58. ### Dabu sesijas ID ===
  59. headers = headers2dict("""
  60. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
  61. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  62. Accept-Language: en-US,en;q=0.5
  63. Accept-Encoding: gzip, deflate, br
  64. Referer: https://viaplay.lv/
  65. Cookie: ott_cookies_confirmed=1;
  66. DNT: 1
  67. Connection: keep-alive
  68. Upgrade-Insecure-Requests: 1
  69. """)
  70. r = requests.get(self.url,headers=headers)
  71. if not "PLAY_SESSION" in r.cookies:
  72. return False
  73. self.play_session = r.cookies["PLAY_SESSION"]
  74. self.csrfToken = re.search("csrfToken=(.+)",self.play_session).group(1)
  75. ### Ielogojamies ###
  76. headers = headers2dict("""
  77. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
  78. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  79. Accept-Language: en-US,en;q=0.5
  80. Accept-Encoding: gzip, deflate, br
  81. Referer: https://viaplay.lv/
  82. Cookie: ott_cookies_confirmed=1; PLAY_SESSION=e618c42b377a65021298ff63309d5a907988ed1b-PSESSIONID=b010ea1b-fc5e-4a18-aa15-ebbe8b57b3f0&csrfToken=b4eb35263d9be16ef9f7b2f5d10a8ee99dfe75a8-1478051634814-63682b20f1e7e5579de6d056
  83. DNT: 1
  84. Connection: keep-alive
  85. Upgrade-Insecure-Requests: 1
  86. Content-Type: application/x-www-form-urlencoded
  87. """)
  88. url = "https://viaplay.lv/tdi/login/nav/form?csrfToken=%s"%self.csrfToken
  89. # https://viaplay.lv/tdi/login/nav/form?_infuse=1&_ts=1490554674901&csrfToken=
  90. params = "nav_redirectUri=https%3A%2F%2Fviaplay.lv%2F&nav_email={}&nav_password={}".format(urllib.quote(user),urllib.quote(password))
  91. # nav_redirectUri=https%3A%2F%2Fviaplay.lv%2F&nav_email=ivars777%40gmail.com&nav_password=kaskade7&nav_remember=true
  92. headers["Cookie"] = "ott_cookies_confirmed=1; PLAY_SESSION=%s;"%self.play_session
  93. if self.device:
  94. headers["Cookie"] += "ott_dids=%s"%self.device
  95. #cookie = dict(PLAY_SESSION=self.play_session,_hjIncludedInSample=1, mobileAppPromo="shown")
  96. r = requests.post(url,params,headers=headers,allow_redirects=False)
  97. if not "Set-Cookie" in r.headers:
  98. self.play_session = None
  99. return False
  100. if not "ott_web_sac" in r.cookies:
  101. self.play_session = None
  102. return False
  103. self.ott = r.cookies["ott_web_sac"]
  104. ### Dabu iekārtas ID ###
  105. if not self.device:
  106. headers = headers2dict("""
  107. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
  108. Accept: application/xml, text/xml, */*; q=0.01
  109. Accept-Language: en-US,en;q=0.5
  110. Accept-Encoding: gzip, deflate, br
  111. Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  112. X-Requested-With: XMLHttpRequest
  113. Referer: https://viaplay.lv/movies/me-and-earl-and-the-dying-girl
  114. DNT: 1
  115. Connection: keep-alive """)
  116. url = "https://viaplay.lv/tdi/account/device/create?_infuse=1&csrfToken=%s"%self.csrfToken
  117. params = "successRedirectUri=https%3A%2F%2Fviaplay.lv%2Fmovies%2F&slotId=&title=Enigma2"
  118. headers["Cookie"] = "PLAY_SESSION=%s; ott_cookies_confirmed=1; ott_web_sac=%s;"%(self.play_session,self.ott)
  119. #cookie = dict(PLAY_SESSION=self.play_session,_hjIncludedInSample=1, mobileAppPromo="shown")
  120. r = requests.post(url,params,headers=headers,allow_redirects=False)
  121. if not ("Set-Cookie" in r.headers and "ott_dids" in r.headers["Set-Cookie"]):
  122. self.play_session = None
  123. return False
  124. self.device = r.cookies["ott_dids"]
  125. self.options["device"] = self.device
  126. self.options_write(self.options)
  127. return True
  128. def logout(self):
  129. return True
  130. def is_logedin(self):
  131. if self.play_session:
  132. return True
  133. else:
  134. return False
  135. def get_video_info(self,vid):
  136. import demjson
  137. ### Dabu strimus ###
  138. headers = headers2dict("""
  139. Host: viaplay.lv
  140. User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46
  141. Accept: application/xml, text/xml, */*; q=0.01
  142. Accept-Language: en-US,en;q=0.5
  143. Accept-Encoding: gzip, deflate, br
  144. X-Requested-With: XMLHttpRequest
  145. DNT: 1
  146. Connection: keep-alive
  147. Referer: https://viaplay.lv/
  148. """)
  149. url = "https://viaplay.lv/prehravac/init?_infuse=1&productId=%s"%vid #t110623
  150. headers["Cookie"] = "ott_cookies_confirmed=1; ott_dids=%s; PLAY_SESSION=%s"%(self.device,self.play_session)
  151. r = requests.get(url,headers=headers,allow_redirects=False)
  152. statuss = re.search("<status>(.+?)</status>", r.content).group(1)
  153. if statuss.lower() <> "ok":
  154. raise Exception(statuss)
  155. #print r.content
  156. m = re.search(r"<!\[CDATA\[\s+var TDIPlayerOptions = (.+?);[\n\t\s]+\]\]>\s+</script>", r.content, re.DOTALL)
  157. if not m:
  158. raise "Can not find stream info"
  159. txt = m.group(1)
  160. txt = re.sub("// .+$", "", txt, flags=re.MULTILINE)
  161. #print txt
  162. #for m in re.finditer("// .+$", txt, re.MULTILINE):
  163. # txt = txt[:m.start()] + txt[m.end():]
  164. #print txt
  165. js = demjson.decode(txt)
  166. return js
  167. #return txt
  168. def get_content(self, data):
  169. print "[%s] get_content:"%self.name, data
  170. source,data,path,plist,clist,params,qs = self.parse_data(data)
  171. content=[]
  172. content.append(("..return", "back","","Return back"))
  173. if clist=="home":
  174. content.extend([
  175. ("Search", "viaplay::search-results-all?query={0}",self.img,"Meklēt"),
  176. ("Filmas", "viaplay::movies",self.img,"Filmas"),
  177. ("Seriāli", "viaplay::series",self.img,"Seriāli"),
  178. ("Bērniem", "viaplay::kids",self.img,"Bērniem"),
  179. ("Dokumentalās filmas", "viaplay::documentary",self.img,"Dokumentalās filmas"),
  180. ("Sports", "viaplay::live",self.img,"Sports"),
  181. ])
  182. return content
  183. ### Meklēt ###
  184. elif clist=="search-results-all":
  185. url = "https://viaplay.lv/"+data
  186. r = self._http_request(url)
  187. result = re.findall(r'<div id="product-(\w+)".+?<a href="([^"]+)">.+?<img data-srcset="([^ ]+).+?alt="([^"]+)">.+?<h3 class="is-size-h6">([^<]+)</h3>.*?<p>([^<]+).+?</p>.+?<p class="promo-notice">([^<]+)</p>.+?<p class="info">([^<]+)</p>', r, re.DOTALL)
  188. for item in result:
  189. vid = item[0]
  190. data2 = item[1].replace("https://viaplay.lv/","")
  191. img = item[2]
  192. ep = item[3]
  193. title= item[4]
  194. seas = item[5].replace("\n","").replace("\t","")
  195. desc = item[6]
  196. desc2 = item[7]
  197. if ep==title:
  198. title = "%s (%s)"%(title,seas)
  199. else:
  200. title = "%s - %s%s"%(title,seas,ep)
  201. desc = "%s\n%s\n%s"%(title,desc2,desc)
  202. content.append((title,self.name+"::"+data2,img,desc))
  203. return content
  204. ### Sadalas ##
  205. elif data in ["movies","series","kids","documentary"]:
  206. r = self._http_request(self.url+data)
  207. # https://viaplay.lv/tdi/movies/next?sections[]=MOVIES&genres[]=a3591&sort[]=latest&offset=0
  208. # https://viaplay.lv/tdi/series/next?sections[]=SERIES&sort[]=latest&offset=0
  209. # https://viaplay.lv/tdi/kids/next?sections[]=KIDS&cat[]=SERIES&cat[]=MOVIE&sort[]=latest&offset=18
  210. # https://viaplay.lv/kids?sections[]=KIDS&cat[]=SERIES&sort[]=latest
  211. sections = {"movies":"MOVIES","series":"SERIES","kids":"KIDS","documentary":"DOCUMENTS"}
  212. nosaukums = {"movies":"Flmas","series":"Seriāli","kids":"Bērnu","documentary":"Dokumentalās"}
  213. #availability = {"new":"jaunākās","last":"pēdējā iespēja"}
  214. sort = OrderedDict([("latest","jaunākais"),("title","pēc nosaukuma"),("popular","pēc popularitātes"),("year","pēc gada")])
  215. for s in sort:
  216. if data in ("movies","series"):
  217. title = "%s - %s"%(nosaukums[data],sort[s])
  218. data2 = "%s/next?sections[]=%s&sort[]=%s"%(data,sections[data],s)
  219. content.append((title,self.name+"::"+data2,self.img,title))
  220. else:
  221. title = "%s filmas - %s"%(nosaukums[data],sort[s])
  222. data2 = "%s/next?sections[]=%s&cat[]=MOVIE&sort[]=%s"%(data,sections[data],s)
  223. content.append((title,self.name+"::"+data2,self.img,title))
  224. title = "%s seriāli - %s"%(nosaukums[data],sort[s])
  225. data2 = "%s/next?sections[]=%s&cat[]=SERIES&sort[]=%s"%(data,sections[data],s)
  226. content.append((title,self.name+"::"+data2,self.img,title))
  227. # Pievienojam žanru sarakstu
  228. result = re.findall(r'name="genres\[\]" value="([^"]+)">.+?class="">([^<]+)</label>', r, re.DOTALL)
  229. for item in result:
  230. s = "latest"
  231. genre = item[1].replace("&amp;","&")
  232. title = "%s: %s"%(nosaukums[data],genre)
  233. data2 = "%s/next?sections[]=%s&genres[]=%s&sort[]=%s"%(data,sections[data],item[0],s)
  234. content.append((title,self.name+"::"+data2,self.img,title))
  235. return content
  236. ### Filmu/seriālu/sēriju saraksts ###
  237. elif clist in ("movies","series","kids","documentary") and plist[1] == "next":
  238. url = "https://viaplay.lv/tdi/"+data
  239. r = self._http_request(url)
  240. if clist == "series" and "season" in qs:
  241. result = re.findall(r'<div id="product-(\w+)".+?<a href="([^"]+)">.+?<img data-srcset="([^ ]+).+?alt="([^"]+)">.+?<h3 class="is-size-h6">([^<]+)</h3>.*?<p>([^<]+).+?</p>.+?<p class="promo-notice">([^<]+)</p>.+?<p class="info">([^<]+)</p>', r, re.DOTALL)
  242. for item in result:
  243. vid = item[0]
  244. data2 = item[1].replace("https://viaplay.lv/","")
  245. img = item[2]
  246. ep = item[3]
  247. title= item[4]
  248. seas = item[5]
  249. desc = item[6]
  250. desc2 = item[7]
  251. title = "%s - %s%s"%(title,seas,ep)
  252. desc = "%s\n%s\n%s"%(title,desc2,desc)
  253. content.append((title,self.name+"::"+data2,img,desc))
  254. else: # filmas
  255. result = re.findall(r'<div id="product-(\w+)".+?<a href="([^"]+)">.+?<img data-srcset="([^ ]+).+?alt="([^"]+)">.+?<p>([^<]+)</p>.+?<p class="promo-notice">([^<]+).+?<p class="is-strong detail">(.+?)</p>.+?<p class="info">([^<]+)</p>', r, re.DOTALL)
  256. for item in result:
  257. vid = item[0]
  258. data2 = item[1].replace("https://viaplay.lv/","")
  259. img = item[2]
  260. title = item[3]
  261. year = item[4]
  262. year = year.replace("\n","").replace("\t","")
  263. title = title +"(%s)"%year
  264. desc= item[5]
  265. genre = re.findall(">([^<]+)<", item[6], re.DOTALL)
  266. genre = ("".join(genre)).replace("&amp;","&")
  267. desc2 = item[7]
  268. desc = "%s\n%s\n%s"%(genre,desc2,desc)
  269. content.append((title,self.name+"::"+data2, img,desc))
  270. m = re.search(r"data\('href', 'https://viaplay\.lv/tdi/([^']+)'\)", r, re.DOTALL)
  271. if m:
  272. data2 = m.group(1)
  273. content.append(("Next page",self.name+"::"+data2,img,"Next page"))
  274. return content
  275. ### Seriāls ###
  276. elif clist == "series" and len(plist)==2:
  277. url = "https://viaplay.lv/"+data
  278. r = self._http_request(url)
  279. result = re.findall(r'<li>.*?<a class="tdi" href="https://viaplay\.lv/([^"]+)" data-related-ancestor="\.js-tdi-items-filter-and-items">([^<]+)</a>.*?</li>', r, re.DOTALL)
  280. for item in result:
  281. title = item[1]
  282. data2 = item[0]
  283. data2 = data2.replace("series/","series/next/")
  284. data2 = data2+"&sort[]=ord"
  285. #series/littlest-pet-shop?season=t6821
  286. #series/next/peppa-pig?season=t8430
  287. # &sort[]=ord
  288. if "availability=" in data2: continue
  289. content.append((title,self.name+"::"+data2,self.img,title)) #TODO bilde
  290. return content
  291. def is_video(self,data):
  292. source,data,path,plist,clist,params,qs = self.parse_data(data)
  293. if clist in ("movies","documentary","kids") and len(plist)>1 and plist[1]<>"next":
  294. return True
  295. elif clist == "series" and len(plist)>1 and plist[1] == "episode":
  296. return True
  297. else:
  298. return False
  299. def get_streams(self, data):
  300. print "[viaplay] get_streams:", data
  301. if not self.is_video(data):
  302. return []
  303. source,data,path,plist,clist,params,qs = self.parse_data(data)
  304. if not self.is_logedin():
  305. self.login()
  306. if not self.is_logedin():
  307. raise Exception("Could not login to viaplay.lv, check username/password in options")
  308. streams = []
  309. url = "https://viaplay.lv/"+data
  310. r = self._http_request(url)
  311. if clist in ("series","livestream"): # TODO nerāda overtime u.c.
  312. m = re.search(r'<h1 class="is-bottom-sticked is-size-h2">(.+?)</h1>.*?<h2 class="is-size-h4">.*?<p class="is-size-h6 is-strong is-bottom-sticked">(.+?)<div class="toggler-content">\s+<p>(.+?)</p>', r, re.DOTALL)
  313. if not m:
  314. raise Exception("Problem getting video information")
  315. title = m.group(1).replace("\n"," ").replace("\t","").strip()
  316. title = re.sub("<[^>]+>","",title).strip()
  317. desc2 = m.group(2).replace("\n"," ").replace("\t","").strip()
  318. desc2 = re.sub("<[^>]+>","",desc2).strip()
  319. desc = m.group(3)
  320. desc = "%s\n%s"%(desc2,desc)
  321. vid = re.search('data-productid="(\w+)"',r).group(1)
  322. else:
  323. m = re.search(r'<h1 class="is-strong is-bottom-sticked is-size-h2" jnp-id="(\w+)">([^<]+)</h1>.*?<h2 class="is-strong is-size-h4">([^<]+)</h2>.*?<p class="is-size-h6 is-strong is-bottom-sticked">(.+?)<div class="toggler-content">\s+<p>(.+?)</p>', r, re.DOTALL)
  324. if not m:
  325. raise Exception("Problem getting video information")
  326. title = m.group(2).strip()
  327. title2 = m.group(3).strip()
  328. title = "%s | %s"%(title,title2)
  329. desc = m.group(5).strip()
  330. desc2 = m.group(4).strip()
  331. desc2 = re.sub("<[^>]+>","",desc2)
  332. desc2 = desc2.replace("\n"," ").replace("\t","")
  333. desc = "%s\n%s"%(desc2,desc)
  334. vid = m.group(1)
  335. js = self.get_video_info(vid)
  336. #for m in re.finditer(r"lang: '(?P<lang>\w+)',\s+src: '(?P<url>[^']+)',\s+type: '(?P<mime>[^']+)',\s+drm: \[(?P<drm>.+?)\]\s*\}", r, re.DOTALL):
  337. if not js:
  338. return []
  339. tracks = js["tracks"]
  340. #if not tracks["HLS"]:
  341. # raise Exception("Encrypted DASH playing not yet implemented")
  342. captions = []
  343. llist = ["fr","en","ru","lv"]
  344. for st in js["plugins"]["settings"]["subtitles"]:
  345. sub = {}
  346. sub["url"] = st["src"]
  347. sub["lang"] = st["srclang"]
  348. sub["name"] = st["label"]
  349. sub["type"] = "vtt"
  350. sub["order"] = llist.index(sub["lang"])*10 if sub["lang"] in llist else 0
  351. captions.append(sub)
  352. captions = sorted(captions,key=lambda item: item["order"],reverse=True)
  353. for s in tracks["HLS"] if tracks["HLS"] else tracks["DASH"] :
  354. stype = "DASH" if "dash" in s["type"] else "HLS"
  355. if "drm" in s: ###
  356. # TODO, encrypted stream
  357. raise Exception("Can not play DRM protected stream!\nOnly local and Russian content available without DRM")
  358. continue
  359. url = s["src"]
  360. #urlp = util.streamproxy_encode(s["src"])
  361. stream = util.item()
  362. stream["url"]=url
  363. stream["resolver"] = "viaplay"
  364. stream["lang"]=s["lang"]
  365. stream["quality"]="variant"
  366. stream["bitrate"]= "1000000"
  367. stream["name"]= title
  368. stream["desc"]=desc
  369. stream["type"]=stype
  370. stream["subs"] = captions
  371. print url
  372. if stype=="DASH": streams.append(stream)
  373. if stype == "HLS": # izvelkam individuālos strimus
  374. r = requests.get(url)
  375. result = re.findall("#EXT-X-STREAM-INF:BANDWIDTH=(\d+),RESOLUTION=(\d+x\d+)\n(\w+.m3u8)", r.content)
  376. if not result:
  377. continue
  378. for s2 in result:
  379. ### TODO vajag lietot cookie ar tokenu no playlista requesta
  380. if "set-cookie" in r.headers:
  381. headers = {"Cookie":r.headers["set-cookie"]}
  382. else:
  383. headers={}
  384. #url2 = re.sub(r"(http.*://.+/)\w+.m3u8", r"\1"+s2[2], url)
  385. url2 = "/".join(url.split("/")[:-1])+"/"+s2[2]
  386. #r2 = requests.get(url2,headers=headers)
  387. #if "set-cookie" in r2.headers:
  388. #headers = {"Cookie":r2.headers["set-cookie"]}
  389. #else:
  390. #headers={}
  391. url2p=util.streamproxy_encode(url2,headers)
  392. stream = util.item()
  393. stream["url"]=url2p
  394. stream["lang"]=s["lang"]
  395. stream["quality"]="%s"%(s2[1])
  396. stream["name"]= title
  397. stream["desc"]=desc
  398. stream["bitrate"]=s2[0]
  399. stream["type"]="DASH" if "dash" in s["type"] else "HLS"
  400. streams.append(stream)
  401. ### TODO - sakārtot sarakstu, lai pirmais ir labakais video
  402. qlist = ["","512","640","758","1024","variant"]
  403. llist = ["lt","et","fr","en","ru","lv"]
  404. for s in streams:
  405. lv = llist.index(s["lang"])*10000000 if s["lang"] in llist else 0
  406. #qv=qlist.index(s["quality"]) if s["quality"] in qlist else 0
  407. qv = int(s["bitrate"]) if s["bitrate"] else 0
  408. s["order"] = lv+qv
  409. #print s["lang"],s["quality"],s["bitrate"],s["order"]
  410. streams = sorted(streams,key=lambda item: item["order"],reverse=True)
  411. return streams
  412. def call(self, data,params = None, headers=None):
  413. if not headers: headers = self.headers
  414. #if not lang: lang = self.country
  415. url = "https://viaplay.lv/tdi/" + data
  416. content = self._http_request(url, params, headers)
  417. return content
  418. if __name__ == "__main__":
  419. if len(sys.argv)>1:
  420. data= sys.argv[1]
  421. else:
  422. data = "kids/child-and-karlson"
  423. c = Source()
  424. print "login: %s"%c.login()
  425. if "/" in data:
  426. streams = c.get_streams(data)
  427. util.play_video(streams)
  428. else:
  429. vinfo = c.get_video_info(data)
  430. if "HLS" in vinfo["tracks"] and vinfo["tracks"]["HLS"]:
  431. url = vinfo["tracks"]["HLS"][0]["src"]
  432. urlp = util.streamproxy_encode(url)
  433. util.player(urlp)
  434. else:
  435. print "No HLS stream"
  436. sys.exit()
  437. r = requests.get("https://viaplay.lv/movies?sections[]=MOVIES")
  438. result = re.findall(r'<div id="product-(\w+)".+?<a href="([^"]+)">.+?<img data-srcset="([^ ]+).+?alt="([^"]+)">.+?<p class="promo-notice">([^<]+)<', r.content, re.DOTALL)
  439. for item in result:
  440. vid = item[0]
  441. url = item[1]
  442. img = item[2]
  443. title = item[3]
  444. desc= item[4]
  445. print "\n%s (%s):"%(title,vid)
  446. vinfo = c.get_video_info(vid)
  447. if "HLS" in vinfo["tracks"]:
  448. for s in vinfo["tracks"]["HLS"]:
  449. print "HLS %s: \n%s"%(s["lang"],s["src"])
  450. if "DASH" in vinfo["tracks"]:
  451. for s in vinfo["tracks"]["DASH"]:
  452. print "DASH %s: \n%s"%(s["lang"],s["src"])
  453. #except Exception,ex:
  454. #print ex.message
  455. #content = c.get_content(data)
  456. #for item in content:
  457. # print item
  458. pass