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

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 cricfree(Screen):

    def __init__(self, session):
        global old_ref
        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,
         'cancel': self.exit,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['title'] = Label('Cricfree - Liveevents')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        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 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://cricfree.sx/'
        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://cricfree.sx/')
        page = urllib2.urlopen(req)
        response = page.read()
        matches = re.findall('<td class="matchtime" style=".*?">(.*?)</td>\\s<td><span class="country-icon.*?"></span></td>\\s<td>.*?</td>\\s<td style=".*?;" href="(.*?)" target="_blank">(.*?)</a></td>', response, re.DOTALL)
        print matches
        if matches:
            for each in matches:
                time, url, match = each
                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://cricfree.sx/')
            page = urllib2.urlopen(req)
            response = page.read()
            print response
            update_parameter = re.findall('<tr><td><a href="(.*?)" target="iframe_a">', response)
            if update_parameter:
                uri = 'http://cricfree.sx' + update_parameter[0]
                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://cricfree.sx/')
                page = urllib2.urlopen(req)
                response = page.read()
                print response
                page_param = re.findall("<script type='text/javascript'>fid='(.*?)'; v_width=620; v_height=490;</script><script type='text/javascript' src='http://www.reytv.co/player.js'></script>", response)
                #print page_param
                if page_param:
                    url = 'http://www.reytv.co/embed.php?live=' + page_param[0]
                    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.reytv.co')
                    req.add_header('Referer', 'http://cricfree.sx/update/atraces.php')
                    page = urllib2.urlopen(req)
                    response = page.read()
                    print response
                    file = re.findall('file: "(.*?)",', response)
                    re_dir_url = file[0].split('/')
                    print re_dir_url
                    securetoken = re.findall('securetoken: "(.*?)"', response)
                    swf = 'http://p.jwpcdn.com/6/11/jwplayer.flash.swf'
                    player_url = file[0] + ' swfurl=' + swf + ' token=' + securetoken[0] + ' playpath=' + page_param[0] + ' pageurl=' + url
                    print player_url
                    self.play_that_shit(player_url)
                else:                             #<script type='text/javascript'>id='sk3'; width='620'; height='490';</script><script type='text/javascript' src='http://theactionlive.com/livegamecr.js'></script>
                    update_parameter = re.findall("<script type='text/javascript'>id='(.*?)'; width=.*?</script><script type='text/javascript' src='http://theactionlive.com/livegamecr.js'></script>", response)
                    if update_parameter:
                        url = 'http://chupala.biggestplayer.me/streamt.php?id=' + update_parameter[0] + '&width=620&height=460'
                        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', 'chupala.biggestplayer.me')
                        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
                        req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
                        req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
                        req.add_header('Connection', 'keep-alive')
                        req.add_header('Referer', 'http://theactionlive.com/livegamecrnope.php?id=sk3&width=620&height=490&stretching=')
                        response = urllib2.urlopen(req)
                        buf = StringIO(response.read())
                        f = gzip.GzipFile(fileobj=buf)
                        data = f.read()
                        id = re.findall("<script type='text/javascript'>id='(.*?)';", data)
                        print id
                        if id:
                            try:
                                url = 'http://chupala.biggestplayer.me/streamcr.php?id=' + id[0] + '&width=640&height=460&stretching='
                                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', 'chupala.biggestplayer.me')
                                req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
                                req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
                                req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
                                req.add_header('Connection', 'keep-alive')
                                req.add_header('Referer', 'http://theactionlive.com/livegamecr.php?id=feed21&width=620&height=490&stretching=')
                                response = urllib2.urlopen(req)
                                buf = StringIO(response.read())
                                f = gzip.GzipFile(fileobj=buf)
                                data = f.read()
                                streamer = re.findall('file: "(.*?)"', data)
                                if streamer:
                                    final_url = streamer[0]
                                    self.play_that_shit(final_url)
                                else:
                                    file = re.findall('file: "(.*?)"', data)
                                    if file:
                                        self.play_that_shit(file[0])
                            except:
                                pass

                    else:
                        page_param = re.findall("<script type='text/javascript'>fid='(.*?)'; v_width=...; v_height=...;</script><script type='text/javascript' src='http://www.yotv.co/player.js'></script>", response)
                        if page_param:
                            player_url = 'http://yotv.co/embedo.php?live=' + page_param[0] + '&vw=620&vh=490'
                            req = urllib2.Request(player_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', 'yotv.co')
                            req.add_header('Referer', 'http://cricfree.sx/update/atraces.php')
                            page = urllib2.urlopen(req)
                            response = page.read()
                            print response
                            file = re.findall('file: "(.*?)",', response)
                            token = re.findall('securetoken: "(.*?)"', response)
                            if file:
                                final_url = file[0].replace('/redirect', ':80/live')
                                fin = 'rtmp://31.220.2.149:80/live/' + page_param[0] + ' token=%Zrey(nKa@#Z swfurl=http://p.jwpcdn.com/6/12/jwplayer.flash.swf pageurl=http://yotv.co/embedo.php?live=ss2r&vw=620&vh=490'
                                print fin
                                self.play_that_shit(fin)
                        else:
                            page_param = re.findall('<iframe id="player" scrolling="no" width="..." height="..." allowtransparency="no" frameborder="0" src="http://www.wiz1.net/(.*?)"></iframe>', response)
                            if page_param:
                                player_url = 'http://www.wizi1.net/' + page_param[0]
                                req = urllib2.Request(player_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', 'wizi1.net')
                                req.add_header('Referer', 'http://www.wizi1.net')
                                page = urllib2.urlopen(req)
                                response = page.read()
                                print response
                                iframe = re.findall('<script type="text/javascript"> swidth="640", sheight="460";</script><script type="text/javascript" src="http://www3.sawlive.tv/embed/(.*?)"></script>', response)
                                if iframe:
                                    print 'Hoster : sawlive'
                                    req = urllib2.Request(iframe[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', 'http://www.wagasworld.com')
                                    req.add_header('Host', 'sawlive.tv')
                                    page = urllib2.urlopen(req)
                                    r = page.read()
                                    print r
                                    new_url = re.findall('src="(.*?)">', r)
                                    if new_url:
                                        req = urllib2.Request(new_url[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', 'http://www.wagasworld.com')
                                        req.add_header('Host', 'sawlive.tv')
                                        page = urllib2.urlopen(req)
                                        r = page.read()
                                        flashplayer = re.findall("new SWFObject\\('(.*?)',", r)
                                        file = re.findall("'file', '(.*?)'\\);", r)
                                        streamer = re.findall("'streamer', '(.*?)'\\);", r)
                                        final_url = streamer[0] + ' playpath=' + file[0] + ' swfurl=' + flashplayer[0] + ' pageurl=' + new_url[0]
                                        self.play_that_shit(final_url)
                                    else:
                                        data_to_unpack = re.findall('(eval\\(function\\(p,a,c,k,e,d\\).*?,0,\\{\\}\\)\\))', 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)
                                            new_url = re.findall('src="(.*?)">', streamer)
                                            if new_url:
                                                req = urllib2.Request(new_url[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', 'http://www.wagasworld.com')
                                                req.add_header('Host', 'sawlive.tv')
                                                page = urllib2.urlopen(req)
                                                r = page.read()
                                                flashplayer = re.findall("new SWFObject\\('(.*?)',", r)
                                                file = re.findall("'file', '(.*?)'\\);", r)
                                                streamer = re.findall("'streamer', '(.*?)'\\);", r)
                                                final_url = streamer[0] + ' playpath=' + file[0] + ' swfurl=' + flashplayer[0] + ' pageurl=' + new_url[0]
                                                self.play_that_shit(final_url)
                            else:
                                page_param = re.findall('<script type=\'text/javascript\'>fid=\'(.*?)\'; v_width=620; v_height=490;</script><script type=\'text/javascript\' src=\'http://www.webtv.ws/player.js\'></script>', response)
                                if page_param:
                                    player_url = 'http://www.webtv.ws/embed.php?live=' + page_param[0] +'&vw=620&vh=490'
                                    req = urllib2.Request(player_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.webtv.ws')
                                    req.add_header('Referer', 'http://cricfree.sx')
                                    page = urllib2.urlopen(req)
                                    response = page.read()
                                    print response
                                    source=re.findall('file: "(.*?)"',response)
                                    self.play_that_shit(source[0])
    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(cricfree)


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')]