# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/hdtvizle.py
from imports import *
from about import *
from StringIO import StringIO
import gzip
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
cj = {}

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, index):
    res = [(name,
      link,
      image,
      index)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, 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 hdtvler(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,
         'blue': self.dnitnow}, -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('hdtvler.net')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.list_cat)

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

    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]

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

        elif self.info == 'list_channels':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

        elif self.info == 'list_channels':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

        elif self.info == 'list_channels':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

        elif self.info == 'list_episodes':
            try:
                self.load_poster()
            except:
                print 'error loading poster'

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('HD', 'http://www.hdtvler.net/category/vlc-player-hd-tv-izle/'),
         ('Sinema', 'http://www.hdtvler.net/category/sinema-kanallari/'),
         ('Haber', 'http://www.hdtvler.net/category/haber-kanallari/'),
         ('Spor', 'http://www.hdtvler.net/category/spor-kanallari/'),
         ('Cocuk', 'http://www.hdtvler.net/category/cocuk-tv-kanallari/'),
         ('Muzik', 'http://www.hdtvler.net/category/muzik-kanallari/'),
         ('Dini', 'http://www.hdtvler.net/category/dini-tv-kanallari/'),
         ('Belgesel', 'http://www.hdtvler.net/category/belgesel-kanallari/'),
         ('YerelTv', 'http://www.hdtvler.net/category/yerel-tv/')]
        for each in cat:
            title, url = each
            self.cat_list.append(cat_(title, url))

        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def list_channels(self, data):
        self.info = 'list_channels'
        self.show_list = []
        channels = re.findall('<img class="postimg" src="(.*?)" alt=""/></a>.*?<h2><a href="(.*?)" rel="bookmark" title=".*?">(.*?)</a>', data, re.DOTALL)
        print channels
        for each in channels:
            img, url, title = each
            self.show_list.append(show_(title, url, img, None))

        self['menulist'].l.setList(self.show_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def get_link(self, data):
        link = re.findall('<iframe src="(.*?)" width=".*?" height=".*?".*?allowfullscreen></iframe>', data)
        print link
        if link:
            link = 'http://www.hdtvler1.net' + link[0]
#Host:www.hdtvler1.net
#Referer:http://www.hdtvler1.net/tv-8/
            getPage(link, timeout=8, method='GET', headers={'Host': 'www.hdtvler1.net',
             'Referer': 'http://www.hdtvler1.net/',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36','Cookie':'_gat=1; PHPSESSID=6e8629ae255d3e52e93f145506ac4775; __atuvc=2%7C40; __atuvs=57f8e33c6c79cb30001; _ga=GA1.2.1181431382.1475928550; GED_PLAYLIST_ACTIVITY=W3sidSI6Iit1MmoiLCJ0c2wiOjE0NzU5MjkwMjAsIm52IjowLCJ1cHQiOjE0NzU5Mjg4OTIsImx0IjoxNDc1OTI4OTU4fSx7InUiOiJrdm8yIiwidHNsIjoxNDc1OTI5MDIwLCJudiI6MCwidXB0IjoxNDc1OTI4ODkyLCJsdCI6MTQ3NTkyODkwNH0seyJ1IjoidHJmeCIsInRzbCI6MTQ3NTkyODk2OSwibnYiOjEsInVwdCI6MTQ3NTkyODk1MSwibHQiOjE0NzU5Mjg5Njl9XQ..'}).addCallback(self.get_ultracast_link)
        else:
            file = re.findall("file: '(.*?)',", data)
            print file
            if file:
                self.play_movie(file[0])
            else:
                src = re.findall('<video id="aPlayer" src="(.*?)"', data)
                if src:
                    self.play_movie(src[0])
					
					


    def get_ultracast_link(self, data):
        print data
        link = re.findall("file: '(.*?)',", data)
        print link
        if link:
            self.play_movie(link[0])
        else:
            link = re.findall('file:"(.*?)"\\}', data)
            print link
            if link:
                self.play_movie(link[0])
            else:
                link = re.findall('fil.*?: "(.*?)"', data)
                print link
                if link:
                    self.play_movie(link[0])

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

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'list_cat':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={
             'Referer': 'http://bratu-marian.ro/channel-1/',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}).addCallback(self.list_channels)
        elif self.info == 'list_channels':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={
             'Referer': 'http://bratu-marian.ro/channel-1/',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}).addCallback(self.get_link)
        elif self.info == 'list_live':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={
             'Referer': 'http://bratu-marian.ro/channel-1/',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}).addCallback(self.get_link)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/hayyes_poster.jpg'):
                os.system('rm -r /tmp/hayyes_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_channels':
            self.close()
        elif self.info == 'list_episodes':
            self.info = 'list_shows'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_streams':
            self.info = 'list_episodes'
            self['blue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info = 'list_channels'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.info == 'list_live':
            self.info = 'list_cat'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/hayyes_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/hayyes/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 '[hayyes] 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 '[hayyes] no cover.. error'
        return

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


class unwise():

    def worker(self, str_eval):
        page_value = ''
        try:
            ss = 'w,i,s,e=(' + str_eval + ')'
            exec ss
            page_value = self.__unwise(w, i, s, e)
        except:
            return

        return page_value

    def __unwise(self, w, i, s, e):
        lIll = 0
        ll1I = 0
        Il1l = 0
        ll1l = []
        l1lI = []
        while True:
            if lIll < 5:
                l1lI.append(w[lIll])
            elif lIll < len(w):
                ll1l.append(w[lIll])
            lIll += 1
            if ll1I < 5:
                l1lI.append(i[ll1I])
            elif ll1I < len(i):
                ll1l.append(i[ll1I])
            ll1I += 1
            if Il1l < 5:
                l1lI.append(s[Il1l])
            elif Il1l < len(s):
                ll1l.append(s[Il1l])
            Il1l += 1
            if len(w) + len(i) + len(s) + len(e) == len(ll1l) + len(l1lI) + len(e):
                break

        lI1l = ''.join(ll1l)
        I1lI = ''.join(l1lI)
        ll1I = 0
        l1ll = []
        for lIll in range(0, len(ll1l), 2):
            ll11 = -1
            if ord(I1lI[ll1I]) % 2:
                ll11 = 1
            l1ll.append(chr(int(lI1l[lIll:lIll + 2], 36) - ll11))
            ll1I += 1
            if ll1I >= len(l1lI):
                ll1I = 0

        ret = ''.join(l1ll)
        if 'eval(function(w,i,s,e)' in ret:
            ret = re.compile('eval\\(function\\(w,i,s,e\\).*}\\((.*?)\\)').findall(ret)[0]
            return self.worker(ret)
        else:
            return ret