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

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