', r, re.DOTALL | re.IGNORECASE)
raidijums = m.group(1) + " - " if m else ""
m = re.search('data-bid="([^"]+)',r)
if m:
url = "https://www.lattelecom.tv/episode-loader.json?bcast_ids=%s"%(m.group(1))
r = self._http_request(url,headers=self.headers2)
i1 = r.find('{"total":')
i2 = r.find('}
.*?
([^<]+)([^<]+)', r):
title = "%s%s (%s)"%(raidijums,item[2],item[3])
data2 = item[0][1:]
img = "https://www.lattelecom.tv"+item[1]
desc = title
content.append((title,self.name+"::"+data2,img,desc))
return content
### Videonomas video
elif clist=="videonoma" and len(data.split("/"))>1:
ch = data.split("/")[1]
video_id=data[data.find("/")+1:]
#video_id=data.split("/")[-1]
if not self.is_logedin2():
if not self.login2():
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 ")
return content
data2 = self.get_noma_url(video_id)
if not data2:
content=("No stream found for '%s'"%data,"","","No stream found")
return content
r = self.call2(data)
m = re.search('
', r, re.IGNORECASE)
if m:
title = m.group(1)
else:
title = ""
desc = title
content = (title,data2,"",desc)
return content
else:
return content
def get_streams(self, data):
print "[ltc] get_streams:", data
if "::" in data: data = data.split("::")[1]
if not self.is_video(data):
return []
### Video nomas strīmus pagaidām dabu no mājas lapas TODO
if data.split("/")[0]=="videonoma" and len(data.split("/"))>1:
#video_id=data.split("/")[-1]
streams = self.get_stream_url2(data)
else:
if not self.is_logedin():
if not self.login():
return []
r = self.call(data)
if not r: return []
if "errors" in r:
return []
self.refresh_token()
token = "&auth_token=app_%s"%(self.token)
vid = data.split("/")[2].split("?")[0]
vtype = data.split("/")[1]
if vtype == "live-streams":
ch = self.get_channel_by_id(vid)
offset = "%2B03%3A00" # TODO - vajag aktuālo laika nobidi no GMS
data2 = "tv/epg-live/%s/?offset=%s"%(ch["xprs_id"],offset)
r2 = self.call(data2)
if r2 and r2["items"]:
title = r2["items"][0]["title"].encode("utf8")
t1 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_start"])).strftime('%H:%M')
t2 = datetime.datetime.fromtimestamp(int(r2["items"][0]["unix_stop"])).strftime('%H:%M')
title = "%s (%s-%s)"%(title,t1,t2)
desc = r2["items"][0]["description"]
else:
title = ch["name"]
desc = title
elif vtype == "record-streams":
epg = self.get_epg_id(vid)
title = epg["title"].encode("utf8")
t1 = datetime.datetime.fromtimestamp(int(epg["unix_start"])).strftime('%H:%M')
t2 = datetime.datetime.fromtimestamp(int(epg["unix_stop"])).strftime('%H:%M')
date = epg["date"]
title = "%s (%s %s-%s)"%(title,date,t1,t2)
desc = epg["description"]
streams = []
for s in r["data"]:
stream = util.item()
stream["url"]=(s["attributes"]["stream-url"]+token.encode("utf8")).encode("utf8")
stream["name"]=title
stream["desc"]=desc
stream["type"]="hls"
m=re.search(".+_(\w\w)_(\w\w)\.\w+",s["id"])
if m:
stream["quality"]=m.group(2).encode("utf8")
stream["lang"]=m.group(1).encode("utf8")
streams.append(stream)
### TODO - sakārtot sarakstu, lai pirmais ir labakais video
qlist = ["???","lq","mq","hq","hd"]
llist = ["fr","en","ru","lv"]
for s in streams:
lv = llist.index(s["lang"])*10 if s["lang"] in llist else 0
qv=qlist.index(s["quality"]) if s["quality"] in qlist else 0
s["order"] = lv+qv
streams = sorted(streams,key=lambda item: item["order"],reverse=True)
return streams
def is_video(self,data):
if "::" in data:
data = data.split("::")[1]
cmd = data.split("/")
if "get-stream" in data:
return True
elif cmd[0] in ("content") and cmd[1] in ("live-streams","record-streams","vod-streams"):
return True
elif cmd[0]=="arhivs" and len(cmd)==4:
return True
elif cmd[0]=="videonoma" and len(cmd)==3 and not "?" in data:
return True
else:
return False
def get_channels(self):
if self.ch:
return self.ch
if not self.check_logedin():
self.login() # citādi nerāda TV3, LNT, TV6
r= self.call("tv/channels")
self.ch=[]
for i,item in enumerate(r["items"]):
self.ch.append(item)
self.ch_id[item["id"]]=i
self.ch_id2[item["xprs_id"]]=i
self.ch_name[item["name"]]=i
return self.ch
def get_channel_by_id(self,chid):
if not self.ch:
self.get_channels()
if not self.ch:
return None
return self.ch[self.ch_id[chid]] if self.ch_id.has_key(chid) else None
def get_channel_by_id2(self,chid):
if not self.ch:
self.get_channels()
if not self.ch:
return None
return self.ch[self.ch_id2[chid]] if self.ch_id2.has_key(chid) else None
def get_channels2(self):
if self.ch2:
return self.ch2
r= self.call2("tiesraide")
self.ch2=[]
for item in re.findall(r'
', r, re.IGNORECASE)
if m:
title = m.group(1)
else:
title = ""
desc = title
url = "https://www.lattelecom.tv/xmls/%s.xml"%video_id
headers = self.headers2
headers["Cookie"] = self.session_id
response = urllib2.urlopen(urllib2.Request(url, headers=headers))
r = response.read()
servers = re.findall("(?s)
([^<]+)", r)
streams_xml = re.findall('
(mp4:\w+_(\w\w)_(\w\w).mp4)',r)
resource_id = re.search("(?s)
([^<]+)", r).group(1)
token = re.search("(?s)
([^<]+)", r).group(1)
streams=[]
captions = []
llist = ["fr","en","ru","lv"]
for s in re.findall('
([^<]+)', r, re.DOTALL):
sub = {}
sub["url"] = s[1]
sub["lang"] = s[0]
sub["name"] = "captions (vtt)"
sub["type"] = "vtt"
sub["order"] = llist.index(sub["lang"])*10 if sub["lang"] in llist else 0
captions.append(sub)
captions = sorted(captions,key=lambda item: item["order"],reverse=True)
for s in streams_xml:
for server in servers:
server2 = self.load_balancer(server)
url = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(server2,s[0],resource_id,token)
stream = util.item()
stream["url"]=url
stream["lang"]=s[1]
stream["quality"]=s[2]
stream["name"]=title
stream["desc"]=desc
stream["type"]="hls" #stream_type(url)
stream["subs"] = []
for c in captions:
c2= c.copy()
#c2["url"] ="http://%s/mobile-vod/%s/%s?resource_id=%s&auth_token=%s"%(server2,s[0],c["url"],resource_id,token)
c2["url"] ="http://%s/mobile-vod/%s/%s"%(server2,s[0],c["url"])
stream["subs"].append(c2)
pass
streams.append(stream)
break # TODO ņem tikai pirmo serveri, varētu pārbaudit, kurš no tiem strādā, kurš ne
return streams
#data = {}
#data["server"] = re.findall("(?s)
([^<]+)", r)[1]
#data["language"]=re.findall('(?s)
', r)
#data["language"]="lv" if "lv" in data["language"] else "ru" if "ru" in data["language"] else "en"
#data["qs"]=re.findall('(?s)([^<]+)', r)
#data["qs"]=dict(data["qs"])
#qs = data["qs"].keys()
#data["quality"] = "hd" if "hd" in qs else "hq" if "hq" in qs else "mhq" if "mhq" in qs else "lq"
#data["mp4"] = data["qs"][data["quality"]]
#data["token"] = re.search("(?s)([^<]+)", r).group(1)
#data["resource_id"]=re.search("(?s)([^<]+)", r).group(1)
#data["server"]=self.load_balancer(data["server"])
#data["hls"] = "http://%s/mobile-vod/%s/playlist.m3u8?resource_id=%s&auth_token=%s"%(data["server"],data["mp4"],data["resource_id"],data["token"])
##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"])
### wwww.lattelecom.tv izsaukumi
def login2(self,user="",password=""):
"""Login in to site, create session cookies"""
if not user: user=self.options["user"]
if not password: password = self.options["password"]
url0 = "https://www.lattelecom.tv"
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
# Dabūjam sesijas id un url_gif, kas redirektējas uz auth_url
headers = headers2dict("""
Host: www.lattelecom.tv
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
DNT: 1
Connection: keep-alive
""")
response = urllib2.urlopen(urllib2.Request(url0, headers=headers))
session_id = response.headers["set-cookie"].split(";")[0]
html = response.read()
url_gif = url0 + re.search('(/auth/\d+\.gif)', html).group(1)
# Dabūtjam auth_url
headers = headers2dict("""
Host: www.lattelecom.tv
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language: en-US,en;q=0.5
DNT: 1
Referer: https://www.lattelecom.tv/
""")
headers["Cookie"] = session_id
urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))
response = urllib2.urlopen(urllib2.Request(url_gif, headers=headers))
if response.code == 302:
url_auth = response.headers["location"]
else:
self.error = u"auth.gif nenostrādāja"
#raise u"auth.gif nenostrādāja"
return False
# Pierakstāmies iekš auth.lattelecom.lv
headers = headers2dict("""
Host: auth.lattelecom.lv
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language: en-US,en;q=0.5
DNT: 1
Referer: https://www.lattelecom.tv/
""")
response = urllib2.urlopen(urllib2.Request(url_auth, headers=headers))
if not response.code == 302:
self.error = u"pierakstīšanās auth.lattelecom.lv nenostrādāja"
return False
#raise "pierakstīšanās auth.lattelecom.lv nenostrādāja"
# Mēģinam ielogoties
headers = headers2dict("""
Host: www.lattelecom.tv
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
DNT: 1
X-Requested-With: XMLHttpRequest
Referer: https://www.lattelecom.tv/
""")
headers["Cookie"] = session_id
#data = "login=yes&email=%s&passw=%s"%(user,password)
url = "https://www.lattelecom.tv/login.json?callback=jQuery111303344749731668816_1463817318435&username=%s&password=%s&captcha=&sid=&_="%(user,password)
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
#with open("auth.htm","w") as f: f.write(response.read())
if not response.code == 200:
#self.error = u"kļūda ielogojoties"
raise Exception(u"kļūda ielogojoties")
html = response.read()
if not '"success":true' in html:
err = re.search('"error":"(.+?)"',html).group(1) if re.search('"error":"(.+?)"',html) else ""
raise Exception(u"Kļūda ielogojoties - %s"%err.decode("utf8"))
self.session_id = session_id
self.headers2["Cookie"] = "%s; "%(self.session_id)
self.error = ""
return True
def check_logedin2(self):
if not self.session_id:
return False
else:
url = "https://www.lattelecom.tv/profils"
response = urllib2.urlopen(urllib2.Request(url, headers=self.headers2))
if response.code == 200:
return True
else:
self.session_id = ""
return False
def is_logedin2(self):
if self.session_id:
return True
else:
return False
def load_balancer(self,server,streams=[]):
headers = headers2dict("""
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
X-Requested-With: ShockwaveFlash/21.0.0.242
""")
url = "http://%s/loadbalancer"%server
response = urllib2.urlopen(urllib2.Request(url, headers=headers))
r = response.read()
statuss = re.search("(\d+)",r).group(1)
edge = re.search("([^<>]+)",r).group(1)
return edge
def test_hls(self,url):
headers = headers2dict("""
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
""")
try:
response = urllib2.urlopen(urllib2.Request(url, headers=headers))
except Exception as ex:
print "hls failed: %s %s"%(ex.getcode(),url)
return False
if response.code == 200:
html = response.read()
url0 = re.search("(http://[^/]+/)",url).group(1)
chunklist = re.search("(chunklist.+)",html).group(1).strip()
url2 = url.split('/')[:-1]
url2 ="/".join(url2)+"/"+chunklist
try:
response2 = urllib2.urlopen(urllib2.Request(url2, headers=headers))
except Exception as ex:
print "hls chunk failed: %s %s"%(ex.getcode(),url2)
return False
if response2.code == 200:
return True
else:
return False
else:
return False
if __name__ == "__main__":
c = Source()
from subprocess import call
if len(sys.argv)>1 and not "ltc::" in sys.argv[1]:
vid = sys.argv[1]
print "login - %s"%c.login("ivars777","xxx")
vid = "1069"
vid = "1462566072086"
channelid="101"
vid = "1350462656767"
#data = c.get_stream_url(vid,"vod")
#call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",data["stream"]])
pass
print "login2 - %s"%c.login2("ivars777","xxx")
#vid2 = "animation/ultimate_avengers_ii"
#vid2 = "animation/ice_age"
vid2 = "tiesraide/ltv1"
#vid2 = "arhivs/1456521417815"
data = c.get_stream_url2(vid2)
print data
#for s in data:
call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",data["stream"]])
pass
else:
if len(sys.argv)>1:
data= sys.argv[1]
else:
data = "ltc::home"
content = c.get_content(data)
for item in content:
print item
#cat = api.get_categories(country)
#chan = api.get_channels("lv")
#prog = api.get_programs(channel=6400)
#prog = api.get_programs(category=55)
#seas = api.get_seasons(program=6453)
#str = api.get_streams(660243)
#res = api.get_videos(802)
#formats = api.getAllFormats()
#det = api.detailed("1516")
#vid = api.getVideos("13170")
pass