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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. content.append((title,self.name+"::"+data2,img,desc))
  297. m = re.search("page=(\d+)",data)
  298. if m:
  299. page = int(m.group(1))
  300. data2 = re.sub("page=\d+","page=%s"%(page+1),data)
  301. content.append(("Next page",self.name+"::"+data2,"","Go to next page"))
  302. return content
  303. ### Sērijas
  304. elif clist=="videonoma" and (params=="?series" or "season_nr" in qs):
  305. url = "https://www.lattelecom.tv/"+path
  306. r = self._http_request(url,headers=self.headers2)
  307. if not r:
  308. return content
  309. m = re.search('<div class="movie_titles"><div class="en">([^<]+)</div>', r)
  310. raidijums = m.group(1) if m else "Series"
  311. img0 = re.search('<meta name="og:image" content="([^"]+)">', r).group(1) if re.search('<meta name="dr:say:img" content="([^"]+)">', r) else ""
  312. m = re.search('season_choice', r)
  313. # Ir sezonas
  314. if m:
  315. result = re.findall(r"""season_choice\(.+?'epizode','([^']*)',[^,]+,'(\d+)',[^,]+,[^,]+\)">([^<]+)<""", r, re.MULTILINE)
  316. if not result:
  317. raise Exception("No seasons find!")
  318. vid = result[0][0]
  319. if not "season_nr" in qs: # Sezonu saraksts
  320. for s,it in enumerate(result):
  321. title = "%s - %s" % (raidijums, it[2])
  322. data2 = path+"?season_nr=%s"%(it[1])
  323. img = img0
  324. desc = title
  325. content.append((title, self.name + "::" + data2, img, desc))
  326. return content
  327. else: # Sezonas epizožu saraksts
  328. if not "season_nr" in qs:
  329. qs["season_nr"]="0"
  330. # https://www.lattelecom.tv/api/episode-loader-design17/0?chunk_size=4&sorting=epizode&series_id=dora_the_explorer
  331. # 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
  332. # https://www.lattelecom.tv/api/episode-loader-design17/3?chunk_size=4&sorting=epizode&series_id=dora_the_explorer
  333. url = "https://www.lattelecom.tv/api/episode-loader-design17/%s?chunk_size=4&sorting=epizode&series_id=%s" % (qs["season_nr"], vid)
  334. r = self._http_request(url,headers=self.headers2)
  335. try:
  336. js = json.loads(r)
  337. except:
  338. raise Exception("Error getting episode list")
  339. result = re.findall(r'class="" href="([^"]+)".+?image:url\(([^ \)]+)\); "></div><div class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div></a>', js["data"])
  340. for item in result:
  341. title = "%s - %s(%s)"%(raidijums,item[2],item[3])
  342. data2 = item[0][1:]
  343. img = "https://www.lattelecom.tv"+item[1]
  344. desc = title
  345. content.append((title,self.name+"::"+data2,img,desc))
  346. return content
  347. # Nav sezonu
  348. else:
  349. result = re.findall(r'class="" href="([^"]+)".+?image:url\(([^ \)]+)\).+?class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div></a>', r)
  350. for item in result:
  351. title = "%s - %s(%s)"%(raidijums,item[2],item[3])
  352. data2 = item[0][1:]
  353. img = "https://www.lattelecom.tv"+item[1]
  354. desc = title
  355. content.append((title,self.name+"::"+data2,img,desc))
  356. return content
  357. ### Videonomas video
  358. elif clist=="videonoma" and len(data.split("/"))>1:
  359. ch = data.split("/")[1]
  360. video_id=data[data.find("/")+1:]
  361. #video_id=data.split("/")[-1]
  362. if not self.is_logedin2():
  363. if not self.login2():
  364. 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 ")
  365. return content
  366. data2 = self.get_noma_url(video_id)
  367. if not data2:
  368. content=("No stream found for '%s'"%data,"","","No stream found")
  369. return content
  370. r = self.call2(data)
  371. m = re.search('<meta name="dr:say:title" content="([^"]+)">', r, re.IGNORECASE)
  372. if m:
  373. title = m.group(1)
  374. else:
  375. title = ""
  376. desc = title
  377. content = (title,data2,"",desc)
  378. return content
  379. else:
  380. return content
  381. def get_streams(self, data):
  382. print "[ltc] get_streams:", data
  383. if "::" in data: data = data.split("::")[1]
  384. if not self.is_video(data):
  385. return []
  386. ### Video nomas strīmus pagaidām dabu no mājas lapas TODO
  387. if data.split("/")[0]=="videonoma" and len(data.split("/"))>1:
  388. #video_id=data.split("/")[-1]
  389. streams = self.get_stream_url2(data)
  390. else:
  391. if not self.is_logedin():
  392. if not self.login():
  393. return []
  394. r = self.call(data)
  395. if not r: return []
  396. if "errors" in r:
  397. return []
  398. self.refresh_token()
  399. token = "&auth_token=app_%s"%(self.token)
  400. vid = data.split("/")[2].split("?")[0]
  401. vtype = data.split("/")[1]
  402. if vtype == "live-streams":
  403. ch = self.get_channel_by_id(vid)
  404. offset = "%2B03%3A00" # TODO - vajag aktuālo laika nobidi no GMS
  405. data2 = "tv/epg-live/%s/?offset=%s"%(ch["xprs_id"],offset)
  406. r2 = self.call(data2)
  407. if r2 and r2["items"]:
  408. title = r2["items"][0]["title"].encode("utf8")
  409. t1 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_start"])).strftime('%H:%M')
  410. t2 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_stop"])).strftime('%H:%M')
  411. title = "%s (%s-%s)"%(title,t1,t2)
  412. img = "https://manstv.lattelecom.tv/cache/" + r2["items"][0]["url"]
  413. desc = r2["items"][0]["description"]
  414. else:
  415. title = ch["name"]
  416. desc = title
  417. elif vtype == "record-streams":
  418. epg = self.get_epg_id(vid)
  419. if epg:
  420. title = epg["title"].encode("utf8")
  421. t1 = datetime.datetime.fromtimestamp(int(epg["unix_start"])).strftime('%H:%M')
  422. t2 = datetime.datetime.fromtimestamp(int(epg["unix_stop"])).strftime('%H:%M')
  423. date = epg["date"]
  424. title = "%s (%s %s-%s)"%(title,date,t1,t2)
  425. desc = epg["description"]
  426. else:
  427. title = desc = data
  428. streams = []
  429. for s in r["data"]:
  430. stream = util.item()
  431. stream["url"]=(s["attributes"]["stream-url"]+token.encode("utf8")).encode("utf8")
  432. stream["name"]=title
  433. stream["desc"]=desc
  434. stream["type"]="hls"
  435. m=re.search(".+_(\w\w)_(\w\w)\.\w+",s["id"])
  436. if m:
  437. stream["quality"]=m.group(2).encode("utf8")
  438. stream["lang"]=m.group(1).encode("utf8")
  439. streams.append(stream)
  440. ### TODO - sakārtot sarakstu, lai pirmais ir labakais video
  441. qlist = ["???","lq","mq","hq","hd"]
  442. llist = ["fr","en","ru","lv"]
  443. for s in streams:
  444. lv = llist.index(s["lang"])*10 if s["lang"] in llist else 0
  445. qv=qlist.index(s["quality"]) if s["quality"] in qlist else 0
  446. s["order"] = lv+qv
  447. streams = sorted(streams,key=lambda item: item["order"],reverse=True)
  448. return streams
  449. def is_video(self,data):
  450. if "::" in data:
  451. data = data.split("::")[1]
  452. cmd = data.split("/")
  453. if "get-stream" in data:
  454. return True
  455. elif cmd[0] in ("content") and cmd[1] in ("live-streams","record-streams","vod-streams"):
  456. return True
  457. elif cmd[0]=="arhivs" and len(cmd)==4:
  458. return True
  459. elif cmd[0]=="videonoma" and len(cmd)==3 and not "?" in data:
  460. return True
  461. else:
  462. return False
  463. def get_channels(self):
  464. if self.ch:
  465. return self.ch
  466. if not self.check_logedin():
  467. self.login() # citādi nerāda TV3, LNT, TV6
  468. r= self.call("tv/channels")
  469. self.ch=[]
  470. for i,item in enumerate(r["items"]):
  471. self.ch.append(item)
  472. self.ch_id[item["id"]]=i
  473. self.ch_id2[item["xprs_id"]]=i
  474. self.ch_name[item["name"]]=i
  475. return self.ch
  476. def get_channel_by_id(self,chid):
  477. if not self.ch:
  478. self.get_channels()
  479. if not self.ch:
  480. return None
  481. return self.ch[self.ch_id[chid]] if self.ch_id.has_key(chid) else None
  482. def get_channel_by_id2(self,chid):
  483. if not self.ch:
  484. self.get_channels()
  485. if not self.ch:
  486. return None
  487. return self.ch[self.ch_id2[chid]] if self.ch_id2.has_key(chid) else None
  488. def get_channels2(self):
  489. if self.ch2:
  490. return self.ch2
  491. r= self.call2("tiesraide")
  492. self.ch2=[]
  493. for item in re.findall(r'<div class="entry forward-link.+?data-xprs="(\d+)".+?title="([^"]+)" href="/tiesraide/([^"]+)"', r, re.DOTALL):
  494. ch={}
  495. ch["id2"]=item[0]
  496. ch["name"]=item[2]
  497. ch["title"]=item[1]
  498. self.ch2.append(ch)
  499. return self.ch2
  500. def get_channel_by_name2(self,name):
  501. if not self.ch2:
  502. self.get_channels2()
  503. for c in self.ch2:
  504. if c["name"]==name:
  505. return c
  506. return None
  507. def get_channel_by_name(self,name):
  508. if not self.ch:
  509. self.get_channels()
  510. ch2 = self.get_channel_by_name2(name)
  511. if not ch2:
  512. return None
  513. ch = self.get_channel_by_id2(ch2["id2"])
  514. return ch
  515. def get_epg(self,date=None,update=False):
  516. #https://manstv.lattelecom.tv/api/v1.3/get/tv/epg/?daynight=2016-05-19
  517. today=datetime.date.today()
  518. if not date:
  519. date=datetime.date.today().strftime("%Y-%m-%d")
  520. if update:
  521. self.epg=[]
  522. self.epg_id={}
  523. self.epg_id2={}
  524. self.epg_date={}
  525. self.epg_ch={}
  526. self.epg_cat={}
  527. if not date in self.epgdates:
  528. r=self.call("tv/epg/?daynight=%s"%date)
  529. for item in r["items"]:
  530. if item["id"] in self.epg_id: continue
  531. else:
  532. item["time_start2"] = datetime.datetime.fromtimestamp(int(item["unix_start"]))
  533. item["time_stop2"] = datetime.datetime.fromtimestamp(int(item["unix_stop"]))
  534. item["date"]=item["time_start2"].strftime("%Y-%m-%d")
  535. self.epg.append(item)
  536. index = self.epg.index(item)
  537. self.epg_id[item["id"]]=index
  538. if not item["date"] in self.epg_date:
  539. self.epg_date[item["date"]]=[]
  540. self.epg_date[item["date"]].append(index)
  541. if not item["channel_id"] in self.epg_ch:
  542. self.epg_ch[item["channel_id"]]=[]
  543. self.epg_ch[item["channel_id"]].append(index)
  544. if not date in self.epgdates:
  545. self.epgdates.append(date)
  546. def get_epg_id(self,epgid):
  547. if not self.epg:
  548. return None
  549. #self.get_epg()
  550. if epgid in self.epg_id:
  551. return self.epg[self.epg_id[epgid]]
  552. return None
  553. def get_epg_date(self,date,chid):
  554. if not date in self.epgdates:
  555. self.get_epg(date)
  556. items = []
  557. ch = self.get_channel_by_id(chid)
  558. for it in self.epg_date[date]:
  559. item = self.epg[it]
  560. if item["channel_id"]==ch["xprs_id"]:
  561. items.append(item)
  562. return items
  563. def call(self, data,params = None, headers=None):
  564. if not headers: headers = self.headers
  565. #if not lang: lang = self.country
  566. url = self.api_url + data
  567. content = self._http_request(url,params, headers)
  568. if content:
  569. try:
  570. result = json.loads(content)
  571. return result
  572. except Exception, ex:
  573. return None
  574. else:
  575. return None
  576. def call2(self, data,params = None, headers=None):
  577. if not headers: headers = self.headers2
  578. #if not lang: lang = self.country
  579. url = self.api_url2 + data
  580. content = self._http_request(url,params, headers)
  581. return content
  582. def _http_request0(self, url,params = None, headers=None):
  583. if not headers: headers = self.headers
  584. try:
  585. r = urllib2.Request(url, data=params, headers=headers)
  586. u = urllib2.urlopen(r)
  587. content = u.read()
  588. u.close()
  589. return content
  590. except Exception as ex:
  591. return None
  592. def login(self,user="",password=""):
  593. """Login in to site, get token"""
  594. self.options_read()
  595. if not user: user=self.options["user"]
  596. if not password: password = self.options["password"]
  597. # Dabūjam tokenu
  598. url = "https://manstv.lattelecom.tv/api/v1.3/post/user/login"
  599. params = "uid=7f777e938d35e017&password=%s&username=%s&"%(password,user)
  600. headers = headers2dict("""
  601. Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  602. User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
  603. Host: manstv.lattelecom.tv
  604. """ )
  605. try:
  606. r = urllib2.Request(url, data=params, headers=headers)
  607. u = urllib2.urlopen(r)
  608. content = u.read()
  609. u.close()
  610. except Exception as ex:
  611. return None
  612. #r = self.call(data, params)
  613. if r and "token" in content:
  614. self.token=re.search('"token":"(.+?)"', content).group(1)
  615. return True
  616. else:
  617. return False
  618. def refresh_token(self):
  619. data = "user/refresh-token//%s"%self.token
  620. r = self.call(data)
  621. if 'token' in r:
  622. self.token = r["token"]
  623. return True
  624. else:
  625. self.token = ""
  626. return False
  627. def check_logedin(self):
  628. if not self.token:
  629. return False
  630. else:
  631. if self.refresh_token():
  632. return True
  633. else:
  634. return False
  635. def is_logedin(self):
  636. if self.token:
  637. return True
  638. else:
  639. return False
  640. #----------------------------------------------------------------------
  641. def get_tv_url(self,video_id):
  642. """Get m3u8 url for given live tv channel"""
  643. url = "https://m.lattelecom.tv/tiesraide/%s"%video_id
  644. data = self.get_stream_url2("tiesraide/%s"%video_id)
  645. #headers = self.headers
  646. #headers["Cookie"] = "%s; %s; _hjIncludedInSample=0; MobBitr=1; MobRentBitr=%s; MobRentLang=%s;"%(self.session_id,self.mobtv_cache,data["quality"],data["language"])
  647. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  648. #html = response.read()
  649. #m3u8 = re.search('x-mpegURL" src="(.*?)"', html).group(1) if "x-mpegURL" in html else ""
  650. return data["stream"] if data else None
  651. #----------------------------------------------------------------------
  652. def get_noma_url(self,video_id,quality="hq",language="lv"):
  653. """Get m3u8 url for given rental video"""
  654. video_id1,video_id2=video_id.split("/")
  655. data = self.get_stream_url2(video_id)
  656. #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"])
  657. #headers = self.headers
  658. #headers["Cookie"] = "%s; %s; MobRentBitr=%s; MobBitr=1; MobRentLang=%s"%(self.session_id,self.mobtv_cache,quality,language)
  659. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  660. #m3u8 = response.read()
  661. return data["stream"] if data else None
  662. #----------------------------------------------------------------------
  663. def get_arhivs_url(self,video_id):
  664. """Get m3u8 url for given archive video"""
  665. data = self.get_video_data(video_id)
  666. #url = "https://m.lattelecom.tv/free_origin?show_origin=1&type=arhivs&event_id=%s&bitrate=mhq"%(video_id) #,data["quality"])
  667. #headers = self.headers
  668. #headers["Cookie"] = "%s; %s; MobBitr=1; "%(self.session_id,self.mobtv_cache)
  669. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  670. #m3u8 = response.read()
  671. return data["stream"] if data else None
  672. def get_stream_url(self,video_id,type="vod",chid=""):
  673. "Get stream urls (hls) using manstv api"
  674. if type=="vod":
  675. data = "vod/get-stream/%s"%video_id
  676. elif type=="tv":
  677. data = "tv/get-stream?id=%s"%video_id
  678. elif type=="archive":
  679. if not chid: return None
  680. data="archive/get-stream/%s?channelid=%s"%(video_id,chid)
  681. else:
  682. return None
  683. if not self.is_logedin():
  684. if not self.login():
  685. return None
  686. r = self.call(data)
  687. if not r:
  688. return None
  689. self.refresh_token()
  690. token = "&auth_token=app_%s"%(self.token)
  691. hls={}
  692. hls["stream"]=r["stream"]+token
  693. hls["streams"]=[]
  694. if "items" in r:
  695. for s in r["items"]["streams"]:
  696. s["stream"] += token
  697. hls["streams"].append(s)
  698. return hls
  699. def get_info2(self, data):
  700. # Get movie info (for VOD)
  701. nfo = {}
  702. tt = lambda p,r,d: re.search(p,r).group(1) if re.search(p,r) else d
  703. tt2 = lambda p,r,d: (re.sub("[\.]","",re.search(p,r).group(1))).split(", ") if re.search(p,r) else d
  704. r = self.call2(data)
  705. m = re.search(r'"movie_titles" data-movieid=(\d+)><div class="en">([^<]+)</div><div class="lv translated">([^<]+)</div>', r)
  706. if m:
  707. title1 = unescape(m.group(2))
  708. title2 = unescape(m.group(3))
  709. else:
  710. m = re.search('<meta name="dr:say:title" content="([^"]+)">', r, re.IGNORECASE)
  711. title1 = title2 = unescape(m.group(1)) if m else "Video"
  712. nfo["title"] = title2
  713. nfo["originaltitle"] = title1
  714. if nfo["originaltitle"] and not nfo["title"]:
  715. nfo["title"] = nfo["originaltitle"]
  716. if 'episode_switcher_title' in r:
  717. title2 = title2.replace("\xe2\x80\x93", "-")
  718. if " - " in title2:
  719. nfo["set"] = title2.split(" - ")[0]
  720. else:
  721. nfo["set"] = tt('<div class="movie_titles"><div class="en">(.+?)<', r, title2)
  722. m = re.search('<div class="serial_switcher_banner active".+?<div class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div>', r)
  723. if m:
  724. ep1 = m.group(1)
  725. ep2 = m.group(2)
  726. nfo["title"] = "%s - %s(%s)"%(nfo["set"], ep1, ep2)
  727. nfo["originaltitle"] = nfo["originaltitle"] + "(%s)" % ep2
  728. m = re.search("S(\d+)E(\d+)", ep2)
  729. if m:
  730. nfo["season"] = m.group(1)
  731. nfo["eposode"] = m.group(2)
  732. nfo["thumb"] = tt('<meta name="og:image" content="([^"]+)"', r,"")
  733. nfo["thumb"] = nfo["thumb"].replace("http:", "https:")
  734. nfo["year"] = tt('movie-informatio-title">Gads<.+?content">([^<]+)<', r, "")
  735. nfo["runtime"] = tt('movie-informatio-title">Garums<.+?content">([^<]+)<', r, "")
  736. nfo["quality"] = tt('movie-informatio-title">Kvalitāte<.+?content">([^<]+)<', r, "")
  737. nfo["genre"]=tt('movie-informatio-title">Žanrs<.+?content">([^<]+)<', r, "")
  738. nfo["director"] = tt('movie-informatio-title">Režisors<.+?content">([^<]+)<', r, "")
  739. nfo["actor"] = tt2('movie-informatio-title">Aktieri<.+?content">([^<]+)<', r, "")
  740. nfo["language"] = tt2('movie-informatio-title">Valodas*<.+?content">([^<]+)<', r, "")
  741. nfo["subtitles"] = tt2('movie-informatio-title">Subtitri<.+?content">([^<]+)<', r, "")
  742. nfo["plot"] = tt('movie-informatio-title">Apraksts<.+?content">([^<]+)<', r, "")
  743. nfo["tagline"] = nfo["plot"]
  744. return nfo
  745. def get_stream_url2(self,data):
  746. video_id=data[data.find("/")+1:]
  747. if not self.is_logedin2():
  748. if not self.login2():
  749. return []
  750. #data2 = self.get_noma_url(video_id)
  751. nfo = self.get_info2(data)
  752. title = util.nfo2title(nfo)
  753. desc = util.nfo2desc(nfo)
  754. img = nfo["thumb"]
  755. #xml = util.nfo2xml(nfo)
  756. url = "https://www.lattelecom.tv/xmls/%s.xml"%video_id
  757. headers = self.headers2
  758. headers["Cookie"] = self.session_id
  759. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  760. r = response.read()
  761. servers = re.findall("(?s)<origin>([^<]+)</origin>", r)
  762. streams_xml = re.findall('<stream quality="\w+">(mp4:\w+(\w\w)_(\w\w).mp4)</stream>',r)
  763. resource_id = re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  764. token = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  765. streams=[]
  766. captions = []
  767. llist = ["fr","en","ru","lv"]
  768. for s in re.findall('<subtitles code="([^"]+)">([^<]+)</subtitles>', r, re.DOTALL):
  769. sub = {}
  770. sub["url"] = s[1]
  771. sub["lang"] = s[0]
  772. sub["name"] = "captions (vtt)"
  773. sub["type"] = "vtt"
  774. sub["order"] = llist.index(sub["lang"])*10 if sub["lang"] in llist else 0
  775. captions.append(sub)
  776. captions = sorted(captions,key=lambda item: item["order"],reverse=True)
  777. for s in streams_xml:
  778. for server in servers:
  779. stream = util.item()
  780. server2 = self.load_balancer(server)
  781. url = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(server2,s[0],resource_id,token)
  782. # TODO Engima2 gstreamer vajag lai padod playlist nevis chunklist
  783. # r3 = self._http_request(url)
  784. # sss = re.findall(r"#EXT-X-STREAM-INF:.*?BANDWIDTH=(\d+).*?\n(.+?)$", r3, re.IGNORECASE | re.MULTILINE)
  785. # if sss:
  786. # url2 = sss[0][1]
  787. # stream["headers"] = {"Referer":url}
  788. # if url2.startswith("http"):
  789. # url = url2
  790. # else:
  791. # url = util.hls_base(url)+url2
  792. stream["url"]=url
  793. stream["lang"]=s[1]
  794. stream["quality"]=s[2]
  795. stream["name"]= unescape(title)
  796. stream["desc"]= unescape(desc)
  797. stream["img"] = img
  798. stream["nfo"] = {"movie":nfo}
  799. stream["type"]="hls" #stream_type(url)
  800. stream["subs"] = []
  801. for c in captions:
  802. c2= c.copy()
  803. #c2["url"] ="http://%s/mobile-vod/%s/%s?resource_id=%s&auth_token=%s"%(server2,s[0],c["url"],resource_id,token)
  804. c2["url"] ="http://%s/mobile-vod/%s/%s"%(server2,s[0],c["url"])
  805. stream["subs"].append(c2)
  806. pass
  807. streams.append(stream)
  808. break # TODO ņem tikai pirmo serveri, varētu pārbaudit, kurš no tiem strādā, kurš ne
  809. return streams
  810. #data = {}
  811. #data["server"] = re.findall("(?s)<origin>([^<]+)</origin>", r)[1]
  812. #data["language"]=re.findall('(?s)<language code="([^"]+)">', r)
  813. #data["language"]="lv" if "lv" in data["language"] else "ru" if "ru" in data["language"] else "en"
  814. #data["qs"]=re.findall('(?s)<stream quality="([^"]+)">([^<]+)</stream>', r)
  815. #data["qs"]=dict(data["qs"])
  816. #qs = data["qs"].keys()
  817. #data["quality"] = "hd" if "hd" in qs else "hq" if "hq" in qs else "mhq" if "mhq" in qs else "lq"
  818. #data["mp4"] = data["qs"][data["quality"]]
  819. #data["token"] = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  820. #data["resource_id"]=re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  821. #data["server"]=self.load_balancer(data["server"])
  822. #data["hls"] = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(data["server"],data["mp4"],data["resource_id"],data["token"])
  823. ##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"])
  824. ### wwww.lattelecom.tv izsaukumi
  825. def login2(self,user="",password=""):
  826. """Login in to site, create session cookies"""
  827. if not user: user=self.options["user"]
  828. if not password: password = self.options["password"]
  829. url0 = "https://www.lattelecom.tv"
  830. class NoRedirectHandler(urllib2.HTTPRedirectHandler):
  831. def http_error_302(self, req, fp, code, msg, headers):
  832. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  833. infourl.status = code
  834. infourl.code = code
  835. return infourl
  836. http_error_300 = http_error_302
  837. http_error_301 = http_error_302
  838. http_error_303 = http_error_302
  839. http_error_307 = http_error_302
  840. # Dabūjam sesijas id un url_gif, kas redirektējas uz auth_url
  841. headers = headers2dict("""
  842. Host: www.lattelecom.tv
  843. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  844. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  845. Accept-Language: en-US,en;q=0.5
  846. DNT: 1
  847. Connection: keep-alive
  848. """)
  849. response = urllib2.urlopen(urllib2.Request(url0, headers=headers))
  850. session_id = response.headers["set-cookie"].split(";")[0]
  851. html = response.read()
  852. url_gif = url0 + re.search('(/auth/\d+\.gif)', html).group(1)
  853. # Dabūtjam auth_url
  854. headers = headers2dict("""
  855. Host: www.lattelecom.tv
  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.lattelecom.tv/
  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 u"auth.gif nenostrādāja"
  870. return False
  871. # Pierakstāmies iekš auth.lattelecom.lv
  872. headers = headers2dict("""
  873. Host: auth.lattelecom.lv
  874. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  875. Accept: image/png,image/*;q=0.8,*/*;q=0.5
  876. Accept-Language: en-US,en;q=0.5
  877. DNT: 1
  878. Referer: https://www.lattelecom.tv/
  879. """)
  880. response = urllib2.urlopen(urllib2.Request(url_auth, headers=headers))
  881. if not response.code == 302:
  882. self.error = u"pierakstīšanās auth.lattelecom.lv nenostrādāja"
  883. return False
  884. #raise "pierakstīšanās auth.lattelecom.lv nenostrādāja"
  885. # Mēģinam ielogoties
  886. headers = headers2dict("""
  887. Host: www.lattelecom.tv
  888. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  889. Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
  890. Accept-Language: en-US,en;q=0.5
  891. DNT: 1
  892. X-Requested-With: XMLHttpRequest
  893. Referer: https://www.lattelecom.tv/
  894. """)
  895. headers["Cookie"] = session_id
  896. #data = "login=yes&email=%s&passw=%s"%(user,password)
  897. url = "https://www.lattelecom.tv/login.json?callback=jQuery111303344749731668816_1463817318435&username=%s&password=%s&captcha=&sid=&_="%(user,password)
  898. req = urllib2.Request(url, headers=headers)
  899. response = urllib2.urlopen(req)
  900. #with open("auth.htm","w") as f: f.write(response.read())
  901. if not response.code == 200:
  902. #self.error = u"kļūda ielogojoties"
  903. raise Exception(u"kļūda ielogojoties")
  904. html = response.read()
  905. if not '"success":true' in html:
  906. err = re.search('"error":"(.+?)"',html).group(1) if re.search('"error":"(.+?)"',html) else ""
  907. raise Exception(u"Kļūda ielogojoties - %s"%err.decode("utf8"))
  908. self.session_id = session_id
  909. self.headers2["Cookie"] = "%s; "%(self.session_id)
  910. self.error = ""
  911. return True
  912. def check_logedin2(self):
  913. if not self.session_id:
  914. return False
  915. else:
  916. url = "https://www.lattelecom.tv/profils"
  917. response = urllib2.urlopen(urllib2.Request(url, headers=self.headers2))
  918. if response.code == 200:
  919. return True
  920. else:
  921. self.session_id = ""
  922. return False
  923. def is_logedin2(self):
  924. if self.session_id:
  925. return True
  926. else:
  927. return False
  928. def load_balancer(self,server,streams=[]):
  929. headers = headers2dict("""
  930. Connection: keep-alive
  931. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  932. X-Requested-With: ShockwaveFlash/21.0.0.242
  933. """)
  934. url = "http://%s/loadbalancer"%server
  935. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  936. r = response.read()
  937. statuss = re.search("<status>(\d+)</status>",r).group(1)
  938. edge = re.search("<edge>([^<>]+)</edge>",r).group(1)
  939. return edge
  940. def test_hls(self,url):
  941. headers = headers2dict("""
  942. Connection: keep-alive
  943. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  944. """)
  945. try:
  946. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  947. except Exception as ex:
  948. print "hls failed: %s %s"%(ex.getcode(),url)
  949. return False
  950. if response.code == 200:
  951. html = response.read()
  952. url0 = re.search("(http://[^/]+/)",url).group(1)
  953. chunklist = re.search("(chunklist.+)",html).group(1).strip()
  954. url2 = url.split('/')[:-1]
  955. url2 ="/".join(url2)+"/"+chunklist
  956. try:
  957. response2 = urllib2.urlopen(urllib2.Request(url2, headers=headers))
  958. except Exception as ex:
  959. print "hls chunk failed: %s %s"%(ex.getcode(),url2)
  960. return False
  961. if response2.code == 200:
  962. return True
  963. else:
  964. return False
  965. else:
  966. return False
  967. if __name__ == "__main__":
  968. sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
  969. import run
  970. source = Source()
  971. data= sys.argv[1] if len(sys.argv)>1 else source.name+"::home"
  972. run.run(source, data)
  973. sys.exit()
  974. c.get_info2(sys.argv[1])
  975. if len(sys.argv)>1 and not "ltc::" in sys.argv[1]:
  976. vid = vid2 = sys.argv[1]
  977. password = sys.argv[2]
  978. print "login - %s"%c.login("ivars777",password)
  979. #vid = "1069"
  980. #vid = "1462566072086"
  981. #channelid="101"
  982. #vid = "1350462656767"
  983. #data = c.get_stream_url(vid,"vod")
  984. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",data["stream"]])
  985. #pass
  986. print "login2 - %s"%c.login2("ivars777",password)
  987. #vid2 = "animation/ultimate_avengers_ii"
  988. #vid2 = "animation/ice_age"
  989. #vid2 = "tiesraide/ltv1"
  990. #vid2 = "arhivs/1456521417815"
  991. streams = c.get_stream_url2(vid2)
  992. stream = streams[-1]
  993. print
  994. #for s in data:
  995. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",stream["url"]])
  996. cmd = ["ffplay.exe",
  997. "-headers","Referer:%s"%(quote(stream["headers"]["Referer"])),
  998. "-headers","Connection:Keep-Alive",
  999. stream["url"]]
  1000. print " ".join(cmd)
  1001. call(cmd)
  1002. pass
  1003. else:
  1004. if len(sys.argv)>1:
  1005. data= sys.argv[1]
  1006. else:
  1007. data = "ltc::home"
  1008. content = c.get_content(data)
  1009. for item in content:
  1010. print item
  1011. #cat = api.get_categories(country)
  1012. #chan = api.get_channels("lv")
  1013. #prog = api.get_programs(channel=6400)
  1014. #prog = api.get_programs(category=55)
  1015. #seas = api.get_seasons(program=6453)
  1016. #str = api.get_streams(660243)
  1017. #res = api.get_videos(802)
  1018. #formats = api.getAllFormats()
  1019. #det = api.detailed("1516")
  1020. #vid = api.getVideos("13170")
  1021. pass