from imports import *
from about import *
from StringIO import StringIO
import gzip
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
cj = {}

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,index):
    res = [(name, link, image,index)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def episodes_(name, link, image, info):
    res = [(name,
      link,
      image,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def cat_(letter, link):
    res = [(letter, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class vipgoal(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,
         'red': self.exit,
         'blue': self.dnitnow}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('vipgoal')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        global old_ref
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        url = 'http://www.vipgoal.net/index.php?ck=FOOTBALL'
        getPage(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_channels)

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

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'
        elif self.info == 'list_channels' or self.info == 'list_live':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'
        elif self.info == 'list_channels' or self.info == 'list_live':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'
        elif self.info == 'list_channels' or self.info == 'list_live':
            try:
                self.load_poster()
            except:
                print 'error loading poster'


    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'
        elif self.info == 'list_episodes' or self.info == 'list_live':
            try:
                self.load_poster()
            except:
                print 'error loading poster'


    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('1.Channels', 'http://showsport-tv.com/', None,'1'),('2.LiveEvents','http://showsport-tv.com/',None,'2')]
        for each in cat:
            category, link, thumb, index = each
            self.cat_list.append(show_(category, link, thumb,index))
        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def list_channels(self, data):
        self.info = 'list_channels'
        self.show_list = []
        channels=re.findall('<span class="icon-logo"></span>\n.*?<li class="">\n.*?<a href=".*?">\n.*?<div class="litd fecha"><b>(.*?)</b>(.*?)</div>\n.*?<div class="litd flag .*?" title="(.*?)"></div>\n.*?<div class="litd .*?"><img src="(.*?)" border="0" title=".*?"></div>\n.*?<div class="litd nombre"><a href="(.*?)" title=".*?"><h2>.*?</h2></a></div>',data,re.DOTALL)
        print channels
        for(matchday,matchtime,title,img,url) in channels:									
            url='http://www.vipgoal.net/'+url
            img='http://www.vipgoal.net/'+img
            title=matchday+' '+matchtime+' '+title
            print title
            self.show_list.append(show_(title, url, img,None))
        self['menulist'].l.setList(self.show_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def list_live(self, data):
        print data
        self.info = 'list_live'
        self.show_list = []
        matches_live=re.findall('<div class="date_time column"><span class="starttime time" rel=".*?">(.*?)</span>.*?Today</span></div><div class="team column"><img src=".*?"><span>(.*?)</span></div>\n<div class="versus column"><img style="position: absolute;height: ..px" src=".*?"></div>\n<div class="away column"><span style="padding-right: ..px;">(.*?)</span><img src=".*?"></div>\n<div class="live_btn column"> <a href="(.*?)">\&nbsp;Live </a> </div>',data)
        print matches_live
        for each in matches_live:
            matchtime,team1,team2,url=each
            title=matchtime+' : '+team1+' : '+team2
            url='http://showsport-tv.com'+url
            #img='http://showsport-tv.com'+url.replace('\n','').replace(' ','%20')
            self.show_list.append(show_(title, url,None,'2'))
        matches_1=re.findall('<div class="date_time column">.*?src="/images/live.gif"></div><div class="team column"><img src=".*?"><span>(.*?)</span></div>\n<div class="versus column">.*?src="/images/vs-logo.png"></div>\n<div class="away column"><span style="padding-right: 10px;">(.*?)</span><img src=".*?"></div>\n<div class="live_btn column"> <a class="online" href="(.*?)">',data,re.DOTALL)
        if matches_1:
            for each in matches_1:
                team1,team2,url=each
                title='Live '+team1+' : '+team2
                url='http://showsport-tv.com'+url
                self.show_list.append(show_(title, url,None,'2'))
        self['menulist'].l.setList(self.show_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_link(self, data):
        print data#<script type="text/javascript" src="http://www.sunhd.info/channelsa.php?file=146&width=650&height=410&autostart=true"></script>
#<script type="text/javascript" src="http://www.playerapp1.pw/channel.php?file=151&width=650&height=410&autostart=true"></script>
        link=re.findall('src="http://.*?php\?file=(.*?)&',data)
        print link
        self.build_link(link[0])

    def build_link(self,data):
        print data
        url='http://cdn.sitenow.me/live/tvb%s/playlist.m3u8' %data
        fl = 'http://127.0.0.1:88/hlsvariant://' + url + ' headers={"Host":"cdn.sitenow.me","Origin":"http://www.playerapp1.pw","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36","Referer":"http://www.playerapp1.pw/channel.php"}'
        self.play_movie(fl)

    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]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        selectedIndex= self['menulist'].l.getCurrentSelection()[0][3]
        if self.info == 'list_cat'and selectedIndex=='1':
            url = str(selectedEntry)
            print url
            getPage(url, timeout=8, method='GET', headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_channels)
        elif self.info == 'list_cat' and selectedIndex=='2':
            url = str(selectedEntry)
            print url
            getPage(url, timeout=8, method='GET', headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_live)
        elif self.info=='list_channels':
            url = str(selectedEntry)
            print url
            getPage(url, timeout=8, method='GET', headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)
        elif self.info=='list_live':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'Host': 'showsport-tv.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)
        #elif selectedIndex=='2':
            

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/hayyes_poster.jpg'):
                os.system('rm -r /tmp/hayyes_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_channels':
            self.close()
        elif self.info == 'list_episodes':
            self.info = 'list_shows'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_streams':
            self.info = 'list_episodes'
            self['blue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info='list_channels'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            #self.load_poster()
        elif self.info=='list_live':
            self.info='list_cat'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/hayyes_poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            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/hayyes/'):
            os.system('mkdir /tmp/hayyes/')
        else:
            print '[hayyes] /tmp/hayyes/ allready present'
			
class unwise:
    def worker(self, str_eval):
        page_value=""
        try:        
            ss="w,i,s,e=("+str_eval+')' 
            exec (ss)
            page_value=self.__unwise(w,i,s,e)
        except: return
        return page_value

    def __unwise(self,  w, i, s, e):
        lIll = 0;
        ll1I = 0;
        Il1l = 0;
        ll1l = [];
        l1lI = [];
        while True:
            if (lIll < 5):
                l1lI.append(w[lIll])
            elif (lIll < len(w)):
                ll1l.append(w[lIll]);
            lIll+=1;
            if (ll1I < 5):
                l1lI.append(i[ll1I])
            elif (ll1I < len(i)):
                ll1l.append(i[ll1I])
            ll1I+=1;
            if (Il1l < 5):
                l1lI.append(s[Il1l])
            elif (Il1l < len(s)):
                ll1l.append(s[Il1l]);
            Il1l+=1;
            if (len(w) + len(i) + len(s) + len(e) == len(ll1l) + len(l1lI) + len(e)):
                break;
            
        lI1l = ''.join(ll1l)
        I1lI = ''.join(l1lI)
        ll1I = 0;
        l1ll = [];
        for lIll in range(0,len(ll1l),2):
            ll11 = -1;
            if ( ord(I1lI[ll1I]) % 2):
                ll11 = 1;
            l1ll.append(chr(    int(lI1l[lIll: lIll+2], 36) - ll11));
            ll1I+=1;
            if (ll1I >= len(l1lI)):
                ll1I = 0;
        ret=''.join(l1ll)
        if 'eval(function(w,i,s,e)' in ret:
            ret=re.compile('eval\(function\(w,i,s,e\).*}\((.*?)\)').findall(ret)[0] 
            return self.worker(ret)
        else:
            return ret