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

ltc.py 60KB

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