# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/beinsports24.py
from imports import *
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):
    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 bein24(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['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['title'] = Label('Beinsports24.com')
        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()
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')

    def down(self):
        self[self.currentList].down()
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')

    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_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'sports'
        url = 'http://beinsports24.com/'
        print url
        getPage(url, method='GET', headers={'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 'got data - now processing live_list'
        self.letter_list = []
        matches = re.findall('(\\d{2}[:]\\d{2}.*?)\n', data)
        for each in matches:
            match = each
            print match
            if 'channel 1<br>' in match:
                url = 'http://beinsports24.com/ch1.html'
            elif 'channel 2<br>' in match:
                url = 'http://beinsports24.com/ch2.html'
            elif 'channel 3<br>' in match:
                url = 'http://beinsports24.com/ch3.html'
            elif 'channel 4<br>' in match:
                url = 'http://beinsports24.com/ch4.html'
            elif 'channel 5<br>' in match:
                url = 'http://beinsports24.com/ch5.html'
            elif 'channel 6<br>' in match:
                url = 'http://beinsports24.com/ch6.html'
            elif 'channel 7<br>' in match:
                url = 'http://beinsports24.com/ch7.html'
            elif 'channel 8<br>' in match:
                url = 'http://beinsports24.com/ch8.html'
            elif 'channel 9<br>' in match:
                url = 'http://beinsports24.com/ch9.html'
            elif 'channel 10<br>' in match:
                url = 'http://beinsports24.com/ch10.html'
            elif 'channel 11<br>' in match:
                url = 'http://beinsports24.com/ch11.html'
            elif 'channel 12<br>' in match:
                url = 'http://beinsports24.com/ch12.html'
            elif 'channel 13<br>' in match:
                url = 'http://beinsports24.com/ch13.html'
            elif 'channel 14<br>' in match:
                url = 'http://beinsports24.com/ch14.html'
            elif 'channel 15<br>' in match:
                url = 'http://beinsports24.com/ch15.html'
            elif 'channel 16<br>' in match:
                url = 'http://beinsports24.com/ch16.html'
            elif 'channel 17<br>' in match:
                url = 'http://beinsports24.com/ch17.html'
            elif 'channel 18<br>' in match:
                url = 'http://beinsports24.com/ch18.html'
            elif 'channel 19<br>' in match:
                url = 'http://beinsports24.com/ch19.html'
            elif 'channel 20<br>' in match:
                url = 'http://beinsports24.com/ch20.html'
            elif 'channel 21<br>' in match:
                url = 'http://beinsports24.com/ch21.html'
            elif 'channel 22<br>' in match:
                url = 'http://beinsports24.com/ch22.html'
            elif 'channel 23<br>' in matches:
                url = 'http://beinsports24.com/ch23.html'
            elif 'channel 24<br>' in matches:
                url = 'http://beinsports24.com/ch24.html'
            elif 'channel 25<br>' in match:
                url = 'http://beinsports24.com/ch25.html'
            else:
                url = 'http://beinsports24.com/ch1.html'
            match = match.replace('<br>', '')
            self.letter_list.append(cat_(str(match), url))

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

    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('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('Cache-Control', 'max-age=0')
            req.add_header('Connection', 'keep-alive')
            req.add_header('Cookie', '__cfduid=d8b81031c5616f058b3f6f77ea3e291681444446189; noadvtday=0')
            req.add_header('Host', 'beinsports24.com')
            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"> fid="(.*?)"; v_width=640; v_height=460;</script><script type="text/javascript" src="http://hdcast.org/firstrow.js"></script>', data)
            if id:
                final_path = 'rtmpe://134.19.185.221:1935/hfufdxdhr/ playpath=' + id[0] + ' swfUrl=http://player.hdcast.org/jws/jwplayer.flash.swf/[[DYNAMIC]]/2/[[DYNAMIC]]/3 pageUrl=http://www.hdcast.org/ token=SECURET0KEN#yw%.?()@W!'
                print final_path
                self.play_that_shit(final_path)

    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):
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')
        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 '[bkssport_live] 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 '[bkssport_live] 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 '[bkssport_live] /tmp/highlive/ allready present'


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


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