# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/arabic_streams.py
from imports import *
from Tools.Directories import fileExists, pathExists
from jsunpacker import *
from arabic_channels import *
if fileExists('/usr/lib/enigma2/python/Plugins/Extensions/JobManager/plugin.pyo'):
    from Plugins.Extensions.JobManager.plugin import *
    JobManagerInstalled = True
else:
    JobManagerInstalled = False
UserAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'

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


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

    def about(self):
        self.session.open(AboutScreen)

    def jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]
            self.get_play_link(self.filmname, link)

    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_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'Al Cinema'
        self.load_data_channels()

    def load_data_channels(self):
        self.letter_list = []
        for each in arabic_channels:
            playpath, url = each
            self.letter_list.append(show_(playpath, url, None))

        self.letter_list.sort()
        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

    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
            if selectedName == 'KassPlusHD':
                url = 'http://shoof.alkass.net/shoof/live/live_3.php'
                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('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
                req.add_header('Host', 'shoof.alkass.net')
                req.add_header('Cookie', ' _alid_=E2nyaua/pTvlOmp2LkoREA==;')
                req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
                req.add_header('Connection', 'keep-alive')
                req.add_header('Referer', 'http://shoof.alkass.net/shoof/live/live_1.php')
                page = urllib2.urlopen(req)
                r = page.read()
                java = re.findall('(eval.*?)\n</script>', r)
                unpacked = self.unpackByString(java[0])
                link = re.findall('escape\\("(.*?)"', unpacked)
                self.play_that_shit(link[0])
            elif selectedName == 'KassHD':
                url = 'http://shoof.alkass.net/shoof/live/live_2.php'
                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('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
                req.add_header('Host', 'shoof.alkass.net')
                req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
                req.add_header('Connection', 'keep-alive')
                req.add_header('Cookie', ' _alid_=E2nyaua/pTvlOmp2LkoREA==;')
                req.add_header('Referer', 'http://shoof.alkass.net/shoof/live/live_1.php')
                page = urllib2.urlopen(req)
                r = page.read()
                java = re.findall('(eval.*?)\n</script>', r)
                unpacked = self.unpackByString(java[0])
                link = re.findall('escape\\("(.*?)"', unpacked)
                self.play_that_shit(link[0])
            elif selectedName == 'Kass SD':
                url = 'http://shoof.alkass.net/shoof/live/live_1.php'
                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('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
                req.add_header('Host', 'shoof.alkass.net')
                req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
                req.add_header('Connection', 'keep-alive')
                req.add_header('Referer', 'http://shoof.alkass.net/shoof/live/live_1.php')
                page = urllib2.urlopen(req)
                r = page.read()
                java = re.findall('(eval.*?)\n</script>', r)
                unpacked = self.unpackByString(java[0])
                link = re.findall('escape\\("(.*?)"', unpacked)
                self.play_that_shit(link[0])
            else:
                uri = selectedEntry
                self.play_that_shit(uri)

    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 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 exit(self):
        self.close()

    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 '[arabicstreams] 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 main(session, **kwargs):
    session.open(arabicstreams)


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