from imports import *
import requests
from Tools.Directories import fileExists, pathExists
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, img):
    res = [(letter, link, img)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 26), font=4, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class cricfree_perm(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,
         'cancel': self.exit,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['title'] = Label('Cricfree')
        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()
        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()
        self.load_poster_teledunet()

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

    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'
        self.load_data_channels()

    def load_data_channels(self):
        print 'got data - now processing channel_list'
        self.chanlist = []
        self.chanlist.append(cat_('Sky Sports 1', 'http://cricfree.sx/update/skys1.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('Sky Sports 2', 'http://cricfree.sx/update/skys2.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('Sky Sports 3', 'http://cricfree.sx/update/skys3.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('Sky Sports 4', 'http://cricfree.sx/update/skys4.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('Sky Sports News', 'http://cricfree.sx/update/news.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('Sky Sports F1', 'http://cricfree.sx/update/skysf1.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_mx_sports.png'))
        self.chanlist.append(cat_('BT Sport 1', 'http://cricfree.sx/update/bt1.php', 'http://www.lyngsat-logo.com/logo/tv/bb/bt_sport_1.png'))
        self.chanlist.append(cat_('BT Sport 2', 'http://cricfree.sx/update/bt2.php', 'http://www.lyngsat-logo.com/logo/tv/bb/bt_sport_2.png'))
        self.chanlist.append(cat_('BT Sport ESPN', 'http://cricfree.sx/update/espn.php', 'http://www.lyngsat-logo.com/logo/tv/bb/bt_sport_uk_espn.png'))
        self.chanlist.append(cat_('BT Sport Europe', 'http://cricfree.sx/update/bteu.php', 'http://www.lyngsat-logo.com/logo/tv/bb/bt_sport_europe_uk.png'))
        self.chanlist.append(cat_('Eurosport', 'http://cricfree.sx/update/euro.php', 'http://www.lyngsat-logo.com/logo/tv/bb/british_eurosport.png'))
        self.chanlist.append(cat_('Eurosport 2', 'http://cricfree.sx/update/euro2.php', 'http://www.lyngsat-logo.com/logo/tv/bb/british_eurosport_2.png'))
        self.chanlist.append(cat_('Sky Calcio', 'http://cricfree.sx/update/skycalcio.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_it_calcio.png'))
        self.chanlist.append(cat_('Sky Sports 1 IT', 'http://cricfree.sx/update/sky1ita.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_it_sport1.png'))
        self.chanlist.append(cat_('Sky Sports 2 IT', 'http://cricfree.sx/update/sky2ita.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_it_sport2.png'))
        self.chanlist.append(cat_('Sky Sports 3 IT', 'http://cricfree.sx/update/sky3ita.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sky_it_sport3.png'))
        self.chanlist.append(cat_('SportsNet World', 'http://cricfree.sx/update/setcafl.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sportsnet_world.png'))
        self.chanlist.append(cat_('SportsNet One', 'http://cricfree.sx/update/snone.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sportsnet_one.png'))
        self.chanlist.append(cat_('SportsNet Ontario', 'http://cricfree.sx/update/snontario.php', 'http://www.lyngsat-logo.com/logo/tv/ss/sportsnet_ontario.png'))
        self.chanlist.append(cat_('ESPN USA', 'http://cricfree.sx/update/espnusa.php', 'http://www.lyngsat-logo.com/logo/tv/ee/espn_caribbean.png'))
        self.chanlist.append(cat_('ESPN 2', 'http://cricfree.sx/update/espn2.php', 'http://www.lyngsat-logo.com/logo/tv/ee/espn_2.png'))
        self.chanlist.append(cat_('Ten Sports', 'http://cricfree.sx/update/tensports.php', 'nix'))
        self.chanlist.append(cat_('FOX 1 HD', 'http://cricfree.sx/update/fox1.php', 'http://www.lyngsat-logo.com/logo/tv/ff/fox_sports_global_hd.png'))
        self.chanlist.append(cat_('FOX 2 HD', 'http://cricfree.sx/update/fox2.php', 'http://www.lyngsat-logo.com/logo/tv/ff/fox_sports_2_lam.png'))
        self.chanlist.append(cat_('TSN', 'http://cricfree.sx/update/tsn1.php', 'nix'))
        self.chanlist.append(cat_('MLB HD', 'http://cricfree.sx/update/mlb.php', 'nix'))
        self.chanlist.append(cat_('NBA TV HD', 'http://cricfree.sx/update/nba.php', 'nix'))
        self.chanlist.append(cat_('Golf Channel', 'http://cricfree.sx/update/golf.php', 'nix'))
        self.chanlist.append(cat_('AT THE RACES', 'http://cricfree.sx/update/atraces.php', 'nix'))
        self.chanlist.append(cat_('RACING UK', 'http://cricfree.sx/update/ukrace.php', 'nix'))
        self.chanlist.append(cat_('BOX NATION', 'http://cricfree.sx/update/boxnation.php', 'nix'))
        self.chanlist.append(cat_('STAR SPORTS', 'http://cricfree.sx/update/starsports.php', 'nix'))
        self.chanlist.append(cat_('PTV Sports', 'http://cricfree.sx/update/ptvsports.php', 'nix'))
        self.chanlist.append(cat_('Premier Sports', 'http://cricfree.sx/update/premiersports.php', 'nix'))
        self.chanlist.append(cat_('MU TV', 'http://cricfree.sx/update/mutv.php', 'nix'))
        self.chanlist.append(cat_('Chelsea TV', 'http://cricfree.sx/update/chelsea.php', 'nix'))
        self.chanlist.append(cat_('Motors TV UK', 'http://cricfree.sx/update/motors.php', 'nix'))
        self.chanlist.append(cat_('LFCTV HD', 'http://cricfree.sx/update/tensports.php', 'nix'))
        self.chanlist.append(cat_('BBC', 'http://cricfree.sx/update/tensports.php', 'nix'))
        self.chanlist.append(cat_('Willow HD', 'http://cricfree.sx/update/tensports.php', 'nix'))
        self['menulist'].l.setList(self.chanlist)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster_teledunet()

    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
            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/')
            req.add_header('Host', 'cricfree.sx')
            page = urllib2.urlopen(req)
            response = page.read()
            cookie = page.info()['Set-Cookie']
            print response#<script type='text/javascript'>id='sky1scs'; width='620'; height='490';</script><script type='text/javascript' src='http://soccerschedule.online/livegamecr.js'></script>
			#                                    <script type='text/javascript'>id='bt1dd'; width='620'; height='490';</script><script type='text/javascript' src='http://theactionlive.com/livegamecr.js'></script>
            page_param = re.findall("<script type='text/javascript'>id='(.*?)'; width=.*?; height=.*?;</script><script type='text/javascript' src='http://soccerschedule.online/", response)
            if page_param:
                print page_param
                try:
                    url = 'http://soccerschedule.online/reprocric.php?id=' + page_param[0] + '&width=620&height=490&stretching=uniform'
                    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', 'soccerschedule.online')
                    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('Cookie', cookie)
                    req.add_header('Referer', 'http://cricfree.sx/update/skys1.php')
                    response = urllib2.urlopen(req)
                    buf = StringIO(response.read())
                    f = gzip.GzipFile(fileobj=buf)
                    data = f.read()
                    print data
                    id = re.findall("<script type='text/javascript'>id='(.*?)';", data)
                    print id
                    if id:#
                        url1 = 'http://playstream.club/hicric.php?id=' + id[0] + '&p=0&c=0&stretching=uniform'
                        req = urllib2.Request(url1)
                        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', 'playstream.club')
                        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('Cookie', cookie)
                        req.add_header('Referer', url)
                        try:
                            response = urllib2.urlopen(req)
                            buf = StringIO(response.read())
                            f = gzip.GzipFile(fileobj=buf)
                            data = f.read()
                            print data
                            streamer = re.findall('source: "(.*?)"', data)
                            print streamer
                            if streamer:
                                final_url = 'http://127.0.0.1:88/hls://'+streamer[0]
                                self.play_that_shit(final_url)
                            else:
                                file = re.findall('file:"(.*?)"', data)
                                if file:
                                    print file
                                    self.play_that_shit(file[0])
                        except:
                            print 'socceronline - page changed again'
                except:
                    pass

            else:
                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)
                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)
                    if file:
                        re_dir_url = file[0].split('/')
                        print re_dir_url
                        securetoken = re.findall('securetoken: "(.*?)"', response)
                        swf = 'http://www.yocast.tv/myplayer/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'>fid='crictens'; v_width=620; v_height=490;</script><script type='text/javascript' src='http://www.yotv.co/player.js'></script>
                    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://www.yotv.co/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', 'yotv.co')
                        req.add_header('Referer', 'http://cricfree.sx/update/atraces.php')
                        try:
                            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)
                        except:
                            print 'shit - yotv'

    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'
        file_name = 'cricfree.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_perm)


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