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

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