# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/wizi.py
from imports import *
import os
from StringIO import StringIO
import gzip
from Tools.Directories import fileExists, pathExists
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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=8, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class wizi(Screen):

    def __init__(self, session):
        global old_ref
        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('Wiziwig-Lag10')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.index = ''
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.start)

    def about(self):
        self.close()

    def up(self):
        self[self.currentList].up()

    def down(self):
        self[self.currentList].down()

    def left(self):
        self[self.currentList].pageUp()

    def right(self):
        self[self.currentList].pageDown()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        url = str(selectedEntry)
        getPage(url, timeout=8, method='GET', headers={'Host': 'www.wiz1.net',
         'Referer': 'http://wiz1.net/channel68',
         '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_saw_link, url)

    def start(self):
        url = 'http://www.wiz1.net/lag10_home.php'
        getPage(url, timeout=8, method='GET', headers={'Referer': 'http://www.wiz1.net',
         'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_channels)

    def get_channels(self, data):
        self.channel_list = []
        channels = re.findall('(\\d\\d:\\d\\d) <font color="\\#5185C9"><b>(.*?)</b></font>(.*?)<a href="(.*?)" target="_blank">', data)
        print channels
        for time, league, title, url in channels:
            info = time + ' - ' + league + ' - ' + title
            url = url.replace('channel', 'ch')
            self.channel_list.append(cat_(info, url))
            print url

        self['menulist'].l.setList(self.channel_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def get_saw_link(self, data, ref):
        saw_ln = re.findall('<script type="text/javascript" src="(http://www3.sawlive.tv/embed/.*?)"></script>', data)
        if saw_ln:
            print 'Hoster : sawlive'
            print saw_ln
            req = urllib2.Request(saw_ln[0])
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
            req.add_header('X-Requested-With', 'XMLHttpRequest')
            req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
            req.add_header('Referer', ref)
            req.add_header('Host', 'www3.sawlive.tv')
            req.add_header('Cookie', '__cfduid=d19787702c573dacba1ce3d66f52fd1d61443121626')
            page = urllib2.urlopen(req)
            r = page.read()
            data_to_unpack = re.findall('(eval\\(function\\(p,a,c,k,e,d\\).*?\\{\\}\\)\\))', r)
            if data_to_unpack:
                unpacked = self.unpackByString(data_to_unpack[0])
                var1 = re.findall(";Tamrzar.push\\('(.*?)'\\)", unpacked)
                var1_list = []
                for x in var1:
                    var1_list.append(x)

                streamer_to_decode = str(var1_list).replace("['", '').replace("'", '').replace(']', '').replace(',', '').replace(' ', '')
                streamer = urllib.unquote(streamer_to_decode)
                unpacked1 = self.unpackByString(data_to_unpack[6])
                str_to_decode = re.findall("unescape\\('(.*?)'\\)", unpacked1)
                str_dec = str_to_decode[0]
                file = urllib.unquote(str_dec)
                print file
                file = file.replace('%0', '')
                fl = re.findall('(.*?)">', file)
                fl = fl[0]
                new_url = re.findall('src="(http://.*?sawlive.tv/embed/watch/.*?)/', streamer)
                url = new_url[0] + '/' + fl
                print url
                cj = {}
                getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host': 'www3.sawlive.tv',
                 'Referer': 'http://www.wiz1.net/ch21',
                 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.get_saw_link1, url)
            else:
                print r
                ch = re.findall("var ch='(.*?)'", r)
                sw = re.findall("var sw='(.*?)'", r)
                var_chz = re.findall("var chz='(.*?)'", r)
                swz = re.findall("var swz='(.*?)'", r)
                za3 = re.findall("var za3='(.*?)'", r)
                url = re.findall('src="(.*?)\\+\'"></iframe>', r)
                stringlast = re.findall('\\+unezcapez\\(\'(.*?)\'\\)\\+\'"></iframe>', r)
                if url and var_chz:
                    url = 'http://www3.sawlive.tv/embed/watch/' + urllib.unquote(var_chz[0]) + '/b' + urllib.unquote(stringlast[0])
                    cj = {}
                    getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host': 'www3.sawlive.tv',
                     'Referer': 'http://www.wiz1.net/ch21',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.get_saw_link1, url)
                else:
                    vars = re.findall('var (.*?)="(.*?)";', r)
                    print vars
                    var_sw = re.findall("var sw='(.*?)';", r)
                    if var_sw:
                        var1 = vars[0][1]
                        var2 = vars[1][1]
                        var3 = vars[2][1]
                        var4 = vars[3][1]
                        ch = var1 + var2 + var3 + var4
                        print ch
                        link = 'http://www3.sawlive.tv/embed/watch/' + ch + '/' + sw[0]
                        print link
                        cj = {}
                        getPage(link, timeout=8, method='GET', cookies=cj, headers={'Host': 'www3.sawlive.tv',
                         'Referer': 'http://www.wiz1.net/ch21',
                         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.get_saw_link1, link)
                    else:
                        print 'sawlive changed method again'

    def javascriptUnEscape(self, str):
        for j in str:
            str = str.replace(j, urllib.unquote(j))

        return str

    def get_saw_link1(self, data, url):
        print 'final step' + data
        print url
        file = re.findall("so\\.addVariable\\('file', '(.*?)'\\);", data)
        streamer = re.findall("'streamer': '(.*?)'", data)
        print file
        print streamer
        if 'http://sawlive.tv/streams/' in str(file[0]):
            file = 'http://127.0.0.1:88/hlsvariant://' + file[0] + ' headers={"Referer":"http://sawlive.tv","User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"}'
            self.play_that_shit(file)
        else:
            file = 'rtmp://75.126.73.5/flash/' + file[0] + ' swfurl=http://static2.sawlive.tv/player.swf pageurl=' + url
            self.play_that_shit(file)

    def play_that_shit(self, data):
        self.index = 'player'
        if data:
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, data)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()

    def unpackByString(self, sJavascript):
        aSplit = sJavascript.split(";',")
        if len(aSplit) == 1:
            print 'packed type 2'
            aSplit = sJavascript.split(";}',")
        else:
            print 'packed type 1'
        p = str(aSplit[0])
        aSplit = aSplit[1].split(',')
        a = int(aSplit[0])
        c = int(aSplit[1])
        k = aSplit[2].split('.')[0].replace("'", '').split('|')
        e = ''
        d = ''
        sUnpacked = str(self.__unpack(p, a, c, k, e, d))
        return sUnpacked.replace('\\', '')

    def __unpack(self, p, a, c, k, e, d):
        while c > 1:
            c = c - 1
            if k[c]:
                p = re.sub('\\b' + str(self.__itoa(c, a)) + '\\b', k[c], p)

        return p

    def __itoa(self, num, radix):
        result = ''
        while num > 0:
            result = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[num % radix] + result
            num /= radix

        return result

    def exit(self):
        if self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'get_channels'
            self['menulist'].l.setList(self.channel_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        else:
            self.close()