from imports import *
from about import *
import requests

class m2list(MenuList):

    def __init__(self, list):
        MenuList.__init__(self, list, False, eListboxPythonMultiContent)
        self.l.setFont(0, gFont('Regular', 14))
        self.l.setFont(1, gFont('Regular', 16))
        self.l.setFont(2, gFont('Regular', 18))
        self.l.setFont(3, gFont('Regular', 20))
        self.l.setFont(4, gFont('Regular', 22))
        self.l.setFont(5, gFont('Regular', 24))
        self.l.setFont(6, gFont('Regular', 26))
        self.l.setFont(7, gFont('Regular', 28))
        self.l.setFont(8, gFont('Regular', 32))


def show_(name, link, image,description):
    res = [(name, link, image,description)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res
	
def cat_(name, link):
    res = [(name, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res	


class tata(Screen):

    def __init__(self, session):
        self.session = session
        sz_w = getDesktop(0).size().width()
        if sz_w == 1920:
            if config.Albatros.skin.value=='1':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen_new.xml"
            elif config.Albatros.skin.value=='2':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin2/defaultListScreen_new.xml"
            elif config.Albatros.skin.value=='3':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin3/defaultListScreen_new.xml"
        else:
            if config.Albatros.skin.value=='1':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen.xml"
            elif config.Albatros.skin.value=='2':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin2/defaultListScreen.xml"
            elif config.Albatros.skin.value=='3':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin3/defaultListScreen.xml"
        with open(path, "r") as f:
            self.skin = f.read()
            f.close()
        Screen.__init__(self, session)
        self['actions'] = ActionMap(['OkCancelActions',
         'ColorActions',
         'DirectionActions',
         'MovieSelectionActions'], {'up': self.up,
         'down': self.down,
         'left': self.left,
         'right': self.right,
         'ok': self.ok,
         'cancel': self.exit,
         'green': self.search,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Search')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('Tata.to')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.m_list=[]
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        global old_ref
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.start)

    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        if self.info == 'content' or self.info=='start':
            self[self.currentList].up()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].up()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
			
    def down(self):
        if self.info == 'content' or self.info=='start':
            self[self.currentList].down()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].down()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)

    def left(self):
        if self.info == 'content' or self.info=='start':
            self[self.currentList].pageUp()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].pageUp()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)

    def right(self):
        if self.info == 'content' or self.info=='start':
            self[self.currentList].pageDown()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].pageDown()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)

    def start(self):
        self.info='start'
        start_list=[('TV Channels','https://www.tata.to/channels','http://www.directpackages.com/shared/2014/03/TV-Channels.png'),('Serien','https://www.tata.to/tv','http://orig14.deviantart.net/7d96/f/2013/287/d/3/tv_series_icon_by_quaffleeye-d6qj64q.png'),('Filme','https://www.tata.to/filme','http://www.dealgott.de/wp-content/uploads/2017/03/image-435.png')]
        self.ss_list=[]
        for title,url,img in start_list:
            self.ss_list.append(show_(title,url,img,None))
        self['menulist'].l.setList(self.ss_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def search(self):
        self.info='search'
        self.session.openWithCallback(self.search_tata, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_tata(self, searchstring = None):
        self.info='search'
        self.m_list=[]
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'https://www.tata.to/filme?suche=' + searchstring_fin+'&type=alle'
            t=requests.get(url)
            data=t.text
            self.get_content(data)

    def get_series(self):
        self.info='series'
        self.s_list=[]
        url='https://www.tata.to/tv'
        data=requests.get(url).text
        series=re.findall('<div class="ml-item"><div class="ml-item-content"><a href="(.*?)".*?<img src="(.*?)".*?<h6> (.*?) </h6>.*?<div class="caption-description"> (.*?) </div><ul class="item-details">',data)
        if series:
            for (url,img,title,description) in series:
                url=str(url)
                img=str(img).replace('https','http')
                title=str(title)
                self.s_list.append(show_(title,url,img,description))	
            self['menulist'].l.setList(self.s_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()

    def get_s_content(self):
        self.info='s_content'	
        self.e_list=[]
        url=self['menulist'].getCurrent()[0][1]
        t=requests.get(url)
        data=t.text
        s_bl=re.findall('<div class="sl-item">(.*?)</li></ul>',data,re.DOTALL)
        if s_bl:
            epis=re.findall('<a href="https://www.tata.to/film/.*?-stream-(.*?)">(.*?)</a></li>',s_bl[0])
            for (url,title) in epis:
                url='https://tata.to/ajax/stream/'+str(url)
                title=str(title)
                self.e_list.append(cat_(title,url))	
            self['menulist'].l.setList(self.e_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)				

    def get_pages(self):
        self.info='content'
        url='https://www.tata.to/filme'
        t=requests.get(url)
        data=t.text
        last_page=re.findall('data-ci-pagination-page="(.*?)">Letzte',data)
        i=1
        for i in range(1,2):
            url=url+'/'+str(i)
            data=requests.get(url).text
            self.get_content(data)
            url='https://www.tata.to/filme'

    def get_content(self,data):
        self.info='content'
        movies=re.findall('<div class="ml-item-content"><a href="(.*?)" class="ml-image">.*?<img src="(.*?)".*?<div class="mtd-header"><h6>(.*?)</h6>.*?<div class="caption-description"> (.*?) </div><ul class="item-details"><li>',data)
        if movies:
            for(url,img,title,description) in movies:
                id=re.findall('/film/.*?-stream-([a-z,1-9,0]{8})',url)
                #print id
                img=str(img).replace('https','http')
                title=str(title).replace('<span class="mark-wc">','').replace('</span>','')
                uri='https://tata.to/ajax/stream/'+str(id[0])
                self.m_list.append(show_(title,uri,img,description))
        else:
            movies=re.findall('<div class="ml-item-content">.*?<a href="https://www.tata.to/film/(.*?)-stream-(.*?)" class="ml-image">.*?<img src="(.*?)" alt="" width="150" height="240">',data,re.DOTALL)
            if movies:
                for(title,id,img) in movies:
                    id=str(id)
                    img=str(img).replace('https','http')
                    title=str(title).title()
                    uri='https://tata.to/ajax/stream/'+id
                    self.m_list.append(show_(title,uri,img,None))
            else:
                title='Sorry - nothing found'
                url='http://'
                self.m_list.append(show_(title,url,None,None))
        self['menulist'].l.setList(self.m_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        self.load_poster()
		
    def get_link1(self):
        self.info='link'
        self.q_list=[]	
        url=self['menulist'].getCurrent()[0][1]
        #print url
        data=requests.get(url,headers={"Host":"tata.to","Referer":"http://tata.to","Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","X-Requested-with":"XMLHttpRequest"}).text
        print data
        data=base64.b64decode(data)
        print data
        #q_link=re.findall('"link_mp4":"(.*?)","quality":([0-9]{3,4})\}',data)
        link=re.findall('"playinfo":"(.*?)"',data)
        print link
        link1=link[0].replace('\\','').replace('embed.html','index.m3u8').replace('https','http')
        link1='http://127.0.0.1:88/hlsvariant://'+str(link1)+ ' headers={"x-requested-with":"ShockwaveFlash/26.0.0.126","Referer":"'+link[0]+'","User-Agent":"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"}'
        self.play_movie(link1)
        #for (lnk,q) in q_link:
        #    lnk=(lnk.encode('utf-8')).replace('\\','')
        #    lnk=str(lnk)
        #    q=str(q)
        #    self.q_list.append(cat_(q,lnk))
        #self['menulist'].l.setList(self.q_list)
        #self['menulist'].l.setItemHeight(40)
        #self['menulist'].moveToIndex(0)
        #auswahl = self['menulist'].getCurrent()[0][0]
        #self['name'].setText(auswahl)

    def get_final_link(self):
        url=self['menulist'].getCurrent()[0][1]
        print url
        r=requests.get(url,allow_redirects=False,headers={"user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","x-client-data":"CIW2yQEIorbJAQ==","x-requested-with":"XMLHttpRequest"}) 
        #print r.text
        try:      	
            loc=r.headers['Location']
            self.play_movie(loc)
        except:
            print 'no redirect'
            self.play_movie(url)
			
    def get_ch(self):
        self.info='list_cat'
        self.ch_l=[]
        url='https://www.tata.to/channels'
        headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","referer":"https://www.tata.to/"}
        t=requests.get(url,headers)
        data=t.text
        print data
        ch_bl=re.findall('<div class="ml-list-holder">(.*?)<nav class="page-nav">',data,re.DOTALL)
        print ch_bl
        if ch_bl:
            ch=re.findall('<a href="(.*?)" class="ml-image">.*?<img src="(.*?)" alt="">',ch_bl[0],re.DOTALL)
            print ch
            for (url,img) in ch:
                title=str(url).split('/')[4]
                url=str(url)
                img=str(img).replace('https','http')
                self.ch_l.append(show_(title,url,img,None))
            self['menulist'].l.setList(self.ch_l)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()

    def get_link(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        t=requests.get(url,headers={"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X)"})
        data=t.text
        m3u8=re.search('data-src="https(.*?)\/embed.+?(\?token.*?)"',data)
        if m3u8:#https://s2.skyfall.to/13thStreet/hds/token=67d42077-14902957026105/tracks-v1a1/Seg1-Frag49648
            link='https' + m3u8.group(1) + '/playlist.m3u8' + m3u8.group(2)
            h=' headers={"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X)"}'
            fin='http://127.0.0.1:88/hlsvariant://'+str(link)+str(h)
			#http://127.0.0.1:88/hls://https://s2.skyfall.to/KinoweltTV/playlist.m3u8?token=ff35d65f-14903783947579 headers={"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X)"}
            print fin
            self.play_movie(fin)
		
    def play_movie(self, link):
        self.info='player'
        if link:
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, link)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        sel = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'content':
            self.get_link1()
        elif self.info=='link':
            self.get_final_link()
        elif self.info=='start' and sel=='TV Channels':
            self.get_ch()    
        elif self.info=='start' and sel=='Serien':
            self.get_series()
        elif self.info=='start' and sel=='Filme':
            self.get_pages()
        elif self.info == 'list_cat':
            self.get_link()
        elif self.info=='series':
            self.get_s_content()
        elif self.info=='s_content':
            self.get_link1()
			
    def exit(self):
        print self.info
        if self.info == 'start':
            self.close(self.session, 'exit')
        if self.info == 'content':
            self.start()
        elif self.info == 'list_cat':
            self.start()
        elif self.info=='link':	
            self.m_list=[]		
            self.get_pages()
        elif self.info=='search':	
            self.m_list=[]		
            self.get_pages()			
        elif self.info=='player':
            self.session.nav.playService(old_ref)
            self.show()
            self.start()
            #self.info='link'
            #self['menulist'].l.setList(self.q_list)
            #self['menulist'].l.setItemHeight(40)
            #self['menulist'].moveToIndex(0)
        elif self.info=='series':
            self.start()
        elif self.info=='s_content':
            self.get_series()
			
    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        except:
            print "Error: can't find file or read data"

    def show_cover(self):
        jpg_link = '/usr/lib/enigma2/python/Plugins/Extensions/hayyes/images/'
        jpg_name = 'no_cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(file_name, jpg_store)
        else:
            self.poster_resize(jpg_store)

    def downloadPic(self, data, jpg_store):
        if fileExists(jpg_store):
            self.poster_resize(jpg_store)
        else:
            print '[hayyes] logo not found'

    def poster_resize(self, poster_path):
        self['poster'].instance.setPixmap(None)
        self['poster'].hide()
        sc = AVSwitch().getFramebufferScale()
        self.picload = ePicLoad()
        size = self['poster'].instance.size()
        self.picload.setPara((size.width(),
         size.height(),
         sc[0],
         sc[1],
         False,
         1,
         '#FF000000'))
        if self.picload.startDecode(poster_path, 0, 0, False) == 0:
            ptr = self.picload.getData()
            if ptr != None:
                self['poster'].instance.setPixmap(ptr)
                self['poster'].show()
            else:
                print '[hayyes] no cover.. error'
        return

    def dir(self):
        if not pathExists('/tmp/Albatros/'):
            os.system('mkdir /tmp/Albatros/')
        else:
            print '/tmp/Albatros/ allready present'

		
	