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

ltc.py 51KB

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