# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/kuretv.py
from imports import *
import os
from StringIO import StringIO
import gzip
from Tools.Directories import fileExists, pathExists
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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, cookie):
    res = [(name,
      link,
      image,
      cookie)]
    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 kuretv(Screen):

    def __init__(self, session):
        global old_ref
        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(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('kure.tv')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.get_channels)

    def about(self):
        self.close()

    def up(self):
        self[self.currentList].up()
        self.load_poster_()

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

    def left(self):
        self[self.currentList].pageUp()

    def right(self):
        self[self.currentList].pageDown()

    def get_channels(self):
        self.index = 'get_channels'
        self.channel_list = []
        url = 'http://www.kure.tv/canli-yayin'
        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')
        try:
            page = urllib2.urlopen(req)
            r = page.read()
            cookie = page.info()['Set-Cookie']
        except:
            r='Sorry - page down'
        channels = re.findall('<a href="(.*?)" target= "_blank" title="(.*?)">.*?<div class="live-thumb">.*?<img src="(.*?)"  alt="', r, re.DOTALL)
        for url, title, img in channels:
            url = 'http://www.kure.tv' + url
            print url
            if 'http://www.kure.tv/uye/uyelik/kayit' not in url:
                self.channel_list.append(show_(title, url, img, cookie))

        self.channel_list.append(show_('Samanyolu TV', 'http://www.kure.tv/samanyolutv', 'http://images1.kure.tv/channel_images/logo/1/medium/samanyolutv.png?1398519461', cookie))
        self['menulist'].l.setList(self.channel_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        self.load_poster_()

    def ok(self):
        if self.index == 'get_cat':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'Cookie': '__cfduid=d6183dd67423da779cd5a9cba7d67f1751432398047; _pk_id.1.9699=846a85249eb7d311.1432398051.32.1440096432.1440096315.; has_js=1',
             'Host': 'www.wagasworld.com',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_channels)
        elif self.index == 'get_channels':
            selectedEntry = self['menulist'].getCurrent()[0][1]
            selectedName = self['menulist'].getCurrent()[0][0]
            cookie = self['menulist'].getCurrent()[0][3]
            url = selectedEntry
            self.filmname = str(selectedName)
            self.get_link(cookie)

    def get_link(self, cookie):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        print selectedEntry
        req = urllib2.Request(selectedEntry)
        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', 'www.kure.tv')
        req.add_header('Cookie', cookie)
        page = urllib2.urlopen(req)
        cookie = page.info()['Set-Cookie']
        r = page.read()
        link = re.findall("file: '(.*?)'", r)
        print link
        print cookie
        if link:
            link = link[0]
            ln = 'http://127.0.0.1:88/hlsvariant://' + link
            self.play_that_shit(ln)

    def parse_dict_cookies(self, value):
        result = {}
        for item in value.split(';'):
            item = item.strip()
            if not item:
                continue
            if '=' not in item:
                result[item] = None
                continue
            name, value = item.split('=', 1)
            result[name] = value

        return result

    def play_that_shit(self, data):
        self.index = 'player'
        if data:
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, data)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()

    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):
        if self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'get_channels'
            self['menulist'].l.setList(self.channel_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        else:
            self.close()

    def load_poster_(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/wagasworld_poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            print "Error: can't find file or read data"

    def downloadPic(self, data, jpg_store):
        if fileExists(jpg_store):
            self.poster_resize(jpg_store)
        else:
            print '[wagasworld] 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 '[wagasworld] no cover.. error'
        return

    def dir(self):
        if not pathExists('/tmp/wagasworld/'):
            os.system('mkdir /tmp/wagasworld/')
        else:
            print '[wagasworld] /tmp/wagasworld/ allready present'