# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/firstrow.py
from plugin import *
from StringIO import StringIO
import gzip
from jsunpacker import *
from imports import *
from Tools.Directories import fileExists, pathExists

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


class firstrow(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['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('firstrow.ge.eu')
        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 jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    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 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 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'
        url = 'http://firstrowge.eu/'
        self.load_data_channels(url)

    def load_data_channels(self, data):
        print 'got data - now processing channel_list'
        req = urllib2.Request(data)
        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://firstrowge.eu/')
        req.add_header('Host', 'firstrowge.eu')
        page = urllib2.urlopen(req)
        response = page.read()
        matches = re.findall('<span class="matchtime">(.*?)</span> </span>(.*?)</a> </h3> <div>.*?<br> <a  href=\'(.*?)\'', response, re.DOTALL)
        print matches
        if matches:
            for each in matches:
                time, match, url = each
                url = 'http://firstrowge.eu' + url
                print url
                view = time + ' ' + match
                self.letter_list.append(cat_(view, url))

        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    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
            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://firstrowge.eu')
            req.add_header('Host', 'firstrowge.eu')
            page = urllib2.urlopen(req)
            response = page.read()
            print response
            update_parameter = re.findall('<script type="text/javascript" src="(http://www.04stream.com/.*?)"></script>', response)
            if update_parameter:
                uri = update_parameter[0]
                print uri
                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://firstrowge.eu')
                page = urllib2.urlopen(req)
                response = page.read()
                cookie = page.info()['Set-Cookie']
                print response
                page_param = re.findall("src=(.*?)'", response)
                print page_param
                if page_param:
                    url = page_param[0] + 'firstrow'
                    req = urllib2.Request(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('Host', 'www.04stream.com')
                    req.add_header('Cookie', cookie)
                    req.add_header('Referer', 'http://firstrowge.eu')
                    page = urllib2.urlopen(req)
                    response = page.read()
                    match = re.findall('object\\s+id="player1".*?(\'\\+thist\\+\'.*?)&.*?param\\s+name="movie"\\s+value="(.*?)"', response)
                    swf = match[0][1]
                    streamer = match[0][0]
                    print 'streamer : ' + streamer
                    import random
                    ip_list = ['213.152.162.122:1935',
                     '213.152.180.159:1935',
                     '213.152.180.151:1935',
                     '179.43.158.195:1935',
                     '179.43.158.196:1935',
                     '179.43.158.197:1935',
                     '179.43.158.198:1935',
                     '179.43.158.199:1935',
                     '179.43.158.200:1935',
                     '179.43.158.201:1935',
                     '179.43.158.203:1935',
                     '179.43.158.202:1935',
                     '199.195.195.100:1935',
                     '173.192.81.169:1935',
                     '199.189.105.12:1935',
                     '206.190.129.4:1935',
                     '199.195.194.244:1935',
                     '199.195.195.20:1935',
                     '146.185.25.162:1935',
                     '146.185.25.186:1935',
                     '46.28.49.36:1935',
                     '37.130.227.140:1935',
                     '146.185.25.130:1935',
                     '199.195.195.76:1935',
                     '199.195.194.220:1935']
                    streami = 'rtmp://' + random.choice(ip_list)
                    streamer = str(streamer).replace("'+thist+'", streami)
                    page = uri + 'gofeed2all.eu'
                    fin_url = streamer + ' pageurl=' + page + ' swfurl=http://thecdn.04stream.com/p/ooolo1.swf'
                    print fin_url
                    self.play_that_shit(fin_url)
            else:
                update_parameter = re.findall('<iframe allowTransparency="true" id="player"  scrolling="no" width="650" allowtransparency="no" frameborder="0"  src="http://leton.tv/player.php?(.*?)"', response)
                if update_parameter:
                    uri = 'http://leton.tv/player.php' + update_parameter[0]
                    print uri
                    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://firstrowge.eu')
                    page = urllib2.urlopen(req)
                    response = page.read()
                    print response
                    ip_1 = re.findall('var a = (.*?);', response)
                    ip_2 = re.findall('var b = (.*?);', response)
                    ip_3 = re.findall('var c = (.*?);', response)
                    ip_4 = re.findall('var d = (.*?);', response)
                    div = re.findall('var f = (.*?);', response)
                    file = re.findall("var v_part = '(.*?)';", response)
                    if ip_1:
                        ip = str(int(ip_1[0]) / int(div[0])) + '.' + str(int(ip_2[0]) / int(div[0])) + '.' + str(int(ip_3[0]) / int(div[0])) + '.' + str(int(ip_4[0]) / int(div[0]))
                        print ip
                        rtmp_url = 'rtmp://' + ip + file[0]
                        swfurl = 'http://files.leton.tv/jwplayer.flash.swf'
                        pageurl = 'http://leton.tv/player.php?streampage=ww_dokumix6&width=778&height=470'
                        if file:
                            final_url = rtmp_url + ' swfUrl=' + swfurl + ' pageUrl=' + pageurl + ' live=true'
                            print final_url
                            self.play_that_shit(final_url)
                else:
                    update_parameter = re.findall('<iframe allowTransparency="true" id="player"  scrolling="no" width="650" allowtransparency="no" frameborder="0"  src="http://7cast.net/player/(.*?)" height="500">', response)
                    if update_parameter:
                        uri = 'http://7cast.net/player/' + update_parameter[0]
                        print uri
                        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://firstrowge.eu')
                        page = urllib2.urlopen(req)
                        response = page.read()
                        print response
                        data_to_unpack = re.findall('(eval\\(function\\(p,a,c,k,e,d\\).*?,0,\\{\\}\\)\\))', response)
                        unpacked = self.unpackByString(data_to_unpack[0])
                        print unpacked
                        var1 = re.findall(";myRtk.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)
                        var2 = re.findall(";myScrT.push\\('(.*?)'\\)", unpacked)
                        var2_list = []
                        for x in var2:
                            var2_list.append(x)

                        file_to_decode = str(var2_list).replace("['", '').replace("'", '').replace(']', '').replace(',', '').replace(' ', '')
                        file = urllib.unquote(file_to_decode)
                        print streamer
                        print file
                        streamer = 'rtmp://pub.7cast.net/redirects'
                        swf = 'http://7cast.net/jplayer.swf'
                        page = 'http://7cast.net/player/m2ybeurpu3v9nh/650/390'
                        final_url = streamer + '/' + file + ' swfurl=' + swf + ' pageurl=' + page
                        print final_url
                        self.play_that_shit(final_url)
                    else:
                        update_parameter = re.findall('<iframe allowTransparency="true" id="player"  scrolling="no" width="650" allowtransparency="no" frameborder="0"  src="http://vaughnlive.tv/embed/video/(.*?)" height="500">', response)
                        if update_parameter:
                            uri = 'http://vaughnlive.tv/embed/video/' + update_parameter[0]
                            print uri
                            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://firstrowge.eu')
                            page = urllib2.urlopen(req)
                            response = page.read()
                            print response
                            server = re.findall('return "(.*?),', response)
                            server = server[0]
                            file = re.findall('vsVars.*?\\.k2 = "(.*?)";', response)
                            swf = re.findall('swfobject\\.embedSWF\\("(.*?)",', response)
                            token = re.findall('"0m0(.*?)";', response)
                            file = file[0]
                            token = token[0]
                            swf = 'http://vaughnlive.tv' + swf[0]
                            final_url = 'rtmp://' + server + '/live app=live?' + token + ' token=balls2u live=1 swfurl=' + swf + ' pageurl=' + uri + ' playpath=live_' + file
                            self.play_that_shit(final_url)

    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/highlive_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/HighLive/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 '[bkssport_live] 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 '[cricfree] 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 '[cricfree] 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/highlive/'):
            os.system('mkdir /tmp/highlive/')
        else:
            print '[cricfree] /tmp/highlive/ allready present'


def main(session, **kwargs):
    session.open(firstrow)


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='Cricfree - Livestreams', description='watch live events', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]