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

ltc.py 60KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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.3/post/user/login"
  736. params = "uid=7f777e938d35e017&password=%s&username=%s&"%(password,user)
  737. headers = headers2dict("""
  738. Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  739. User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
  740. Host: manstv.lattelecom.tv
  741. """ )
  742. try:
  743. r = urllib2.Request(url, data=params, headers=headers)
  744. u = urllib2.urlopen(r)
  745. content = u.read()
  746. u.close()
  747. except Exception as ex:
  748. return None
  749. #r = self.call(data, params)
  750. if r and "token" in content:
  751. self.token=re.search('"token":"(.+?)"', content).group(1)
  752. return True
  753. else:
  754. return False
  755. def refresh_token(self):
  756. data = "user/refresh-token//%s"%self.token
  757. r = self.call(data)
  758. if 'token' in r:
  759. self.token = r["token"]
  760. return True
  761. else:
  762. self.token = ""
  763. return False
  764. def check_logedin(self):
  765. if not self.token:
  766. return False
  767. else:
  768. if self.refresh_token():
  769. return True
  770. else:
  771. return False
  772. def is_logedin(self):
  773. if self.token:
  774. return True
  775. else:
  776. return False
  777. #----------------------------------------------------------------------
  778. def get_tv_url(self,video_id):
  779. """Get m3u8 url for given live tv channel"""
  780. url = "https://m.lattelecom.tv/tiesraide/%s"%video_id
  781. data = self.get_stream_url2("tiesraide/%s"%video_id)
  782. #headers = self.headers
  783. #headers["Cookie"] = "%s; %s; _hjIncludedInSample=0; MobBitr=1; MobRentBitr=%s; MobRentLang=%s;"%(self.session_id,self.mobtv_cache,data["quality"],data["language"])
  784. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  785. #html = response.read()
  786. #m3u8 = re.search('x-mpegURL" src="(.*?)"', html).group(1) if "x-mpegURL" in html else ""
  787. return data["stream"] if data else None
  788. #----------------------------------------------------------------------
  789. def get_noma_url(self,video_id,quality="hq",language="lv"):
  790. """Get m3u8 url for given rental video"""
  791. video_id1,video_id2=video_id.split("/")
  792. data = self.get_stream_url2(video_id)
  793. #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"])
  794. #headers = self.headers
  795. #headers["Cookie"] = "%s; %s; MobRentBitr=%s; MobBitr=1; MobRentLang=%s"%(self.session_id,self.mobtv_cache,quality,language)
  796. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  797. #m3u8 = response.read()
  798. return data["stream"] if data else None
  799. #----------------------------------------------------------------------
  800. def get_arhivs_url(self,video_id):
  801. """Get m3u8 url for given archive video"""
  802. data = self.get_video_data(video_id)
  803. #url = "https://m.lattelecom.tv/free_origin?show_origin=1&type=arhivs&event_id=%s&bitrate=mhq"%(video_id) #,data["quality"])
  804. #headers = self.headers
  805. #headers["Cookie"] = "%s; %s; MobBitr=1; "%(self.session_id,self.mobtv_cache)
  806. #response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  807. #m3u8 = response.read()
  808. return data["stream"] if data else None
  809. def get_stream_url(self,video_id,type="vod",chid=""):
  810. "Get stream urls (hls) using manstv api"
  811. if type=="vod":
  812. data = "vod/get-stream/%s"%video_id
  813. elif type=="tv":
  814. data = "tv/get-stream?id=%s"%video_id
  815. elif type=="archive":
  816. if not chid: return None
  817. data="archive/get-stream/%s?channelid=%s"%(video_id,chid)
  818. else:
  819. return None
  820. if not self.is_logedin():
  821. if not self.login():
  822. return None
  823. r = self.call(data)
  824. if not r:
  825. return None
  826. self.refresh_token()
  827. token = "&auth_token=app_%s"%(self.token)
  828. hls={}
  829. hls["stream"]=r["stream"]+token
  830. hls["streams"]=[]
  831. if "items" in r:
  832. for s in r["items"]["streams"]:
  833. s["stream"] += token
  834. hls["streams"].append(s)
  835. return hls
  836. def get_info2(self, data):
  837. # Get movie info (for VOD)
  838. nfo = {}
  839. tt = lambda p,r,d: re.search(p,r).group(1) if re.search(p,r) else d
  840. tt2 = lambda p,r,d: (re.sub("[\.]","",re.search(p,r).group(1))).split(", ") if re.search(p,r) else d
  841. r = self.call2(data)
  842. m = re.search(r'"movie_titles" data-movieid=(\d+)><div class="en">([^<]+)</div><div class="lv translated">([^<]+)</div>', r)
  843. if m:
  844. title1 = unescape(m.group(2))
  845. title2 = unescape(m.group(3))
  846. else:
  847. m = re.search('<meta name="dr:say:title" content="([^"]+)">', r, re.IGNORECASE)
  848. title1 = title2 = unescape(m.group(1)) if m else "Video"
  849. nfo["title"] = title2
  850. nfo["originaltitle"] = title1
  851. if nfo["originaltitle"] and not nfo["title"]:
  852. nfo["title"] = nfo["originaltitle"]
  853. if 'episode_switcher_title' in r:
  854. title2 = title2.replace("\xe2\x80\x93", "-")
  855. if " - " in title2:
  856. nfo["set"] = title2.split(" - ")[0]
  857. else:
  858. nfo["set"] = tt('<div class="movie_titles"><div class="en">(.+?)<', r, title2)
  859. m = re.search('<div class="serial_switcher_banner active".+?<div class="episode_titlez_design17">([^<]+)</div><div class="episode_number_design17">([^<]+)</div>', r)
  860. if m:
  861. ep1 = m.group(1)
  862. ep2 = m.group(2)
  863. nfo["title"] = "%s - %s(%s)"%(nfo["set"], ep1, ep2)
  864. nfo["originaltitle"] = nfo["originaltitle"] + "(%s)" % ep2
  865. m = re.search("S(\d+)E(\d+)", ep2)
  866. if m:
  867. nfo["season"] = m.group(1)
  868. nfo["eposode"] = m.group(2)
  869. nfo["thumb"] = tt('<meta name="og:image" content="([^"]+)"', r,"")
  870. nfo["thumb"] = nfo["thumb"].replace("http:", "https:")
  871. nfo["year"] = tt('movie-informatio-title">Gads<.+?content">([^<]+)<', r, "")
  872. nfo["runtime"] = tt('movie-informatio-title">Garums<.+?content">([^<]+)<', r, "")
  873. nfo["quality"] = tt('movie-informatio-title">Kvalitāte<.+?content">([^<]+)<', r, "")
  874. nfo["genre"]=tt('movie-informatio-title">Žanrs<.+?content">([^<]+)<', r, "")
  875. nfo["director"] = tt('movie-informatio-title">Režisors<.+?content">([^<]+)<', r, "")
  876. nfo["actor"] = tt2('movie-informatio-title">Aktieri<.+?content">([^<]+)<', r, "")
  877. nfo["language"] = tt2('movie-informatio-title">Valodas*<.+?content">([^<]+)<', r, "")
  878. nfo["subtitles"] = tt2('movie-informatio-title">Subtitri<.+?content">([^<]+)<', r, "")
  879. nfo["plot"] = tt('movie-informatio-title">Apraksts<.+?content">([^<]+)<', r, "")
  880. nfo["tagline"] = nfo["plot"]
  881. return nfo
  882. def get_stream_url2(self,data):
  883. video_id=data[data.find("/")+1:]
  884. if not self.is_logedin2():
  885. if not self.login2():
  886. return []
  887. #data2 = self.get_noma_url(video_id)
  888. nfo = self.get_info2(data)
  889. title = util.nfo2title(nfo)
  890. desc = util.nfo2desc(nfo)
  891. img = nfo["thumb"]
  892. #xml = util.nfo2xml(nfo)
  893. url = "https://www.shortcut.lv/xmls/%s.xml"%video_id
  894. headers = self.headers2
  895. headers["Cookie"] = self.session_id
  896. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  897. r = response.read()
  898. servers = re.findall("(?s)<origin>([^<]+)</origin>", r)
  899. streams_xml = re.findall('<stream quality="\w+">(mp4:\w+(\w\w)_(\w\w).mp4)</stream>',r)
  900. resource_id = re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  901. token = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  902. streams=[]
  903. captions = []
  904. llist = ["fr","en","ru","lv"]
  905. for s in re.findall('<subtitles code="([^"]+)">([^<]+)</subtitles>', r, re.DOTALL):
  906. sub = {}
  907. sub["url"] = s[1]
  908. sub["lang"] = s[0]
  909. sub["name"] = "captions (vtt)"
  910. sub["type"] = "vtt"
  911. sub["order"] = llist.index(sub["lang"])*10 if sub["lang"] in llist else 0
  912. captions.append(sub)
  913. captions = sorted(captions,key=lambda item: item["order"],reverse=True)
  914. for s in streams_xml:
  915. for server in servers:
  916. stream = util.item()
  917. server2 = self.load_balancer(server)
  918. url = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(server2,s[0],resource_id,token)
  919. # TODO Engima2 gstreamer vajag lai padod playlist nevis chunklist
  920. # r3 = self._http_request(url)
  921. # sss = re.findall(r"#EXT-X-STREAM-INF:.*?BANDWIDTH=(\d+).*?\n(.+?)$", r3, re.IGNORECASE | re.MULTILINE)
  922. # if sss:
  923. # url2 = sss[0][1]
  924. # stream["headers"] = {"Referer":url}
  925. # if url2.startswith("http"):
  926. # url = url2
  927. # else:
  928. # url = util.hls_base(url)+url2
  929. stream["url"]=url
  930. stream["lang"]=s[1]
  931. stream["quality"]=s[2]
  932. stream["name"]= unescape(title)
  933. stream["desc"]= unescape(desc)
  934. stream["img"] = img
  935. stream["nfo"] = {"movie":nfo}
  936. stream["type"]="hls" #stream_type(url)
  937. stream["subs"] = []
  938. for c in captions:
  939. c2= c.copy()
  940. #c2["url"] ="http://%s/mobile-vod/%s/%s?resource_id=%s&auth_token=%s"%(server2,s[0],c["url"],resource_id,token)
  941. c2["url"] ="http://%s/mobile-vod/%s/%s"%(server2,s[0],c["url"])
  942. stream["subs"].append(c2)
  943. pass
  944. streams.append(stream)
  945. break # TODO ņem tikai pirmo serveri, varētu pārbaudit, kurš no tiem strādā, kurš ne
  946. return streams
  947. #data = {}
  948. #data["server"] = re.findall("(?s)<origin>([^<]+)</origin>", r)[1]
  949. #data["language"]=re.findall('(?s)<language code="([^"]+)">', r)
  950. #data["language"]="lv" if "lv" in data["language"] else "ru" if "ru" in data["language"] else "en"
  951. #data["qs"]=re.findall('(?s)<stream quality="([^"]+)">([^<]+)</stream>', r)
  952. #data["qs"]=dict(data["qs"])
  953. #qs = data["qs"].keys()
  954. #data["quality"] = "hd" if "hd" in qs else "hq" if "hq" in qs else "mhq" if "mhq" in qs else "lq"
  955. #data["mp4"] = data["qs"][data["quality"]]
  956. #data["token"] = re.search("(?s)<auth_token>([^<]+)</auth_token>", r).group(1)
  957. #data["resource_id"]=re.search("(?s)<resource_id>([^<]+)</resource_id>", r).group(1)
  958. #data["server"]=self.load_balancer(data["server"])
  959. #data["hls"] = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(data["server"],data["mp4"],data["resource_id"],data["token"])
  960. ##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"])
  961. ### wwww.shortcut.lv izsaukumi
  962. def login2(self,user="",password=""):
  963. """Login in to site, create session cookies"""
  964. if not user: user=self.options["user"]
  965. if not password: password = self.options["password"]
  966. url0 = "https://www.shortcut.lv"
  967. class NoRedirectHandler(urllib2.HTTPRedirectHandler):
  968. def http_error_302(self, req, fp, code, msg, headers):
  969. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  970. infourl.status = code
  971. infourl.code = code
  972. return infourl
  973. http_error_300 = http_error_302
  974. http_error_301 = http_error_302
  975. http_error_303 = http_error_302
  976. http_error_307 = http_error_302
  977. # Dabūjam sesijas id un url_gif, kas redirektējas uz auth_url
  978. headers = headers2dict("""
  979. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  980. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  981. Accept-Language: en-US,en;q=0.5
  982. DNT: 1
  983. Connection: keep-alive
  984. """)
  985. response = urllib2.urlopen(urllib2.Request(url0, headers=headers))
  986. session_id = response.headers["set-cookie"].split(";")[0]
  987. html = response.read()
  988. url_gif = url0 + re.search('(/auth/\d+\.gif)', html).group(1)
  989. # Dabūtjam auth_url
  990. headers = headers2dict("""
  991. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  992. Accept: image/png,image/*;q=0.8,*/*;q=0.5
  993. Accept-Language: en-US,en;q=0.5
  994. DNT: 1
  995. Referer: https://www.shortcut.lv/
  996. """)
  997. headers["Cookie"] = session_id
  998. urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))
  999. response = urllib2.urlopen(urllib2.Request(url_gif, headers=headers))
  1000. if response.code == 302:
  1001. url_auth = response.headers["location"]
  1002. else:
  1003. self.error = u"auth.gif nenostrādāja"
  1004. raise Exception(u"auth.gif nenostrādāja")
  1005. #return False
  1006. # Pierakstāmies iekš auth.lattelecom.lv
  1007. headers = headers2dict("""
  1008. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  1009. Accept: image/png,image/*;q=0.8,*/*;q=0.5
  1010. Accept-Language: en-US,en;q=0.5
  1011. DNT: 1
  1012. Referer: https://www.shortcut.lv/
  1013. """)
  1014. response = urllib2.urlopen(urllib2.Request(url_auth, headers=headers))
  1015. if not response.code == 302:
  1016. self.error = u"pierakstīšanās auth.lattelecom.lv nenostrādāja"
  1017. return False
  1018. #raise "pierakstīšanās auth.lattelecom.lv nenostrādāja"
  1019. # Mēģinam ielogoties
  1020. headers = headers2dict("""
  1021. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
  1022. Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
  1023. Accept-Language: en-US,en;q=0.5
  1024. DNT: 1
  1025. X-Requested-With: XMLHttpRequest
  1026. Referer: https://www.shortcut.lv/
  1027. """)
  1028. headers["Cookie"] = session_id
  1029. #data = "login=yes&email=%s&passw=%s"%(user,password)
  1030. url = "https://www.shortcut.lv/login.json?callback=jQuery111303344749731668816_1463817318435&username=%s&password=%s&captcha=&sid=&_="%(user,password)
  1031. req = urllib2.Request(url, headers=headers)
  1032. response = urllib2.urlopen(req)
  1033. #with open("auth.htm","w") as f: f.write(response.read())
  1034. if not response.code == 200:
  1035. #self.error = u"kļūda ielogojoties"
  1036. raise Exception(u"kļūda ielogojoties")
  1037. html = response.read()
  1038. if not '"success":true' in html:
  1039. err = re.search('"error":"(.+?)"',html).group(1) if re.search('"error":"(.+?)"',html) else ""
  1040. raise Exception(u"Kļūda ielogojoties - %s"%err.decode("utf8"))
  1041. self.session_id = session_id
  1042. self.headers2["Cookie"] = "%s; "%(self.session_id)
  1043. self.error = ""
  1044. return True
  1045. def check_logedin2(self):
  1046. if not self.session_id:
  1047. return False
  1048. else:
  1049. url = "https://www.shortcut.lv/profils"
  1050. response = urllib2.urlopen(urllib2.Request(url, headers=self.headers2))
  1051. if response.code == 200:
  1052. return True
  1053. else:
  1054. self.session_id = ""
  1055. return False
  1056. def is_logedin2(self):
  1057. if self.session_id:
  1058. return True
  1059. else:
  1060. return False
  1061. def load_balancer(self,server,streams=[]):
  1062. headers = headers2dict("""
  1063. Connection: keep-alive
  1064. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  1065. X-Requested-With: ShockwaveFlash/21.0.0.242
  1066. """)
  1067. url = "http://%s/loadbalancer"%server
  1068. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  1069. r = response.read()
  1070. statuss = re.search("<status>(\d+)</status>",r).group(1)
  1071. edge = re.search("<edge>([^<>]+)</edge>",r).group(1)
  1072. return edge
  1073. def test_hls(self,url):
  1074. headers = headers2dict("""
  1075. Connection: keep-alive
  1076. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
  1077. """)
  1078. try:
  1079. response = urllib2.urlopen(urllib2.Request(url, headers=headers))
  1080. except Exception as ex:
  1081. print "hls failed: %s %s"%(ex.getcode(),url)
  1082. return False
  1083. if response.code == 200:
  1084. html = response.read()
  1085. url0 = re.search("(http://[^/]+/)",url).group(1)
  1086. chunklist = re.search("(chunklist.+)",html).group(1).strip()
  1087. url2 = url.split('/')[:-1]
  1088. url2 ="/".join(url2)+"/"+chunklist
  1089. try:
  1090. response2 = urllib2.urlopen(urllib2.Request(url2, headers=headers))
  1091. except Exception as ex:
  1092. print "hls chunk failed: %s %s"%(ex.getcode(),url2)
  1093. return False
  1094. if response2.code == 200:
  1095. return True
  1096. else:
  1097. return False
  1098. else:
  1099. return False
  1100. if __name__ == "__main__":
  1101. sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
  1102. import run
  1103. source = Source()
  1104. data= sys.argv[1] if len(sys.argv)>1 else source.name+"::home"
  1105. run.run(source, data)
  1106. sys.exit()
  1107. c.get_info2(sys.argv[1])
  1108. if len(sys.argv)>1 and not "ltc::" in sys.argv[1]:
  1109. vid = vid2 = sys.argv[1]
  1110. password = sys.argv[2]
  1111. print "login - %s"%c.login("ivars777",password)
  1112. #vid = "1069"
  1113. #vid = "1462566072086"
  1114. #channelid="101"
  1115. #vid = "1350462656767"
  1116. #data = c.get_stream_url(vid,"vod")
  1117. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",data["stream"]])
  1118. #pass
  1119. print "login2 - %s"%c.login2("ivars777",password)
  1120. #vid2 = "animation/ultimate_avengers_ii"
  1121. #vid2 = "animation/ice_age"
  1122. #vid2 = "tiesraide/ltv1"
  1123. #vid2 = "arhivs/1456521417815"
  1124. streams = c.get_stream_url2(vid2)
  1125. stream = streams[-1]
  1126. print
  1127. #for s in data:
  1128. #call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",stream["url"]])
  1129. cmd = ["ffplay.exe",
  1130. "-headers","Referer:%s"%(quote(stream["headers"]["Referer"])),
  1131. "-headers","Connection:Keep-Alive",
  1132. stream["url"]]
  1133. print " ".join(cmd)
  1134. call(cmd)
  1135. pass
  1136. else:
  1137. if len(sys.argv)>1:
  1138. data= sys.argv[1]
  1139. else:
  1140. data = "ltc::home"
  1141. content = c.get_content(data)
  1142. for item in content:
  1143. print item
  1144. #cat = api.get_categories(country)
  1145. #chan = api.get_channels("lv")
  1146. #prog = api.get_programs(channel=6400)
  1147. #prog = api.get_programs(category=55)
  1148. #seas = api.get_seasons(program=6453)
  1149. #str = api.get_streams(660243)
  1150. #res = api.get_videos(802)
  1151. #formats = api.getAllFormats()
  1152. #det = api.detailed("1516")
  1153. #vid = api.getVideos("13170")
  1154. pass