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

ltc.py 51KB

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