# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/ilive_new.py
from imports import *
import json
import math
cj = {}
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

def doCtoD(c):
    if len(c) > 0:
        d = ''
        ic = len(c)
        i = 0
        while i < ic:
            try:
                if i % 3 == 0:
                    d += '%'
                else:
                    d += c[i]
            except:
                pass

            i = i + 1

        d = urllib.unquote_plus(d)
        return d
    else:
        return ''


def doXTtoXZ(x, tS, b = 1024, p = 0, s = 0, w = 0, r2 = ''):
    l = len(x)
    t = tS.split(',')
    r = []
    for j in range(int(math.ceil(l / b)), 0, -1):
        for i in range(min(l, b), 0, -1):
            w |= int(t[ord(x[p]) - 48]) << s
            p += 1
            if s:
                r.append(chr(165 ^ w & 255))
                w >>= 8
                s -= 2
            else:
                s = 6

        l -= 1

    r = ''.join(r)
    return r


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):
    res = [(name, link, image)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, 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 ilive(Screen):

    def __init__(self, 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()
        self.session = session
        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,
         'red': self.exit,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('ILive')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.abc)

    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 switchList(self):
        if self.currentList == 'menulist':
            self['ButtonBlue'].hide()
            self['TextBlue'].hide()
            self['menulist'].selectionEnabled(0)
            self.currentList = 'menulist2'
            self.check = 'abc'
        else:
            self['ButtonBlue'].show()
            self['TextBlue'].show()
            self['menulist'].selectionEnabled(1)
            self.currentList = 'menulist'
            self.check = 'letter_movie'

    def abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_list = []
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'sports'
        i = 1
        url = 'http://www.streamlive.to/channels/?p=%s&sort=1' % i
        getPage(url, method='GET', cookies=cj, headers={'Host': 'www.streamlive.to',
         'Referer': 'http://www.streamlive.to/',
         'Content-Type': 'application/x-www-form-urlencoded',
         'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.load_data_channels)

    def load_data_channels(self, data):
        print data
        if 'To prove that you are' in data:
            puzzle = re.findall('Question: .*?: (.*?)<br /><br />', data)
            print puzzle
            if puzzle:
                post = urllib.urlencode({'captcha': puzzle[0]})
                print post
                i = 1
                url = 'http://www.streamlive.to/channels/?p=%s&sort=1' % i
                getPage(url, method='POST', cookies=cj, postdata=post, headers={'Host': 'www.streamlive.to',
                 'Origin': 'http://www.streamlive.to',
                 'Referer': 'http://www.streamlive.to/channels/?p=2&sort=1',
                 'Content-Type': 'application/x-www-form-urlencoded',
                 'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.load_data_channels1)
        else:
            i = 1
            url = 'http://www.streamlive.to/channels/?p=%s&sort=1' % i
            getPage(url, method='GET', cookies=cj, headers={'Host': 'www.streamlive.to',
             'Origin': 'http://www.streamlive.to',
             'Referer': 'http://www.streamlive.to/channels/?p=2&sort=1',
             'Content-Type': 'application/x-www-form-urlencoded',
             'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.load_data_channels1)

    def load_data_channels1(self, data):
        print data
        if 'Answer is wrong' in data:
            self.load_data_channels(data)
        else:
            i = 1
            while i < 24:
                url = 'http://www.streamlive.to/channels/?p=%s&sort=1' % i
                getPage(url, method='GET', cookies=cj, headers={'Host': 'www.streamlive.to',
                 'Origin': 'http://www.streamlive.to',
                 'Referer': 'http://www.streamlive.to/channels/?p=2&sort=1',
                 'Content-Type': 'application/x-www-form-urlencoded',
                 'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.load_data_channels2)
                i += 1

    def load_data_channels2(self, data):
        channels = re.findall('<a href="(.*?)" title="(.*?)" class="clist-thumb">', data)
        if channels:
            for each in channels:
                url, title = each
                print url
                url = url.replace('view', 'embed')
                title = title.replace('%28', '(').replace('%29', ')').replace('%3A', ':').replace('%26', '&').replace('%27', '`').replace('%2F', '/')
                self.letter_list.append(show_(title, url, None))

            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            return
        else:
            return

    def ok(self):
        if self.check == 'abc':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            uri = selectedEntry
            print uri
            token_url = 'http://www.streamlive.to/server.php?id=1422814097'
            req = urllib2.Request(token_url)
            print token_url
            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', 'http://www.ilive.to/view/46465/Fox_News-live-stream-channel')
            page = urllib2.urlopen(req)
            r = page.read()
            token = re.findall('"token"\\:"(.*?)"', r)
            print token
            token = token[0]
            uri = str(uri).replace('embed-now', 'embed')
            req = urllib2.Request(uri)
            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('Referer', 'http://www.ilive.to/channels/?sort=1')
            p = urllib2.urlopen(req)
            response = p.read()
            print response
            new_page = re.findall('document.write\\("<iframe src=\'(.*?)\' frameborder=', response)
            print new_page
            ch_id = re.findall('480&channel=(.*?)/', new_page[0])
            ch_id = ch_id[0]
            req = urllib2.Request(new_page[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('Referer', 'http://www.streamlive.to/channels/?sort=1')
            req.add_header('Cookie', str(cj))
            p = urllib2.urlopen(req)
            response = p.read()
            if 'answer this question' in response:
                puzzle = re.findall('Question: .*?: (.*?)<br /><br />', response)
                print puzzle
                if puzzle:
                    post = urllib.urlencode({'captcha': puzzle[0]})
                    print post
                    url = new_page[0]
                    req = urllib2.Request(url, post)
                    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('Referer', 'http://www.streamlive.to/channels/?sort=1')
                    req.add_header('Cookie', 'PHPSESSID=cgg482oklv2g9oge2no2ab4k05; __gads=ID=e32632c261e92a23:T=1434810969:S=ALNI_MbkeZdTIZ6ZjTTpgCzf5yOg4JZDpw; captcha_keystring=qIGebHM4iUabU4qwuDAiPvpMyhixkbjpLZ7lysNghyztuiDRtmh9nVuxJpL15KAzXSVl5CaFnmoNUb9ovI9BmLF%2B1LF3f%2BumUCQlZ2maGT4RnUrCusD7Or9lAC5krahL%7Cih03O%2FXKrilUMtWiQh8cgvU99vfoVYpWx9AqcnueOsQ%3D; antiware=47fp%2BU4Zp%2BfUcP%2BxSK92YTE%2BF4hE4BE8kgzyxW83P7okIaze%2FOqcxvzMjGFQxZXMUF0FLFO31huHMt4CUyBHc11M9fi%2FKQ74Do77zHHek4DiOCgrRx1Zqj03WJhMSfr1%7Cakh%2FMmFuVuIIzIlXuJWRW9fczKNXsDEOIDOx3wKMQnE%3D')
                    p = urllib2.urlopen(req)
                    response = p.read()
            auth_url = 'http://www.streamlive.to/tv-ajax.php'
            postdata = 'action=getchannel4channel&id=undefined'
            req = urllib2.Request(auth_url)
            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('Referer', 'http://www.streamlive.to/channels/?sort=1')
            p1 = urllib2.urlopen(req, postdata)
            p2 = p1.read()
            print 'auth_done'
            if '<script language=javascript>c="' in response:
                c = re.compile('<script language=javascript>c="(.+?)"').findall(response)[0]
                cu = urllib.unquote_plus(c)
                d = doCtoD(c)
                t = re.compile('t=Array\\(([0-9,]+)\\)').findall(d)[0]
                x = re.compile('"\\)\\);\\s*x\\("(.+?)"').findall(response)[0]
                z = doXTtoXZ(x, t)
                if z:
                    link = '' + z
                else:
                    link = response
            pageUrl = 'http://www.streamlive.to/'
            playpath = re.compile('.*file[:,]\\s*[\'"]([^\'"]+).flv[\'"]').findall(response)
            if playpath:
                playpath = playpath[0]
                newplaypath = str(playpath)
                rtmp = re.compile('streamer: "(.+?)"').findall(response)
                hls = re.findall("'file': '(.*?)',", response)
                print hls
                if rtmp:
                    print rtmp
                    rtmp = rtmp[0]
                    newrtmp = str(rtmp)
                    newrtmp = newrtmp.replace('\\/', '/').replace('\\', '')
                    app = '' + newrtmp
                    app = app.split('?xs=')[1]
                    app2 = re.compile('rtmp://[\\.\\w:]*/([^\\s]+)').findall(newrtmp)[0]
                    try:
                        ReplacementA = re.compile('(rtmp://[0-9A-Za-z]+\\.ilive\\.to:\\d+/)').findall(app)[0]
                    except:
                        ReplacementA = ''

                    if len(ReplacementA) > 0:
                        app = app.replace(ReplacementA, '')
                    newapp = str(app)
                    swf = 'http://www.streamlive.to/ads/streamlive.swf'
                    TimeOut = '15'
                    playable = '%s/%s swfUrl=%s pageUrl=%s token=%s' % (newrtmp,
                     newplaypath,
                     swf,
                     pageUrl,
                     token)
                    print 'RTMP IS ' + playable
                    self.play_that_shit(playable)
            else:
                print response
                if 'answer this question' in response:
                    puzzle = re.findall('Question: .*?: (.*?)<br /><br />', response)
                    print puzzle
                    if puzzle:
                        post = urllib.urlencode({'captcha': puzzle[0]})
                        print post
                        url = new_page[0]
                        req = urllib2.Request(url, post)
                        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('Referer', 'http://www.streamlive.to/channels/?sort=1')
                        req.add_header('Cookie', str(cj))
                        p = urllib2.urlopen(req)
                        response = p.read()
                        print response
                auth_url = 'http://www.streamlive.to/tv-ajax.php'
                postdata = 'action=getchannel4channel&id=undefined'
                req = urllib2.Request(auth_url)
                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('Referer', 'http://www.streamlive.to/channels/?sort=1')
                p1 = urllib2.urlopen(req, postdata)
                p2 = p1.read()
                print 'auth_done'
                if '<script language=javascript>c="' in response:
                    c = re.compile('<script language=javascript>c="(.+?)"').findall(response)[0]
                    cu = urllib.unquote_plus(c)
                    d = doCtoD(c)
                    t = re.compile('t=Array\\(([0-9,]+)\\)').findall(d)[0]
                    x = re.compile('"\\)\\);\\s*x\\("(.+?)"').findall(response)[0]
                    z = doXTtoXZ(x, t)
                    if z:
                        link = '' + z
                    else:
                        link = response
                pageUrl = 'http://www.streamlive.to/'
                playpath = re.compile('.*file[:,]\\s*[\'"]([^\'"]+).flv[\'"]').findall(response)
                print playpath
                print response
                if playpath:
                    playpath = playpath[0]
                    newplaypath = str(playpath)
                    rtmp = re.compile('streamer: "(.+?)"').findall(response)
                    hls = re.findall("'file': '(.*?)',", response)
                    print hls
                    if rtmp:
                        print rtmp
                        rtmp = rtmp[0]
                        newrtmp = str(rtmp)
                        newrtmp = newrtmp.replace('\\/', '/').replace('\\', '')
                        app = '' + newrtmp
                        app = app.split('?xs=')[1]
                        app2 = re.compile('rtmp://[\\.\\w:]*/([^\\s]+)').findall(newrtmp)[0]
                        try:
                            ReplacementA = re.compile('(rtmp://[0-9A-Za-z]+\\.ilive\\.to:\\d+/)').findall(app)[0]
                        except:
                            ReplacementA = ''

                        if len(ReplacementA) > 0:
                            app = app.replace(ReplacementA, '')
                        newapp = str(app)
                        swf = 'http://www.streamlive.to/ads/streamlive.swf'
                        TimeOut = '15'
                        playable = '%s/%s swfUrl=%s pageUrl=%s token=%s' % (newrtmp,
                         newplaypath,
                         swf,
                         pageUrl,
                         token)
                        print 'RTMP IS ' + playable
                        self.play_that_shit(playable)

    def play_that_shit(self, data):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        self.close()

    def load_poster_teledunet(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/teledunet_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/teledunet/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 '[teledunet] 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 '[teledunet] no cover.. error'
        return

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found, try again later on'), MessageBox.TYPE_INFO, timeout=3)

    def errorload2(self, error):
        print '[teledunet] error %s' % error
        count_movies = len(self.letter_movielist)
        self.loading_ok = True
        self.loading = 0
        self.count = 0

    def errorload(self, error):
        print error

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