# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/glarab.py
from setup import *
from imports import *
import string
from glarab_med_list import *
from glarab_list import *
import json, base64
import urllib, urllib2
import random
import time
useHigh = 'yes'
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


def episodes_(name, link, image, info):
    res = [(name,
      link,
      image,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def cat_(letter, link):
    res = [(letter, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class glarab(Screen):

    def __init__(self, session):
        self.session = 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()
        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('Glarab')
        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 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 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 = []
        if useHigh == 'yes':
            for each in glarab_list:
                playpath, url = each
                self.letter_list.append(cat_(playpath, url))

        else:
            for each in glarab_med_list:
                playpath, url = each
                self.letter_list.append(cat_(playpath, url))

        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)

    def ok(self):
        if self.check == 'abc':
            link = self.play_that_shit()
            self.play_it(link)

    def getUrl(self, url, cookieJar = None, post = None, timeout = 20, headers = None, returnResponse = False, noredirect = False, jsonpost = False):
        cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
        opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
        if jsonpost:
            req.add_header('Content-Type', 'application/json')
        if headers:
            for h, hv in headers:
                req.add_header(h, hv)

        response = opener.open(req, post, timeout=timeout)
        if returnResponse:
            return response
        link = response.read()
        response.close()
        return link

    def play_it(self, link):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, str(link))
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def play_that_shit(self):
        proxy = config.Albatros.glarab_proxy.value
        if config.Albatros.glarab_proxy.value == '0' and useHigh == 'yes':
            videoPath = self['menulist'].l.getCurrentSelection()[0][1]
            apikey = base64.b64decode('OGRhZmFjMzY5Y2I0NDVmYjg5Mzk1NDI4ZTY0YWQ1NmU=')
            apipwd = base64.b64decode('OTBjODgzYjFjNDdhNGI5OWFhNWE4MmU2YjMyOTUxYTU=')
            data = {'f': 'maincheck',
             'action': 'maincheck'}
            header = [('User-Agent', '')]
            sessionpage = self.getUrl('https://api.gliptv.com/auth.aspx', post=json.dumps(data), headers=header, jsonpost=True)
            sessionpage = json.loads(sessionpage)['resp']
            apipwd = sessionpage[0]['APIPassword']
            apikey = sessionpage[0]['APIKey']
            print 'got keys'
            gldatafull = self.getUrl(base64.b64decode('aHR0cDovL3Bhc3RlYmluLmNvbS9yYXcvcHFUZTB1eFI='))
            gldatafull = gldatafull.splitlines()
            print gldatafull
            valdic = []
            currenttime = int(time.time())
            for ln in gldatafull:
                if not ln.startswith('##') and len(ln) > 0:
                    serial, mac, storetime = ln.split(':')
                    storetime = int(storetime.split('#')[0])
                    if storetime > currenttime:
                        valdic += [(serial, mac)]
                        glserialno, glmacAddress = random.choice(valdic)
                        data = {'gmt': '0',
                         'APIPassword': apipwd,
                         'APIKey': apikey,
                         'appVersion': '4.5',
                         'deviceType': '7',
                         'deviceFirmware': '4.4.4',
                         'deviceModel': 'GT-I9300',
                         'action': 'checkNewDevice',
                         'serialNumber': glserialno,
                         'macAddress': glmacAddress,
                         'deviceInfo': 'samsung-m0-amlogic-19',
                         'applicationType': '5'}
                        header = [('User-Agent', '')]
                        sessionpage = self.getUrl(base64.b64decode('aHR0cHM6Ly9hcGkuZ2xpcHR2LmNvbS9hdXRoLmFzcHg='), post=json.dumps(data), headers=header, jsonpost=True)
                        sessionpage = json.loads(sessionpage)
                        glpw = sessionpage['keys']['pw']
                        gltoken = sessionpage['keys']['token']
                        gldeviceid = str(sessionpage['devicebox']['deviceID'])
                        glboxid = str(sessionpage['devicebox']['BoxID'])
                        try:
                            data = {'ContentType_ID': '4',
                             'f': 'getStreamURL',
                             'itemName': videoPath,
                             'APIPassword': apipwd,
                             'APIKey': apikey,
                             'DeviceID': gldeviceid,
                             'DeviceType': '7',
                             'streamProtocal': 'hls',
                             'BoxID': glboxid,
                             'User_Country': '',
                             'appVersion': '4.5',
                             'ClusterName': 'zixi',
                             'token': gltoken,
                             'action': 'getStreamURL',
                             'streamType': 'live',
                             'content_ID': '301493',
                             'pw': glpw,
                             'DUID': '',
                             'User_Province': '',
                             'PackageID': '1'}
                            header = [('User-Agent', '')]
                            sessionpage = self.getUrl('https://api.gliptv.com/auth.aspx', post=json.dumps(data), headers=header, jsonpost=True)
                            print sessionpage
                            link = json.loads(sessionpage)['resp']
                            print link
                            return link
                        except:
                            self.stream_not_found()

    def exit(self):
        self.close()

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Channel not available, try again later on'), MessageBox.TYPE_INFO, timeout=3)