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

ltc2.py 61KB

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