from imports import *
from about import *
import urllib2,urllib,cgi, re , cookielib ,jscrypto
import urlparse
import HTMLParser

from operator import itemgetter
import traceback,cookielib
import base64,os,  binascii

from time import time
import base64,sys
try:
    import json
except:
    import simplejson as json
headers=[('User-Agent','AppleCoreMedia/1.0.0.13A452 (iPhone; U; CPU OS 9_0_2 like Mac OS X; en_gb)')]
useragent='AppleCoreMedia/1.0.0.13A452 (iPhone; U; CPU OS 9_0_2 like Mac OS X; en_gb)'
lastfinalurl=''
cookieJar = cookielib.LWPCookieJar()
S365COOKIEFILE='/usr/lib/enigma2/python/Plugins/Extensions/Albatros/365cookie'
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 cat_(letter, link):
    res = [(letter, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=letter, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER))
    return res


class sport365(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}, -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('Sport 365 Live')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        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.get_matches)

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

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def get_matches(self):
        self.info='get_matches'
        self.m_list=[]
        cookieJar=get365CookieJar(True)
        url='http://www.sport365.live/de/events/-/1/-/-'+'/'+str(getutfoffset())
        headers=[('User-Agent','AppleCoreMedia/1.0.0.13A452 (iPhone; U; CPU OS 9_0_2 like Mac OS X; en_gb)')]
        linkshtml=getUrl(url,headers=headers, cookieJar=cookieJar)
        reg="images\/types.*?(green|red).*?px;\">([^<]+)<\/td><td style=\"borde.*?>([^<]+)<\/td><td.*?>([^<]+)<\/td.*?\(.*?,.?\"([^\"]+)\".*?\">([^<]+)<"
        sportslinks=re.findall(reg,linkshtml)
        print 'got links',sportslinks
        kkey=get365Key(cookieJar,useproxy=False)
        for tp,tm,nm,lng,lnk,cat in sportslinks:
            cat=cat.split("/")[0]
            try:
                lnk=json.loads(lnk.decode("base64"))
                lnk=jscrypto.decode(lnk["ct"],kkey,lnk["s"].decode("hex"))
            except:
                print 'can not decode that shit'
            if not lnk.startswith("http"):
                lnk='http://www.sport365.live'+lnk
            lnk=lnk.replace('\\','').replace('"','')
            if tp =='green':
                tp='Live'
            else:
                tp='Next'
            title=tp+' :'+lng+' '+tm+' '+nm+' '+cat
            self.m_list.append(cat_(title,lnk))
        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)
        return
		
    def get_player_url(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        pu=selectMatch(url)
        if pu:
            pu=pu.replace('\\','')
            self.play_match(pu)

		
    def ok(self):
        if self.info=='get_matches':
            self.get_player_url()
        else:
            self.close()
			
    def exit(self):
        if self.info=='get_matches':
            self.close()
        elif self.info=='player':
            self.show()
            self.get_matches()
            self.session.nav.playService(old_ref)			
    
    def play_match(self, url):
        self.info='player'
        cookieJar=get365CookieJar(True)
        page=getUrl(url,headers=headers, cookieJar=cookieJar)
        kkey=get365Key(cookieJar,useproxy=False)
        print page
        nlnk=re.findall('src="(.*?)" width="768"',page)	
        if nlnk:
            nlnk=nlnk[0].replace('&#48;','0').replace('&#49;','1').replace('&#50;','2').replace('&#51;','3').replace('&#52;','4').replace('&#53;','5').replace('&#54;','6').replace('&#55;','7').replace('&#56;','8').replace('&#57;','9').replace('&#97;','a').replace('&#98;','b').replace('&#99;','c').replace('&#100;','d').replace('&#101;','e').replace('&#102;','f').replace('&#103;','g').replace('&#104;','h').replace('&#105;','i').replace('&#106;','j').replace('&#107;','k').replace('&#108;','l').replace('&#109;','m').replace('&#110;','n').replace('&#111;','o').replace('&#112;','p').replace('&#113;','q').replace('&#114;','r').replace('&#115;','s').replace('&#116;','t').replace('&#117;','u').replace('&#118;','v').replace('&#119;','w').replace('&#120;','x').replace('&#121;','y').replace('&#122;','z')
            page1=getUrl(nlnk,headers=headers, cookieJar=cookieJar)
            post_page=re.findall('<script src=\'(.*?)\'></script>',page1)[0]
            reg1=re.findall('<input type="hidden" name="r" value="(.*?)">',page1)
            reg2=re.findall('<input type="hidden" name="d" value="(.*?)">',page1)
            reg3=re.findall('<input type="hidden" name="f" value="(.*?)">',page1)
            data = urllib.urlencode({'r' : reg1[0],'d':reg2[0],'f':reg3[0]})
            req = urllib2.Request('http://h5.adshell.net/peer5', data)
            response = urllib2.urlopen(req)
            ans = response.read()
            enclink=re.findall("};.*?\('.*?', '.*?', '(.*?)', 1\);var vjs",ans)[0]
            enclink=json.loads(enclink.decode("base64"))
            ct=enclink["ct"].decode("base64")
            import jscrypto
            lnk=jscrypto.decode(enclink["ct"],kkey,enclink["s"].decode("hex"))
            print 'dec link',lnk                    
            enclink=lnk
            print enclink
            enclink=str(enclink).replace('\\','').replace('"','')
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, enclink)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()	

def getUrl(mainurl, cookieJar=None,post=None, timeout=20, headers=None, useproxy=True):
    global lastfinalurl
    lastfinalurl=''
    url=mainurl
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    req = urllib2.Request(url)
    req.add_header('User-Agent',useragent)
    if headers:
        for h,hv in headers:
            req.add_header(h,hv)
    
    if '|' in url:
        url,header_in_page=url.split('|')
        header_in_page=header_in_page.split('&')
        
        for h in header_in_page:
            
            n,v=h.split('=')
            req.add_header(h,v)
    link=""
    try:
        response = opener.open(req,post,timeout=timeout)

        lastfinalurl = response.geturl()
        link=response.read()
        response.close()
    except: pass
    if link=="" and useproxy: 
        
        for retry in range(4):
            try:
                link=getUrlWithWebProxy(mainurl,cookieJar,post,timeout,headers)
                if not link=="": break
            except: pass
    return link;

def unwise_func( 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)#.join('');
    I1lI = ''.join(l1lI)#.join('');
    ll1I = 0;
    l1ll = [];
    for lIll in range(0,len(ll1l),2):
        #print 'array i',lIll,len(ll1l)
        ll11 = -1;
        if ( ord(I1lI[ll1I]) % 2):
            ll11 = 1;
        #print 'val is ', lI1l[lIll: lIll+2]
        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:
#        print 'STILL GOing'
        ret=re.compile('eval\(function\(w,i,s,e\).*}\((.*?)\)').findall(ret)[0]
        return get_unwise(ret)
    else:
#        print 'FINISHED'
        return ret
def get_unwise( str_eval):
    page_value=""
    try:
        ss="w,i,s,e=("+str_eval+')'
        exec (ss)
        page_value=unwise_func(w,i,s,e)
    except: traceback.print_exc(file=sys.stdout)
    #print 'unpacked',page_value
    return page_value  
def get365CookieJar(updatedUName=False):
    cookieJar=None
    try:
        cookieJar = cookielib.LWPCookieJar()
        if not updatedUName:
            cookieJar.load(S365COOKIEFILE,ignore_discard=True)
    except: 
        cookieJar=None

    if not cookieJar:
        cookieJar = cookielib.LWPCookieJar()
    return cookieJar
    
def get365Key(cookieJar,url=None, useproxy=True):
    headers=[('User-Agent',useragent)]
    import time
    if not url:
        mainhtml=getUrl("http://www.sport365.live/de/home",headers=headers, cookieJar=cookieJar)
        try:
            kurl=re.findall('src="(.*?)"></script>',mainhtml)[8]
        except:
            kurl='http://s1.medianetworkinternational.com/js/advertisement.js?'+str(int(time.time()))
    else:
        kurl=url
    import os
    
    khtml=getUrl(kurl,headers=headers, cookieJar=cookieJar)
    print kurl
 
    if khtml=="": 
        kkey=getUrl(kurl,headers=headers, cookieJar=cookieJar)        

    kstr=re.compile('eval\(function\(w,i,s,e\).*}\((.*?)\)').findall(khtml)[0]
    kunc=get_unwise(kstr)
    print kunc   
    import pyaes
    reg="ab5f9063d9ddd3200009cb49b10c2d63".decode("hex")
    keycaller=os.path.dirname(os.path.realpath(__file__)).split('.video.')[-1].encode("hex")+"00000000000000000000000000000000" 
    de = pyaes.new(keycaller[:32].decode("hex"), pyaes.MODE_ECB)
    kkey=re.findall(de.decrypt(reg).replace('\x00', '').split('\0')[0],kunc)
    kkey=re.findall('\{return "(.*?)";',kunc)
    return kkey[0]

def total_seconds(dt):
    # Keep backward compatibility with Python 2.6 which doesn't have
    # this method
    import datetime
    if hasattr(datetime, 'total_seconds'):
        return dt.total_seconds()
    else:
        return (dt.microseconds + (dt.seconds + dt.days * 24 * 3600) * 10**6) / 10**6
        
def getutfoffset():
    import time
    from datetime import datetime

    ts = time.time()
    utc_offset = total_seconds((   datetime.fromtimestamp(ts)-datetime.utcfromtimestamp(ts)))/60
              
    return int(utc_offset)

def selectMatch(url):

    try:
        cookieJar=get365CookieJar()
        mainref='http://www.sport365.live/de/main'
        headers=[('User-Agent',useragent)]
        try:
            getUrl("http://www.sport365.live/",headers=headers, cookieJar=cookieJar)
            mainref=lastfinalurl
        except: pass
        
        url=select365(url,cookieJar,mainref)
        print 'playurl',url
        return url

    except:
        traceback.print_exc(file=sys.stdout)
        return None
def select365(url,cookieJar,mainref):
    print 'select365',url
    #url=base64.b64decode(url)
    retUtl=""
    
    try:
        links=[]
        matchhtml=getUrl(url,cookieJar=cookieJar,headers=[('X-Requested-With','XMLHttpRequest'),('Referer',mainref)])        
        reg=".open\('(.*?)'.*?>(.*?)<"
        sourcelinks=re.findall(reg,matchhtml)
        b6=False
        b7=False

        enc=False
        if 1==2 and len(sourcelinks)==0:
            reg="showPopUpCode\\('(.*?)'.*?\\.write.*?d64\\(\\\\\\'(.*?)\\\\\\'\\)"
            sourcelinks=re.findall(reg,matchhtml)
            #print 'f',sourcelinks
            b6=True
        if 1==2 and len(sourcelinks)==0:
            reg="showPopUpCode\\('(.*?)'.*?\\.write.*?atob\\(\\\\\\'(.*?)\\\\\\'\\)"
            sourcelinks=re.findall(reg,matchhtml)
            #print 's',sourcelinks
            b6=True            
        if len(sourcelinks)==0:
            reg="showWindow\\('(.*?)',.*?>(.*?)<"
            sourcelinks=re.findall(reg,matchhtml)
            #print sourcelinks
            enc=True    
            b6=False
        if len(sourcelinks)==0:
            reg="showPopUpCode\\(.*?,.?'(.*?)'.*?,.*?,(.*?)\\)"
            sourcelinks=re.findall(reg,matchhtml)
            #print sourcelinks
            enc=True    
            b6=False
        if len(sourcelinks)==0:
            reg="<td class='row.' wid.*?>(.*?)<.*?onC.*?\\('(.*?)'"
            sourcelinks=re.findall(reg,matchhtml)
            #print sourcelinks
            enc=True    
            b7=True
            
        #print 'sourcelinks',sourcelinks
        kkey=get365Key(get365CookieJar())
        if len(sourcelinks)==0:
            #print 'No links',matchhtml
            #addDir(Colored("  -"+"No links available yet, Refresh 5 mins before start.",'') ,"" ,0,"", False, True,isItFolder=False)		#name,url,mode,icon
            return ""
        else:
            available_source=[]
            ino=0
            for curl,cname in sourcelinks:
                ino+=1
                try:
                    if b7:
                       curl,cname=cname,curl 
                    if b6:
                        curl,cname=cname,curl
                        #print b6,curl
                        curl=base64.b64decode(curl)
                        curl=re.findall('(http.*?)"',curl)[0]#+'/768/432'
                    if enc:
                        #print curl
                        curl=json.loads(curl.decode("base64"))
                        import jscrypto
                        #print curl["ct"],kkey,curl["s"]
                        curl=jscrypto.decode(curl["ct"],kkey,curl["s"].decode("hex"))
                        #print curl
                        curl=curl.replace('\\/','/').replace('"',"")
                        #print 'fina;',curl
                        if 'window.atob' in curl:
                            reg="window\\.atob\(\\\\(.*?)\\\\\\)"
                            #print 'in regex',reg,curl
                            curl=re.findall(reg,curl)[0]
                            curl=base64.b64decode(curl)
                            curl=re.findall('(http.*?)"',curl)[0]#+'/768/432'
                            if not curl.split('/')[-2].isdigit():
                                curl+='/768/432'
                                
                    #print curl
                    #return curl
                    #cname=cname.encode('ascii', 'ignore').decode('ascii')
                    ##if not cname.startswith('link'):
                    #cname='source# '+str(ino)
                    #available_source.append(cname)
                    #links+=[[cname,curl]]
                except:
                    traceback.print_exc(file=sys.stdout)
            #if len(curl)==0:
            #    return ""
            #if len(curl)==1:
            #    return links[0][1]
    except:
        traceback.print_exc(file=sys.stdout)
    return curl

    
def getCookiesString(cookieJar,cookieName=None):
    try:
        cookieString=""
        for index, cookie in enumerate(cookieJar):
            print index, cookie
            if cookieName==None:
                cookieString+=cookie.name + "=" + cookie.value +";"
            elif (cookieName==cookie.name or cookieName in cookie.name ):
                cookieString=cookie.name + "=" + cookie.value +";"
    except: pass
    #print 'cookieString',cookieString
    return cookieString	