# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/kinoger.py
from imports import *
from about import *
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, 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 show3_(name, link, image):
    res = [(name, link, image)]
    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 kinoger(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,
         'green': self.search,
         '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['green'] = Label(_('Search'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('KinoGer')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.info = ''
        self.index = ''
        self.video_list = []
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.show_cat)

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

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            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 == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            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 == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            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 == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def show_cat(self):
        self.info = 'cat'
        self.cat = []
        self.cat_list = [('http://kinoger.com/stream/anime/', 'Anime'),
         ('http://kinoger.com/stream/action/', 'Action'),
         ('http://kinoger.com/stream/animation/', 'Animation'),
         ('http://kinoger.com/stream/abenteuer/', 'Abenteuer'),
         ('http://kinoger.com/stream/biography/', 'Biography'),
         ('http://kinoger.com/stream/bollywood/', 'Bollywood'),
         ('http://kinoger.com/stream/drama/', 'Drama'),
         ('http://kinoger.com/stream/dokumentation/', 'Dokumentation'),
         ('http://kinoger.com/stream/erwachsene/', 'Erwachsene'),
         ('http://kinoger.com/stream/familie/', 'Familie'),
         ('http://kinoger.com/stream/fantasy/', 'Fantasy'),
         ('http://kinoger.com/stream/geschichte/', 'Geschichte'),
         ('http://kinoger.com/stream/horror/', 'Horror'),
         ('http://kinoger.com/stream/history/', 'History'),
         ('http://kinoger.com/stream/krimi/', 'Krimi'),
         ('http://kinoger.com/stream/krieg/', 'Krieg'),
         ('http://kinoger.com/stream/komdie/', 'Kom\xc3\xb6die'),
         ('http://kinoger.com/stream/kurzfilm/', 'Kurzfilm'),
         ('http://kinoger.com/stream/music/', 'Music'),
         ('http://kinoger.com/stream/mystery/', 'Mystery'),
         ('http://kinoger.com/stream/musical/', 'Musical'),
         ('http://kinoger.com/stream/romance/', 'Romance'),
         ('http://kinoger.com/stream/reality-tv/', 'Reality-TV'),
         ('http://kinoger.com/stream/serie/', 'Serie'),
         ('http://kinoger.com/stream/sport/', 'Sport'),
         ('http://kinoger.com/stream/sci-fi/', 'Sci-Fi'),
         ('http://kinoger.com/stream/thriller/', 'Thriller'),
         ('http://kinoger.com/stream/trickfilm/', 'Trickfilm'),
         ('http://kinoger.com/stream/western/', 'Western'),
         ('http://kinoger.com/stream/zeichentrick/', 'Zeichentrick')]
        for url, title in self.cat_list:
            self.cat.append(cat_(title, url))

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

    def get_videos(self, data):
        self.info = 'videos'
        videos = re.findall('<div class="content_text">.*?<img src="(.*?)" style="float:left;" alt="(.*?)" title=".*?</div> (.*?)<br/>.*?<span class="buttons"><a href="(.*?)"><span><b>Play</b>', data, re.DOTALL)
        if videos:
            for img, title, info, url in videos:
                self.video_list.append(show_(title, url, img, info))

            self['menulist'].l.setList(self.video_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            info = self['menulist'].getCurrent()[0][3]
            self['text'].setText(info)

    def get_link(self, data):
        link = re.findall("thevideos\\.show\\(1,\\[\\['(.*?)'", data)
        print link
#thevideos.show(1,[['bhlvw2ytsucl','v4ict1ws7zfp','bi22w5xacnwa','c4op5v7ubdbh','8pw4d5h51u85','g6h6od5a82h1','z4jfh2duq9o6','yhdezjl1ysym','8tavsx6335bb','1b8solwdmdze','74wc1jcmq7cm','f3i9qcyw08sk','1kkzppf6ohmg','ocyythzpcaxo','i0rv90ca3rjs','ovecp7anjvep','74qp2bot24m5','wl2rdoahj3u1','tig06gfn7m9z','68h8c15rpq0r','z1jvzlqzxaf9','r3taytcdhoel','t39l0b95h14e','bex50gsprnyd','0xr6lb7rxezq','a4bwgcp8zumr','p4j4ajhan8fa','r81y8qh5zerx','h8z3i2niv9a0','iorg6jcwmmxi','nstio2j7iheq','o2al7u9r0xes','g95dx6fc4fag','xv5dn3ymiws6','cbow4jorystd','8q8krg9vxamp','fp0tu2847a2e','7406fpopon92','k93hjonsxuzw','8v4e4agvrbwd','w9o4tkvdit6t','547tmxjk94sn']]);
        if link: #http://thevideos.tv/embed-v4ict1ws7zfp-735x450.html
            url = 'http://thevideos.tv/embed-' + link[0] +  '-735x450.html'
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             #'Host': 'v1.kinoger.pw',
             'Referer': 'http://kinoger.com/main/2562-ted-2-2015.html'}).addCallback(self.get_hls)

    def get_hls(self, data):
#    sources: [{file:"http://185.123.141.51/kj2vy5qseu6vtaw52aoz4kmcg2da6sy4v6fjnp5rdnxhaeuxf4cfwqvqxxda/v.mp4",label:"240p"},{file:"http://185.123.141.51/kj2vy5qseu6vtaw52aoz4kmcg2da6sy4v6fjnp5rdefxaeuxf4cgxcugfida/v.mp4",label:"360p"},{file:"http://185.123.141.51/kj2vy5qseu6vtaw52aoz4kmcg2da6sy4v6fjnp5rd7axaeuxf4caqg5f3cgq/v.mp4",label:"720p"}],
        file = re.findall('file:"(.*?)",label:"360p"', data)
        if file:
            self.play_vid(file[0])

    def play_vid(self, data):
        self.info = '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 search(self):
        index = '1'
        self.session.openWithCallback(self.search_kinoger, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_kinoger(self, searchstring = None):
        index = '2'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://kinoger.com/?do=search&subaction=search&titleonly=3&story=%s&x=0&y=0&submit=submit' % searchstring_fin
            getPage(url, timeout=8, headers={'Host': 'kinoger.com',
             'Referer': 'http://kinoger.com',
             'Origin': 'http://kinoger.com',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.index = '3'
        search = re.findall('<div class="content_text">.*?<img src="(.*?)" style="float:left;" alt="(.*?)" title=".*?<span class="buttons"><a href="(.*?)"><span><b>Play</b></span>', data, re.DOTALL)
        if search:
            for each in search:
                img, title, url = each
                self.search_list.append(show3_(title, url, img))

            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.index == '3':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'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_link)
        elif self.info == 'cat':
            url = str(selectedEntry)
            i = 1
            for i in range(1, 40):
                url = url + 'page/%s/' % i
                getPage(url, timeout=8, method='GET', headers={'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_videos)
                url = str(selectedEntry)
                i = i + 1

        elif self.info == 'videos':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'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_link)

    def exit(self):
        print self.info
        if self.info == 'cat':
            self.close()
        elif self.info == 'videos':
            self.info = 'cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info = 'videos'
            self['menulist'].l.setList(self.video_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    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'