Python module (submodule repositary), which provides content (video streams) from various online stream sources to corresponding Enigma2, Kodi, Plex plugins

ltc.py 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. import sys, os, os.path, re, sys
  9. import urllib,urllib2,urlparse
  10. #from xml.sax.saxutils import unescape,escape
  11. from urllib import quote, unquote
  12. import datetime
  13. import HTMLParser
  14. import json
  15. import datetime
  16. from SourceBase import SourceBase, stream_type
  17. import util
  18. from util import unescape
  19. from collections import OrderedDict
  20. import ssl
  21. if "_create_unverified_context" in dir(ssl):
  22. ssl._create_default_https_context = ssl._create_unverified_context
  23. user_agent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; da-dk) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3"
  24. headers2dict = lambda h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
  25. h = HTMLParser.HTMLParser()
  26. class Source(SourceBase):
  27. def __init__(self,cfg_path=None):
  28. self.name = "ltc"
  29. self.title = "Shortcut.lv (lattelecom.tv)"
  30. self.img = "shortcut.png"
  31. self.desc = "Shortcut.lv (lattelecom.tv) satura skatīšanās"
  32. self.token = "" # manstv.lattelecom.tv
  33. self.session_id = "" # www.shortcut.lv
  34. self.api_url = "https://manstv.lattelecom.tv/api/v1.4/get/"
  35. self.api_url2 = "https://www.shortcut.lv/"
  36. self.headers = headers2dict("""
  37. User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
  38. Host: manstv.lattelecom.tv
  39. Connection: Keep-Alive
  40. """)
  41. self.headers2 = headers2dict("""
  42. Connection: keep-alive
  43. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  44. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  45. Accept-Language: en-US,en;q=0.8
  46. """)
  47. self.channels = None
  48. ### specific service info ###
  49. self.ch = []
  50. self.ch2 = []
  51. self.ch_id={}
  52. self.ch_id2={}
  53. self.ch_name={}
  54. self.epg=[]
  55. self.epg_id={}
  56. self.epg_id2={}
  57. self.epg_date={}
  58. self.epg_ch={}
  59. self.epgdates = []
  60. self.today = datetime.date.today()
  61. self.today2 = self.today.strftime("%d.%m.%Y")
  62. cur_directory = os.path.dirname(os.path.abspath(__file__))
  63. if not cfg_path: cfg_path = cur_directory
  64. self.config_file = os.path.join(cfg_path,self.name+".cfg")
  65. self.options = OrderedDict([("user","lietotajs"),("password","parole")])
  66. self.options_read()
  67. def get_content(self, data):
  68. print "[ltc] get_content:", data
  69. source, data, path, plist, clist, params, qs = self.parse_data(data)
  70. content=[]
  71. content.append(("..return", "back","back.png","Return back"))
  72. if clist=="home":
  73. content.extend([
  74. #("Meklēt TV arhīvā", "ltc::search/{0}","","Meklēt TV arhīvā"), #TODO
  75. ("Meklēt filmas", "ltc::viss/search/?cat=movies&q={0}","","Meklēt filmu sadaļā"),
  76. ("Meklēt seriālus", "ltc::viss/search/?cat=series&q={0}","","Meklēt seriālu sadaļā"),
  77. ("TV tiešraides", "ltc::tiesraide","","TV tiesraides"),
  78. ("TV arhīvs", "ltc::arhivs","","TV arhīvs atseviškiem kanāliem"),
  79. ("Videonoma", "ltc::videonoma","","Filmas (ari Priemiere) un seriāli"),
  80. ])
  81. return content
  82. ### Meklēt TV (1.4 API)
  83. elif clist == "search": #TODO vod/search/{q}
  84. #r = self.call("vod/"+data)
  85. return content
  86. ### Meklēsana video (www )###
  87. elif path == 'viss/search/': #TODO vod/search/{q}
  88. r = self.call2(data)
  89. if "cat=movies" in data:
  90. result = re.findall('class="forward-link" href="/([^"]+)">(<div class="new-movie">Premiere</div>)*<img src="([^"]+)".+?class="categorie-one-title">([^<]+)<', r, re.MULTILINE)
  91. else:
  92. result = re.findall('class="forward-link" href="/([^"]+)">(<div class="new-movie">Premiere</div>)*<img src="([^"]+)".+?class="categorie-one-title">([^<]+)<', r, re.MULTILINE)
  93. for item in result:
  94. title = item[3]
  95. if not item[1]:
  96. title = title + "[P]"
  97. data2 = item[0][0:-1]
  98. img = "https://www.shortcut.lv" + item[2]
  99. desc = title
  100. content.append((title,self.name+"::"+data2,img,desc))
  101. return content
  102. ### Tiešraides kanānālu saraksts ###
  103. elif data=="tiesraide":
  104. #r = self.call2(data)
  105. #m = re.search("var xprs_ides_array = (.+);", r, re.MULTILINE)
  106. #if m:
  107. # js=json.loads(m.group(1))
  108. #else:
  109. # raise Exception("Error reading channel list")
  110. r = self.call2("program-snippet.json")
  111. try:
  112. js = json.loads(r)
  113. except:
  114. js = {}
  115. for item in self.get_channels():
  116. if item["live"]=='0':continue
  117. title = item["name"]
  118. data2 = "content/live-streams/%s?include=quality"%item["id"]
  119. if item["xprs_id"] in js:
  120. epg = js[item["xprs_id"]]
  121. desc = "%s - %s (%s-%s)"%(title,epg[0]["t"],epg[0]["hs"],epg[0]["he"])
  122. #img = "https://www.shortcut.lv" + epg[0]["p"]
  123. img = "https://manstv.shortcut.lv/"+ item['broadcast_default_picture']
  124. else:
  125. img = "https://manstv.shortcut.lv/"+ item['broadcast_default_picture']
  126. desc = title
  127. content.append((title,self.name+"::"+data2,img,desc))
  128. return content
  129. ### TV arhīva sākums ###
  130. elif data=="archive" or data=="arhivs":
  131. #self.get_epg()
  132. content.extend([
  133. ("Archive - categories", "ltc::archive/categories","","TV live archive by categories"),
  134. ("Archive - channels", "ltc::archive/channels","","TV live archive by channels"),
  135. #("Archive - dates", "ltc::archive/dates","","TV live archive by dates"),
  136. ])
  137. return content
  138. ### Arhīva kategorijas
  139. elif data=="archive/categories":
  140. #https://manstv.lattelecom.tv/api/v1.3/get/archive/records/?filter[category]=13&limit=10&until_id=1458681019238
  141. #https://manstv.lattelecom.tv/api/v1.3/get/archive/categories/
  142. r = self.call(data)
  143. for item in r["items"]:
  144. title = item["name"]
  145. data2 = "archive/records?filter[category]=%s&limit=40"%item["id"]
  146. img = "https://manstv.lattelecom.tv/"+ item['image']
  147. desc = title
  148. content.append((title,self.name+"::"+data2,img,desc))
  149. return content
  150. ### Arhīva kategoriju video
  151. elif "archive/records" in data:
  152. #https://manstv.lattelecom.tv/api/v1.3/get/archive/records/?filter[category]=13&limit=10&until_id=1458681019238
  153. #https://manstv.lattelecom.tv/api/v1.3/get/archive/categories/
  154. r = self.call(data)
  155. for i,item in enumerate(r["items"]):
  156. #if not item["is_archive"]==u"1":continue # TODO jānočeko, kurs no atributiem apzīmē, ka ir arhīvs
  157. if not self.epg_id.has_key(item["id"]):
  158. item["time_start2"] = datetime.datetime.fromtimestamp(int(item["unix_start"]))
  159. item["time_stop2"] = datetime.datetime.fromtimestamp(int(item["unix_stop"]))
  160. item["date"]=item["time_start2"].strftime("%Y-%m-%d")
  161. self.epg.append(item)
  162. index = self.epg.index(item)
  163. self.epg_id[item["id"]]=index
  164. if not item["date"] in self.epg_date:
  165. self.epg_date[item["date"]]=[]
  166. self.epg_date[item["date"]].append(index)
  167. if not item["channel_id"] in self.epg_ch:
  168. self.epg_ch[item["channel_id"]]=[]
  169. self.epg_ch[item["channel_id"]].append(index)
  170. item = self.get_epg_id(item["id"])
  171. ch = self.get_channel_by_id2(item["channel_id"])
  172. ch_name = ch["name"] if ch else item["channel_id"]
  173. title = u"[%s %s-%s] %s - %s"%(item["date"],item["time_start2"].strftime("%H:%M"),item["time_stop2"].strftime("%H:%M"),ch_name,item["title"])
  174. #data2 = "archive/get-stream/%s?channelid=%s"%(item["id"],ch["id"])
  175. data2 = "content/record-streams/%s?include=quality"%item["id"]
  176. img = "https://manstv.lattelecom.tv/"+ item["url"]
  177. desc = u"%s - %s\n%s - %s\n%s\n%s"%(ch_name,item["title"],item["time_start"],item["time_stop"],
  178. item["category1"],item["description"])
  179. content.append((title,self.name+"::"+data2,img,desc))
  180. if "until_id" in data:
  181. data2 = re.sub("until_id=\d+","until_id="+item["id"],data)
  182. else:
  183. data2 = data + "&until_id=%s"%item["id"]
  184. content.append(("Next page",self.name+"::"+data2,"","Go to next page"))
  185. return content
  186. ### Arhīva kanānālu saraksts
  187. elif data=="archive/channels":
  188. for item in self.get_channels():
  189. if not item["is_archive"]==u"1":continue
  190. title = item["name"]
  191. data2 = "archive/channel/%s?date=%s"%(item["id"],self.today.strftime("%Y-%m-%d"))
  192. img = "https://manstv.lattelecom.tv/"+ item['broadcast_default_picture']
  193. desc = title
  194. content.append((title,self.name+"::"+data2,img,desc))
  195. return content
  196. ### Arhīva kanānāla video saraksta
  197. elif "archive/channel/" in data:
  198. chid = path.split("/")[2]
  199. for item in self.get_epg_date(qs["date"],chid):
  200. #if item["is_archive"]=='0':continue
  201. ch = self.get_channel_by_id2(item["channel_id"])
  202. ch_name = ch["name"] if ch else item["channel_id"]
  203. title = u"[%s %s-%s] %s - %s"%(item["date"],item["time_start2"].strftime("%H:%M"),item["time_stop2"].strftime("%H:%M"),ch_name,item["title"])
  204. #data2 = "archive/get-stream/%s?channelid=%s"%(item["id"],ch["id"])
  205. data2 = "content/record-streams/%s?include=quality"%item["id"]
  206. img = "https://manstv.lattelecom.tv/"+ item["url"]
  207. desc = u"%s - %s\n%s - %s\n%s\n%s"%(ch_name,item["title"],item["time_start"],item["time_stop"],
  208. item["category1"],item["description"])
  209. content.append((title,self.name+"::"+data2,img,desc))
  210. date2=datetime.datetime.strptime(qs["date"], '%Y-%m-%d').date()-datetime.timedelta(days=1)
  211. date2 = date2.strftime("%Y-%m-%d")
  212. if "date=" in data:
  213. data2 = re.sub("date=[\d-]+","date="+date2,data)
  214. else:
  215. data2 = data + "&date=%s"%date2
  216. content.append(("Previous day (%s)"%date2,self.name+"::"+data2,"","Go previous day"))
  217. return content
  218. ### Arhīva datumi
  219. elif clist=="arhivs" and len(data.split("/"))==2: # TODO - pasreiz nestrada
  220. ch = data.split("/")[1]
  221. r= self.call(data)
  222. m = re.search('class="spac no_select">([^<]+)</span>', r, re.IGNORECASE)
  223. if m:
  224. ch_name = m.group(1)
  225. else:
  226. ch_name = ""
  227. today = datetime.date.today()
  228. for i in range(7):
  229. date = today-datetime.timedelta(i)
  230. title = ch_name + " - " + date.strftime("%d.%m.%Y")
  231. data2 = "%s/%s"%(data,date.strftime("%Y-%m-%d"))
  232. img = ""
  233. desc = title
  234. content.append((title,self.name+"::"+data2,img,desc))
  235. return content
  236. ### Arhīva dienas raidijumi
  237. elif clist=="arhivs" and len(data.split("/"))==3: # TODO - nestrādā
  238. ch = data.split("/")[1]
  239. date = data.split("/")[2]
  240. r= self.call(data)
  241. m = re.search('class="spac no_select">([^<]+)</span>', r, re.IGNORECASE)
  242. if m:
  243. ch_name = m.group(1)
  244. else:
  245. ch_name = ""
  246. for item in re.findall('(?i)href="/([^"]+?)" id="" class="archive_programm_a"><div class="archive_programm "><div class="chanel_time"><span>([^<]+)</span></div><div class="archive_programm_one"><span>([^<]+)', r):
  247. title = "%s - %s"%(item[1],item[2])
  248. data2 = item[0]
  249. img = ""
  250. desc = "%s (%s)\n%s"%(ch_name,date,title)
  251. content.append((title,self.name+"::"+data2,img,desc))
  252. return content
  253. ### Videonoma galvenā
  254. elif data=="videonoma":
  255. content.extend([
  256. ("Filmas - jaunākās", "ltc::videonoma?page=0&genre=all_movies&sorts=laiks&cnt=40&clear=true&filter={}","https://www.shortcut.lv/media/features/2013-12-17/aa3b_videonoma_dropdown_filmas.png","Jaunākās filmas"),
  257. ("Filmas - pēc nosaukuma", "ltc::videonoma?page=0&genre=all_movies&sorts=title&cnt=40&clear=true&filter={}","https://www.shortcut.lv/media/features/2013-12-17/aa3b_videonoma_dropdown_filmas.png","Filmas pēc nosaukuma"),
  258. ("Filmas - latviski", 'ltc::videonoma?page=0&genre=all_movies&sorts=laiks&cnt=40&clear=true&filter={"valoda":["lv"]}',"https://www.shortcut.lv/media/features/2013-12-17/aa3b_videonoma_dropdown_filmas.png","Filmas latviešu valodā"),
  259. ("Filmas - pēc reitinga", "ltc::videonoma?page=0&genre=all_movies&sorts=imbd&cnt=40&clear=true&filter={}","https://www.shortcut.lv/media/features/2013-12-17/aa3b_videonoma_dropdown_filmas.png","Filmas pēc IMBD reitinga"),
  260. ("Filmas bērniem - jaunākās", "ltc::videonoma?page=0&genre=3&sorts=laiks&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_berniem.png","Jaunākie bernu video"),
  261. ("Filmas bērniem - pēc nosaukuma", "ltc::videonoma?page=0&genre=3&sorts=title&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_berniem.png","Bērnu video pēc nosaukuma"),
  262. ("Filmas bērniem - latviski", 'ltc::videonoma?page=0&genre=3&sorts=laiks&cnt=40&clear=true&filter={"valoda":[\"lv\"]}',"https://www.shortcut.lv/images/redesign/videonoma_dropdown_berniem.png","Bērnu video latviski"),
  263. ("Filmas bērniem - pēc reitinga", "ltc::videonoma?page=0&genre=3&sorts=imbd&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_berniem.png","Bērnu video pēc IMBD reitinga"),
  264. ("Sērijas - jaunākās", "ltc::videonoma?page=0&genre=27&sorts=laiks&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Jaunākās sērijas"),
  265. ("Sērijas - pēc nosaukuma", "ltc::videonoma?page=0&genre=27&sorts=title&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Sērijas pēc pēc nosaukuma"),
  266. ("Sērijas animācijas - jaunākās", "ltc::videonoma?page=0&genre=27&sorts=laiks&cnt=40&clear=true&filter={\"zanrs\":[\"201\"]}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Animācijas serijas"),
  267. ("Sērijas animācijas - pēc nosaukuma", "ltc::videonoma?page=0&genre=27&sorts=title&cnt=40&clear=true&filter={\"zanrs\":[\"201\"]}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Animācijas serijas"),
  268. ("Sērijas ģimenes - jaunākās", "ltc::videonoma?page=0&genre=27&sorts=laiks&cnt=40&clear=true&filter={\"zanrs\":[\"195\"]}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Animācijas serijas"),
  269. ("Sērijas ģimenes - pēc nosaukuma", "ltc::videonoma?page=0&genre=27&sorts=title&cnt=40&clear=true&filter={\"zanrs\":[\"195\"]}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Animācijas serijas"),
  270. ("Sērijas latviski - jaunākās", 'ltc::videonoma?page=0&genre=27&sorts=laiks&cnt=40&clear=true&filter={"valoda":["lv"]}',"https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Sērijas latviski"),
  271. ("Sērijas latviski - pēc nosaukuma", 'ltc::videonoma?page=0&genre=27&sorts=title&cnt=40&clear=true&filter={"valoda":["lv"]}',"https://www.shortcut.lv/images/redesign/videonoma_dropdown_raidijumi.png","Sērijas latviski"),
  272. ("Koncerti - jaunākie", "ltc::videonoma?page=0&genre=19&sorts=laiks&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_koncerti.png","Jaunākie koncerti"),
  273. ("Koncerti - pēc nosaukuma", "ltc::videonoma?page=0&genre=19&sorts=title&cnt=40&clear=true&filter={}","https://www.shortcut.lv/images/redesign/videonoma_dropdown_koncerti.png","Koncerti pēc pēc nosaukuma"),
  274. ])
  275. return content
  276. ### Videonomas saraksti
  277. elif path == "videonoma":
  278. url = "https://www.shortcut.lv/movies-snippet.json"+params
  279. r = self._http_request(url,headers=self.headers2)
  280. if not r:
  281. return content
  282. js = json.loads(r,"utf8")
  283. if not r:
  284. return content
  285. for item in js["movies"]:
  286. if not item["title"]:
  287. continue
  288. title = item["title"].encode("utf8")
  289. data2 = item["url"][1:].encode("utf8")
  290. if data2[-1]=="/": data2=data2[:-1]
  291. if "/raidijumi/" in data2:
  292. data2 += "?series" # TODO
  293. img = "https://www.shortcut.lv"+item["image"].encode("utf8")
  294. desc = "%s\n%s"%(title,item["genre"].encode("utf8"))
  295. if "is_premium" in item and item["is_premium"]:
  296. title = title + " [P]"
  297. desc = desc + "\nPremium"
  298. content.append((title,self.name+"::"+data2,img,desc))
  299. m = re.search("page=(\d+)",data)
  300. if m:
  301. page = int(m.group(1))
  302. data2 = re.sub("page=\d+","page=%s"%(page+1),data)
  303. content.append(("Next page",self.name+"::"+data2,"","Go to next page"))
  304. return content
  305. ### Sērijas
  306. elif clist=="videonoma" and (params=="?series" or "season_nr" in qs):
  307. url = "https://www.shortcut.lv/"+path
  308. r = self._http_request(url,headers=self.headers2)
  309. if not r:
  310. return content
  311. m = re.search('<div class="movie_titles"><div class="en">([^<]+)</div>', r)
  312. raidijums = m.group(1) if m else "Series"
  313. img0 = re.search('<meta name="og:image" content="([^"]+)">', r).group(1) if re.search('<meta name="dr:say:img" content="([^"]+)">', r) else ""
  314. m = re.search('season_choice', r)
  315. # Ir sezonas
  316. if m:
  317. result = re.findall(r"""season_choice\(.+?'epizode','([^']*)',[^,]+,'(\d+)',[^,]+,[^,]+\)">([^<]+)<""", r, re.MULTILINE)
  318. if not result:
  319. raise Exception("No seasons find!")
  320. vid = result[0][0]
  321. if not "season_nr" in qs: # Sezonu saraksts
  322. for s,it in enumerate(result):
  323. title = "%s - %s" % (raidijums, it[2])
  324. data2 = path+"?season_nr=%s"%(it[1])
  325. img = img0
  326. desc = title
  327. content.append((title, self.name + "::" + data2, img, desc))
  328. return content
  329. else: # Sezonas epizožu saraksts
  330. if not "season_nr" in qs:
  331. qs["season_nr"]="0"
  332. # https://www.shortcut.lv/api/episode-loader-design17/0?chunk_size=4&sorting=epizode&series_id=dora_the_explorer
  333. # https://www.shortcut.lv/api/episode-loader-design17/3?chunk_size=4&sorting=epizode&series_id=dora_the_explorer&movie_id=10161&z360tv=&is_active_season=false HTTP/1.1
  334. # https://www.shortcut.lv/api/episode-loader-design17/3?chunk_size=4&sorting=epizode&series_id=dora_the_explorer
  335. url = "https://www.shortcut.lv/api/episode-loader-design17/%s?chunk_size=4&sorting=epizode&series_id=%s" % (qs["season_nr"], vid)
  336. r = self._http_request(url,headers=self.headers2)
  337. try:
  338. js = json.loads(r)
  339. except:
  340. raise Exception("Error getting episode list")
  341. result = re.findall(r'class="" href="([^"]+)".+?image:url\(([^ \)]+)\); "></div><div class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div></a>', js["data"])
  342. for item in result:
  343. title = "%s - %s(%s)"%(raidijums,item[2],item[3])
  344. data2 = item[0][1:]
  345. img = "https://www.shortcut.lv"+item[1]
  346. desc = title
  347. content.append((title,self.name+"::"+data2,img,desc))
  348. return content
  349. # Nav sezonu
  350. else:
  351. result = re.findall(r'class="" href="([^"]+)".+?image:url\(([^ \)]+)\).+?class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div></a>', r)
  352. for item in result:
  353. title = "%s - %s(%s)"%(raidijums,item[2],item[3])
  354. data2 = item[0][1:]
  355. img = "https://www.shortcut.lv"+item[1]
  356. desc = title
  357. content.append((title,self.name+"::"+data2,img,desc))
  358. return content
  359. ### Videonomas video
  360. elif clist=="videonoma" and len(data.split("/"))>1:
  361. ch = data.split("/")[1]
  362. video_id=data[data.find("/")+1:]
  363. #video_id=data.split("/")[-1]
  364. if not self.is_logedin2():
  365. if not self.login2():
  366. content=("Can not login\nPlease check lattelecom.tv username/password in\n/usr/lib/enigma2/python/Plugins/Extensions/sources/ltc.cfg file","","","No stream found. Please check lattelecom.tv username/password in sources/ltc.cfg file ")
  367. return content
  368. data2 = self.get_noma_url(video_id)
  369. if not data2:
  370. content=("No stream found for '%s'"%data,"","","No stream found")
  371. return content
  372. r = self.call2(data)
  373. m = re.search('<meta name="dr:say:title" content="([^"]+)">', r, re.IGNORECASE)
  374. if m:
  375. title = m.group(1)
  376. else:
  377. title = ""
  378. desc = title
  379. content = (title,data2,"",desc)
  380. return content
  381. else:
  382. return content
  383. def get_streams(self, data):
  384. print "[ltc] get_streams:", data
  385. if "::" in data: data = data.split("::")[1]
  386. if not self.is_video(data):
  387. return []
  388. ### Video nomas strīmus pagaidām dabu no mājas lapas TODO
  389. if data.split("/")[0]=="videonoma" and len(data.split("/"))>1:
  390. #video_id=data.split("/")[-1]
  391. streams = self.get_stream_url2(data)
  392. else:
  393. if not self.is_logedin():
  394. if not self.login():
  395. return []
  396. r = self.call(data)
  397. if not r: return []
  398. if "errors" in r:
  399. return []
  400. self.refresh_token()
  401. token = "&auth_token=app_%s"%(self.token)
  402. vid = data.split("/")[2].split("?")[0]
  403. vtype = data.split("/")[1]
  404. if vtype == "live-streams":
  405. ch = self.get_channel_by_id(vid)
  406. offset = "%2B03%3A00" # TODO - vajag aktuālo laika nobidi no GMS
  407. data2 = "tv/epg-live/%s/?offset=%s"%(ch["xprs_id"],offset)
  408. r2 = self.call(data2)
  409. if r2 and r2["items"]:
  410. title = r2["items"][0]["title"].encode("utf8")
  411. t1 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_start"])).strftime('%H:%M')
  412. t2 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_stop"])).strftime('%H:%M')
  413. title = "%s (%s-%s)"%(title,t1,t2)
  414. img = "https://manstv.lattelecom.tv/cache/" + r2["items"][0]["url"]
  415. desc = r2["items"][0]["description"]
  416. else:
  417. title = ch["name"]
  418. desc = title
  419. elif vtype == "record-streams":
  420. epg = self.get_epg_id(vid)
  421. if epg:
  422. title = epg["title"].encode("utf8")
  423. t1 = datetime.datetime.fromtimestamp(int(epg["unix_start"])).strftime('%H:%M')
  424. t2 = datetime.datetime.fromtimestamp(int(epg["unix_stop"])).strftime('%H:%M')
  425. date = epg["date"]
  426. title = "%s (%s %s-%s)"%(title,date,t1,t2)
  427. desc = epg["description"]
  428. else:
  429. title = desc = data
  430. streams = []
  431. for s in r["data"]:
  432. stream = util.item()
  433. stream["url"]=(s["attributes"]["stream-url"]+token.encode("utf8")).encode("utf8")
  434. stream["name"]=title
  435. stream["desc"]=desc
  436. stream["type"]="hls"
  437. m=re.search(".+_(\w\w)_(\w\w)\.\w+",s["id"])
  438. if m:
  439. stream["quality"]=m.group(2).encode("utf8")
  440. stream["lang"]=m.group(1).encode("utf8")
  441. streams.append(stream)
  442. ### TODO - sakārtot sarakstu, lai pirmais ir labakais video
  443. qlist = ["???","lq","mq","hq","hd"]
  444. llist = ["fr","en","ru","lv"]
  445. for s in streams:
  446. lv = llist.index(s["lang"])*10 if s["lang"] in llist else 0
  447. qv=qlist.index(s["quality"]) if s["quality"] in qlist else 0
  448. s["order"] = lv+qv
  449. streams = sorted(streams,key=lambda item: item["order"],reverse=True)
  450. return streams
  451. def is_video(self,data):
  452. if "::" in data:
  453. data = data.split("::")[1]
  454. cmd = data.split("/")
  455. if "get-stream" in data:
  456. return True
  457. elif cmd[0] in ("content") and cmd[1] in ("live-streams","record-streams","vod-streams"):
  458. return True
  459. elif cmd[0]=="arhivs" and len(cmd)==4:
  460. return True
  461. elif cmd[0]=="videonoma" and len(cmd)==3 and not "?" in data:
  462. return True
  463. else:
  464. return False
  465. def get_channels(self):
  466. if self.ch:
  467. return self.ch
  468. if not self.check_logedin():
  469. self.login() # citādi nerāda TV3, LNT, TV6
  470. r= self.call("tv/channels")
  471. self.ch=[]
  472. for i,item in enumerate(r["items"]):
  473. self.ch.append(item)
  474. self.ch_id[item["id"]]=i
  475. self.ch_id2[item["xprs_id"]]=i
  476. self.ch_name[item["name"]]=i
  477. return self.ch
  478. def get_channel_by_id(self,chid):
  479. if not self.ch:
  480. self.get_channels()
  481. if not self.ch:
  482. return None
  483. return self.ch[self.ch_id[chid]] if self.ch_id.has_key(chid) else None
  484. def get_channel_by_id2(self,chid):
  485. if not self.ch:
  486. self.get_channels()
  487. if not self.ch:
  488. return None
  489. return self.ch[self.ch_id2[chid]] if self.ch_id2.has_key(chid) else None
  490. def get_channels2(self):
  491. if self.ch2:
  492. return self.ch2
  493. r= self.call2("tiesraide")
  494. self.ch2=[]
  495. for item in re.findall(r'<div class="entry forward-link.+?data-xprs="(\d+)".+?title="([^"]+)" href="/tiesraide/([^"]+)"', r, re.DOTALL):
  496. ch={}
  497. ch["id2"]=item[0]
  498. ch["name"]=item[2]
  499. ch["title"]=item[1]
  500. self.ch2.append(ch)
  501. return self.ch2
  502. def get_channel_by_name2(self,name):
  503. if not self.ch2:
  504. self.get_channels2()
  505. for c in self.ch2:
  506. if c["name"]==name:
  507. return c
  508. return None
  509. def get_channel_by_name(self,name):
  510. if not self.ch:
  511. self.get_channels()
  512. ch2 = self.get_channel_by_name2(name)
  513. if not ch2:
  514. return None
  515. ch = self.get_channel_by_id2(ch2["id2"])
  516. return ch
  517. def get_epg(self,date=None,update=False):
  518. #https://manstv.lattelecom.tv/api/v1.3/get/tv/epg/?daynight=2016-05-19
  519. today=datetime.date.today()
  520. if not date:
  521. date=datetime.date.today().strftime("%Y-%m-%d")
  522. if update:
  523. self.epg=[]
  524. self.epg_id={}
  525. self.epg_id2={}
  526. self.epg_date={}
  527. self.epg_ch={}
  528. self.epg_cat={}
  529. if not date in self.epgdates:
  530. r=self.call("tv/epg/?daynight=%s"%date)
  531. for item in r["items"]:
  532. if item["id"] in self.epg_id: continue
  533. else:
  534. item["time_start2"] = datetime.datetime.fromtimestamp(int(item["unix_start"]))
  535. item["time_stop2"] = datetime.datetime.fromtimestamp(int(item["unix_stop"]))
  536. item["date"]=item["time_start2"].strftime("%Y-%m-%d")
  537. self.epg.append(item)
  538. index = self.epg.index(item)
  539. self.epg_id[item["id"]]=index
  540. if not item["date"] in self.epg_date:
  541. self.epg_date[item["date"]]=[]
  542. self.epg_date[item["date"]].append(index)
  543. if not item["channel_id"] in self.epg_ch:
  544. self.epg_ch[item["channel_id"]]=[]
  545. self.epg_ch[item["channel_id"]].append(index)
  546. if not date in self.epgdates:
  547. self.epgdates.append(date)
  548. def get_epg_id(self,epgid):
  549. if not self.epg:
  550. return None
  551. #self.get_epg()
  552. if epgid in self.epg_id:
  553. return self.epg[self.epg_id[epgid]]
  554. return None
  555. def get_epg_date(self,date,chid):
  556. if not date in self.epgdates:
  557. self.get_epg(date)
  558. items = []
  559. ch = self.get_channel_by_id(chid)
  560. for it in self.epg_date[date]:
  561. item = self.epg[it]
  562. if item["channel_id"]==ch["xprs_id"]:
  563. items.append(item)
  564. return items
  565. def call(self, data,params = None, headers=None):
  566. if not headers: headers = self.headers
  567. #if not lang: lang = self.country
  568. url = self.api_url + data
  569. content = self._http_request(url,params, headers)
  570. if content:
  571. try:
  572. result = json.loads(content)
  573. return result
  574. except Exception, ex:
  575. return None
  576. else:
  577. return None
  578. def call2(self, data,params = None, headers=None):
  579. if not headers: headers = self.headers2
  580. #if not lang: lang = self.country
  581. url = self.api_url2 + data
  582. content = self._http_request(url,params, headers)
  583. return content
  584. def _http_request0(self, url,params = None, headers=None):
  585. if not headers: headers = self.headers
  586. try:
  587. r = urllib2.Request(url, data=params, headers=headers)
  588. u = urllib2.urlopen(r)
  589. content = u.read()
  590. u.close()
  591. return content
  592. except Exception as ex:
  593. return None
  594. def login(self,user="",password=""):
  595. """Login in to site, get token"""
  596. self.options_read()
  597. if not user: user=self.options["user"]
  598. if not password: password = self.options["password"]
  599. # Dabūjam tokenu
  600. url = "https://manstv.lattelecom.tv/api/v1.3/post/user/login"
  601. params = "uid=7f777e938d35e017&password=%s&username=%s&"%(password,user)
  602. headers = headers2dict("""
  603. Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  604. User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
  605. Host: manstv.lattelecom.tv
  606. """ )
  607. try:
  608. r = urllib2.Request(url, data=params, headers=headers)
  609. u = urllib2.urlopen(r)
  610. content = u.read()
  611. u.close()
  612. except Exception as ex:
  613. return None
  614. #r = self.call(data, params)
  615. if r and "token" in content:
  616. self.token=re.search('"token":"(.+?)"', content).group(1)
  617. return True
  618. else:
  619. return False
  620. def refresh_token(self):
  621. data = "user/refresh-token//%s"%self.token
  622. r = self.call(data)
  623. if 'token' in r:
  624. self.token = r["token"]
  625. return True
  626. else:
  627. self.token = ""
  628. return False
  629. def check_logedin(self):
  630. if not self.token:
  631. return False
  632. else:
  633. if self.refresh_token():
  634. return True
  635. else:
  636. return False
  637. def is_logedin(self):
  638. if self.token:
  639. return True
  640. else:
  641. return False
  642. #----------------------------------------------------------------------
  643. def get_tv_url(self,video_id):
  644. """Get m3u8 url for given live tv channel"""
  645. url = "https://m.lattelecom.tv/tiesraide/%s"%video_id
  646. data = self.get_stream_url2("tiesraide/%s"%video_id)
  647. #headers = self.headers
  648. #headers["Cookie"] = "%s; %s; _hjIncludedInSample=0; MobBitr=1; MobRentBitr=%s; MobRentLang=%s;"%(self.session_id,self.mobtv_cache,data["quality"],data["language"])
  649. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  650. #html = response.read()
  651. #m3u8 = re.search('x-mpegURL" src="(.*?)"', html).group(1) if "x-mpegURL" in html else ""
  652. return data["stream"] if data else None
  653. #----------------------------------------------------------------------
  654. def get_noma_url(self,video_id,quality="hq",language="lv"):
  655. """Get m3u8 url for given rental video"""
  656. video_id1,video_id2=video_id.split("/")
  657. data = self.get_stream_url2(video_id)
  658. #url = "https://m.lattelecom.tv/free_origin?show_origin=1&type=4&video_url=%s&bitrate=%s&lng=%s"%(video_id2,data["quality"],data["language"])
  659. #headers = self.headers
  660. #headers["Cookie"] = "%s; %s; MobRentBitr=%s; MobBitr=1; MobRentLang=%s"%(self.session_id,self.mobtv_cache,quality,language)
  661. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  662. #m3u8 = response.read()
  663. return data["stream"] if data else None
  664. #----------------------------------------------------------------------
  665. def get_arhivs_url(self,video_id):
  666. """Get m3u8 url for given archive video"""
  667. data = self.get_video_data(video_id)
  668. #url = "https://m.lattelecom.tv/free_origin?show_origin=1&type=arhivs&event_id=%s&bitrate=mhq"%(video_id) #,data["quality"])
  669. #headers = self.headers
  670. #headers["Cookie"] = "%s; %s; MobBitr=1; "%(self.session_id,self.mobtv_cache)
  671. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  672. #m3u8 = response.read()
  673. return data["stream"] if data else None
  674. def get_stream_url(self,video_id,type="vod",chid=""):
  675. "Get stream urls (hls) using manstv api"
  676. if type=="vod":
  677. data = "vod/get-stream/%s"%video_id
  678. elif type=="tv":
  679. data = "tv/get-stream?id=%s"%video_id
  680. elif type=="archive":
  681. if not chid: return None
  682. data="archive/get-stream/%s?channelid=%s"%(video_id,chid)
  683. else:
  684. return None
  685. if not self.is_logedin():
  686. if not self.login():
  687. return None
  688. r = self.call(data)
  689. if not r:
  690. return None
  691. self.refresh_token()
  692. token = "&auth_token=app_%s"%(self.token)
  693. hls={}
  694. hls["stream"]=r["stream"]+token
  695. hls["streams"]=[]
  696. if "items" in r:
  697. for s in r["items"]["streams"]:
  698. s["stream"] += token
  699. hls["streams"].append(s)
  700. return hls
  701. def get_info2(self, data):
  702. # Get movie info (for VOD)
  703. nfo = {}
  704. tt = lambda p,r,d: re.search(p,r).group(1) if re.search(p,r) else d
  705. tt2 = lambda p,r,d: (re.sub("[\.]","",re.search(p,r).group(1))).split(", ") if re.search(p,r) else d
  706. r = self.call2(data)
  707. m = re.search(r'"movie_titles" data-movieid=(\d+)><div class="en">([^<]+)</div><div class="lv translated">([^<]+)</div>', r)
  708. if m:
  709. title1 = unescape(m.group(2))
  710. title2 = unescape(m.group(3))
  711. else:
  712. m = re.search('<meta name="dr:say:title" content="([^"]+)">', r, re.IGNORECASE)
  713. title1 = title2 = unescape(m.group(1)) if m else "Video"
  714. nfo["title"] = title2
  715. nfo["originaltitle"] = title1
  716. if nfo["originaltitle"] and not nfo["title"]:
  717. nfo["title"] = nfo["originaltitle"]
  718. if 'episode_switcher_title' in r:
  719. title2 = title2.replace("\xe2\x80\x93", "-")
  720. if " - " in title2:
  721. nfo["set"] = title2.split(" - ")[0]
  722. else:
  723. nfo["set"] = tt('<div class="movie_titles"><div class="en">(.+?)<', r, title2)
  724. m = re.search('<div class="serial_switcher_banner active".+?<div class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div>', r)
  725. if m:
  726. ep1 = m.group(1)
  727. ep2 = m.group(2)
  728. nfo["title"] = "%s - %s(%s)"%(nfo["set"], ep1, ep2)
  729. nfo["originaltitle"] = nfo["originaltitle"] + "(%s)" % ep2
  730. m = re.search("S(\d+)E(\d+)", ep2)
  731. if m:
  732. nfo["season"] = m.group(1)
  733. nfo["eposode"] = m.group(2)
  734. nfo["thumb"] = tt('<meta name="og:image" content="([^"]+)"', r,"")
  735. nfo["thumb"] = nfo["thumb"].replace("http:", "https:")
  736. nfo["year"] = tt('movie-informatio-title">Gads<.+?content">([^<]+)<', r, "")
  737. nfo["runtime"] = tt('movie-informatio-title">Garums<.+?content">([^<]+)<', r, "")
  738. nfo["quality"] = tt('movie-informatio-title">Kvalitāte<.+?content">([^<]+)<', r, "")
  739. nfo["genre"]=tt('movie-informatio-title">Žanrs<.+?content">([^<]+)<', r, "")
  740. nfo["director"] = tt('movie-informatio-title">Režisors<.+?content">([^<]+)<', r, "")
  741. nfo["actor"] = tt2('movie-informatio-title">Aktieri<.+?content">([^<]+)<', r, "")
  742. nfo["language"] = tt2('movie-informatio-title">Valodas*<.+?content">([^<]+)<', r, "")
  743. nfo["subtitles"] = tt2('movie-informatio-title">Subtitri<.+?content">([^<]+)<', r, "")
  744. nfo["plot"] = tt('movie-informatio-title">Apraksts<.+?content">([^<]+)<', r, "")
  745. nfo["tagline"] = nfo["plot"]
  746. return nfo
  747. def get_stream_url2(self,data):
  748. video_id=data[data.find("/")+1:]
  749. if not self.is_logedin2():
  750. if not self.login2():
  751. return []
  752. #data2 = self.get_noma_url(video_id)
  753. nfo = self.get_info2(data)
  754. title = util.nfo2title(nfo)
  755. desc = util.nfo2desc(nfo)
  756. img = nfo["thumb"]
  757. #xml = util.nfo2xml(nfo)
  758. url = "https://www.shortcut.lv/xmls/%s.xml"%video_id
  759. headers = self.headers2
  760. headers["Cookie"] = self.session_id
  761. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  762. r = response.read()
  763. servers = re.findall("(?s)<origin>([^<]+)</origin>", r)
  764. streams_xml = re.findall('<stream quality="\w+">(mp4:\w+(\w\w)_(\w\w).mp4)</stream>',r)
  765. resource_id = re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  766. token = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  767. streams=[]
  768. captions = []
  769. llist = ["fr","en","ru","lv"]
  770. for s in re.findall('<subtitles code="([^"]+)">([^<]+)</subtitles>', r, re.DOTALL):
  771. sub = {}
  772. sub["url"] = s[1]
  773. sub["lang"] = s[0]
  774. sub["name"] = "captions (vtt)"
  775. sub["type"] = "vtt"
  776. sub["order"] = llist.index(sub["lang"])*10 if sub["lang"] in llist else 0
  777. captions.append(sub)
  778. captions = sorted(captions,key=lambda item: item["order"],reverse=True)
  779. for s in streams_xml:
  780. for server in servers:
  781. stream = util.item()
  782. server2 = self.load_balancer(server)
  783. url = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(server2,s[0],resource_id,token)
  784. # TODO Engima2 gstreamer vajag lai padod playlist nevis chunklist
  785. # r3 = self._http_request(url)
  786. # sss = re.findall(r"#EXT-X-STREAM-INF:.*?BANDWIDTH=(\d+).*?\n(.+?)$", r3, re.IGNORECASE | re.MULTILINE)
  787. # if sss:
  788. # url2 = sss[0][1]
  789. # stream["headers"] = {"Referer":url}
  790. # if url2.startswith("http"):
  791. # url = url2
  792. # else:
  793. # url = util.hls_base(url)+url2
  794. stream["url"]=url
  795. stream["lang"]=s[1]
  796. stream["quality"]=s[2]
  797. stream["name"]= unescape(title)
  798. stream["desc"]= unescape(desc)
  799. stream["img"] = img
  800. stream["nfo"] = {"movie":nfo}
  801. stream["type"]="hls" #stream_type(url)
  802. stream["subs"] = []
  803. for c in captions:
  804. c2= c.copy()
  805. #c2["url"] ="http://%s/mobile-vod/%s/%s?resource_id=%s&auth_token=%s"%(server2,s[0],c["url"],resource_id,token)
  806. c2["url"] ="http://%s/mobile-vod/%s/%s"%(server2,s[0],c["url"])
  807. stream["subs"].append(c2)
  808. pass
  809. streams.append(stream)
  810. break # TODO ņem tikai pirmo serveri, varētu pārbaudit, kurš no tiem strādā, kurš ne
  811. return streams
  812. #data = {}
  813. #data["server"] = re.findall("(?s)<origin>([^<]+)</origin>", r)[1]
  814. #data["language"]=re.findall('(?s)<language code="([^"]+)">', r)
  815. #data["language"]="lv" if "lv" in data["language"] else "ru" if "ru" in data["language"] else "en"
  816. #data["qs"]=re.findall('(?s)<stream quality="([^"]+)">([^<]+)</stream>', r)
  817. #data["qs"]=dict(data["qs"])
  818. #qs = data["qs"].keys()
  819. #data["quality"] = "hd" if "hd" in qs else "hq" if "hq" in qs else "mhq" if "mhq" in qs else "lq"
  820. #data["mp4"] = data["qs"][data["quality"]]
  821. #data["token"] = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  822. #data["resource_id"]=re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  823. #data["server"]=self.load_balancer(data["server"])
  824. #data["hls"] = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(data["server"],data["mp4"],data["resource_id"],data["token"])
  825. ##data["hls"]="http://%s/mobile-vod/mp4:%s/playlist.m3u8?resource_id=%s&auth_token=app_%s"%(data["server"],data["mp4"],data["resource_id"],data["token"])
  826. ### wwww.shortcut.lv izsaukumi
  827. def login2(self,user="",password=""):
  828. """Login in to site, create session cookies"""
  829. if not user: user=self.options["user"]
  830. if not password: password = self.options["password"]
  831. url0 = "https://www.shortcut.lv"
  832. class NoRedirectHandler(urllib2.HTTPRedirectHandler):
  833. def http_error_302(self, req, fp, code, msg, headers):
  834. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  835. infourl.status = code
  836. infourl.code = code
  837. return infourl
  838. http_error_300 = http_error_302
  839. http_error_301 = http_error_302
  840. http_error_303 = http_error_302
  841. http_error_307 = http_error_302
  842. # Dabūjam sesijas id un url_gif, kas redirektējas uz auth_url
  843. headers = headers2dict("""
  844. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  845. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  846. Accept-Language: en-US,en;q=0.5
  847. DNT: 1
  848. Connection: keep-alive
  849. """)
  850. response = urllib2.urlopen(urllib2.Request(url0, headers=headers))
  851. session_id = response.headers["set-cookie"].split(";")[0]
  852. html = response.read()
  853. url_gif = url0 + re.search('(/auth/\d+\.gif)', html).group(1)
  854. # Dabūtjam auth_url
  855. headers = headers2dict("""
  856. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  857. Accept: image/png,image/*;q=0.8,*/*;q=0.5
  858. Accept-Language: en-US,en;q=0.5
  859. DNT: 1
  860. Referer: https://www.shortcut.lv/
  861. """)
  862. headers["Cookie"] = session_id
  863. urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))
  864. response = urllib2.urlopen(urllib2.Request(url_gif, headers=headers))
  865. if response.code == 302:
  866. url_auth = response.headers["location"]
  867. else:
  868. self.error = u"auth.gif nenostrādāja"
  869. raise Exception(u"auth.gif nenostrādāja")
  870. #return False
  871. # Pierakstāmies iekš auth.lattelecom.lv
  872. headers = headers2dict("""
  873. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  874. Accept: image/png,image/*;q=0.8,*/*;q=0.5
  875. Accept-Language: en-US,en;q=0.5
  876. DNT: 1
  877. Referer: https://www.shortcut.lv/
  878. """)
  879. response = urllib2.urlopen(urllib2.Request(url_auth, headers=headers))
  880. if not response.code == 302:
  881. self.error = u"pierakstīšanās auth.lattelecom.lv nenostrādāja"
  882. return False
  883. #raise "pierakstīšanās auth.lattelecom.lv nenostrādāja"
  884. # Mēģinam ielogoties
  885. headers = headers2dict("""
  886. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  887. Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
  888. Accept-Language: en-US,en;q=0.5
  889. DNT: 1
  890. X-Requested-With: XMLHttpRequest
  891. Referer: https://www.shortcut.lv/
  892. """)
  893. headers["Cookie"] = session_id
  894. #data = "login=yes&email=%s&passw=%s"%(user,password)
  895. url = "https://www.shortcut.lv/login.json?callback=jQuery111303344749731668816_1463817318435&username=%s&password=%s&captcha=&sid=&_="%(user,password)
  896. req = urllib2.Request(url, headers=headers)
  897. response = urllib2.urlopen(req)
  898. #with open("auth.htm","w") as f: f.write(response.read())
  899. if not response.code == 200:
  900. #self.error = u"kļūda ielogojoties"
  901. raise Exception(u"kļūda ielogojoties")
  902. html = response.read()
  903. if not '"success":true' in html:
  904. err = re.search('"error":"(.+?)"',html).group(1) if re.search('"error":"(.+?)"',html) else ""
  905. raise Exception(u"Kļūda ielogojoties - %s"%err.decode("utf8"))
  906. self.session_id = session_id
  907. self.headers2["Cookie"] = "%s; "%(self.session_id)
  908. self.error = ""
  909. return True
  910. def check_logedin2(self):
  911. if not self.session_id:
  912. return False
  913. else:
  914. url = "https://www.shortcut.lv/profils"
  915. response = urllib2.urlopen(urllib2.Request(url, headers=self.headers2))
  916. if response.code == 200:
  917. return True
  918. else:
  919. self.session_id = ""
  920. return False
  921. def is_logedin2(self):
  922. if self.session_id:
  923. return True
  924. else:
  925. return False
  926. def load_balancer(self,server,streams=[]):
  927. headers = headers2dict("""
  928. Connection: keep-alive
  929. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  930. X-Requested-With: ShockwaveFlash/21.0.0.242
  931. """)
  932. url = "http://%s/loadbalancer"%server
  933. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  934. r = response.read()
  935. statuss = re.search("<status>(\d+)</status>",r).group(1)
  936. edge = re.search("<edge>([^<>]+)</edge>",r).group(1)
  937. return edge
  938. def test_hls(self,url):
  939. headers = headers2dict("""
  940. Connection: keep-alive
  941. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  942. """)
  943. try:
  944. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  945. except Exception as ex:
  946. print "hls failed: %s %s"%(ex.getcode(),url)
  947. return False
  948. if response.code == 200:
  949. html = response.read()
  950. url0 = re.search("(http://[^/]+/)",url).group(1)
  951. chunklist = re.search("(chunklist.+)",html).group(1).strip()
  952. url2 = url.split('/')[:-1]
  953. url2 ="/".join(url2)+"/"+chunklist
  954. try:
  955. response2 = urllib2.urlopen(urllib2.Request(url2, headers=headers))
  956. except Exception as ex:
  957. print "hls chunk failed: %s %s"%(ex.getcode(),url2)
  958. return False
  959. if response2.code == 200:
  960. return True
  961. else:
  962. return False
  963. else:
  964. return False
  965. if __name__ == "__main__":
  966. sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
  967. import run
  968. source = Source()
  969. data= sys.argv[1] if len(sys.argv)>1 else source.name+"::home"
  970. run.run(source, data)
  971. sys.exit()
  972. c.get_info2(sys.argv[1])
  973. if len(sys.argv)>1 and not "ltc::" in sys.argv[1]:
  974. vid = vid2 = sys.argv[1]
  975. password = sys.argv[2]
  976. print "login - %s"%c.login("ivars777",password)
  977. #vid = "1069"
  978. #vid = "1462566072086"
  979. #channelid="101"
  980. #vid = "1350462656767"
  981. #data = c.get_stream_url(vid,"vod")
  982. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",data["stream"]])
  983. #pass
  984. print "login2 - %s"%c.login2("ivars777",password)
  985. #vid2 = "animation/ultimate_avengers_ii"
  986. #vid2 = "animation/ice_age"
  987. #vid2 = "tiesraide/ltv1"
  988. #vid2 = "arhivs/1456521417815"
  989. streams = c.get_stream_url2(vid2)
  990. stream = streams[-1]
  991. print
  992. #for s in data:
  993. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",stream["url"]])
  994. cmd = ["ffplay.exe",
  995. "-headers","Referer:%s"%(quote(stream["headers"]["Referer"])),
  996. "-headers","Connection:Keep-Alive",
  997. stream["url"]]
  998. print " ".join(cmd)
  999. call(cmd)
  1000. pass
  1001. else:
  1002. if len(sys.argv)>1:
  1003. data= sys.argv[1]
  1004. else:
  1005. data = "ltc::home"
  1006. content = c.get_content(data)
  1007. for item in content:
  1008. print item
  1009. #cat = api.get_categories(country)
  1010. #chan = api.get_channels("lv")
  1011. #prog = api.get_programs(channel=6400)
  1012. #prog = api.get_programs(category=55)
  1013. #seas = api.get_seasons(program=6453)
  1014. #str = api.get_streams(660243)
  1015. #res = api.get_videos(802)
  1016. #formats = api.getAllFormats()
  1017. #det = api.detailed("1516")
  1018. #vid = api.getVideos("13170")
  1019. pass