# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/filmpalast.py
from imports import *
from about import *
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):
    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, pagenr):
    res = [(letter, link, pagenr)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class filmpalast(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,
         'green': self.search,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Search')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('Filmpalast')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.video_list = []
        self.info = ''
        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://filmpalast.to/search/genre/Abenteuer', 'Abenteuer', '16'),
         ('http://filmpalast.to/search/genre/Action', 'Action', '35'),
         ('http://filmpalast.to/search/genre/Animation', 'Animation', '7'),
         ('http://filmpalast.to/search/genre/Biographie', 'Biographie', '4'),
         ('http://filmpalast.to/search/genre/Dokumentation', 'Dokumentation', '2'),
         ('http://filmpalast.to/search/genre/Drama', 'Drama', '49'),
         ('http://filmpalast.to/search/genre/Familie', 'Familie', '8'),
         ('http://filmpalast.to/search/genre/Fantasy', 'Fantasy', '10'),
         ('http://filmpalast.to/search/genre/Geschichte', 'Geschichte', '1'),
         ('http://filmpalast.to/search/genre/Horror', 'Horror', '29'),
         ('http://filmpalast.to/search/genre/Kom\xc3\xb6die', 'Kom\xc3\xb6die', '20'),
         ('http://filmpalast.to/search/genre/Krieg', 'Krieg', '5'),
         ('http://filmpalast.to/search/genre/Krimi', 'Krimi', '7'),
         ('http://filmpalast.to/search/genre/Musik', 'Musik', '4'),
         ('http://filmpalast.to/search/genre/Mystery', 'Mystery', '8'),
         ('http://filmpalast.to/search/genre/Romantik', 'Romantik', '2'),
         ('http://filmpalast.to/search/genre/Sci-Fi', 'Sci-Fi', '17'),
         ('http://filmpalast.to/search/genre/Sport', 'Sport', '2'),
         ('http://filmpalast.to/search/genre/Thriller', 'Thriller', '40'),
         ('http://filmpalast.to/search/genre/Western', 'Western', '3'),
         ('http://filmpalast.to/search/genre/Zeichentrick', 'Zeichentrick', '1')]
        for url, title, pagenr in self.cat_list:
            self.cat.append(cat_(title, url, pagenr))

        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):
        print data
        self.video_list = []
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        self.info = 'videos'
        last_page = re.findall('>(.*?)</a> <span style="border:0; background', data)
        print last_page
        max_nr = int(self['menulist'].l.getCurrentSelection()[0][2]) + 1
        i = 1
        url = str(selectedEntry)
        for i in range(1, max_nr):
            url = url + '/' + str(i) + '/'
            print url
            getPage(url, timeout=8, method='GET', cookies=cj, 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_videos1)
            i += 1
            url = str(selectedEntry)

    def get_videos1(self, data):
        print data
        videos = re.findall('<a href="(.*?)" title="(.*?)"> <img src="(.*?)" class="cover-opacity" alt=".*?"/></a>', data)
        print videos
        if videos:
            for url, title, img in videos:
                img = 'http://filmpalast.to' + img
                if 'Streams' not in title:
                    self.video_list.append(show_(title, url, img))

            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)

    def get_link(self, data):
        self.info = 'link'
        self.link_list = []
        i = 1
        block = re.findall('<p class="hostName">Streamcloud.eu</p></li>(.*?)</li>', data, re.DOTALL)
        link = re.findall('<a class="button rb iconPlay stream-src" data-id="(.*?)" data-stamp="(.*?)".*?</i> (Play.*?)</a>', block[0], re.DOTALL)
        for id, stamp, play in link:
            url = 'https://filmpalast.to/stream/' + id + '/1'
            title = 'Streamcloud.eu ' + play.replace('<small>', '').replace('</small>', '')
            self.link_list.append(cat_(title, url, None))

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

    def get_hls(self, data):
        real_url = re.findall('url":"(.*?)"', data)
        if real_url:
            real_url = real_url[0].replace('\\', '')
            print real_url
            if 'streamcloud' in real_url:
                getPage(real_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.resolve_streamcloud)
            elif 'wholecloud' in real_url:
                getPage(real_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',
                 'Host': 'www.wholecloud.net'}).addCallback(self.resolve_movshare)
            elif 'nowvideo' in real_url:
                getPage(real_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.resolve_movshare)

    def resolve_streamcloud(self, data):
        id = re.findall('<input type="hidden" name="id".*?value="(.*?)">', data)
        fname = re.findall('<input type="hidden" name="fname".*?alue="(.*?)">', data)
        hash = re.findall('<input type="hidden" name="hash" value="(.*?)">', data)
        if id and fname and hash:
            url = 'https://streamcloud.eu/%s' % id[0]
            post_data = urllib.urlencode({'op': 'download2',
             'usr_login': '',
             'id': id[0],
             'fname': fname[0],
             'referer': '',
             'hash': hash[0],
             'imhuman': 'Weiter+zum+Video'})
            getPage(url, method='POST', postdata=post_data, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_hls1)

    def resolve_movshare(self, data):
        print data
        for frm in re.findall('<form[^>]*method="POST"[^>]*>(.*?)</form>', data, re.S | re.I):
            info = {}
            for i in re.finditer('<input[^>]*name="([^"]*)"[^>]*value="([^"]*)"', frm):
                info[i.group(1)] = i.group(2)

        print info
        p = urllib.urlencode(info)
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print p
        print url
        getPage(url, method='POST', postdata=p, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_wholecloud)

    def get_wholecloud(self, data):
        print data
        domain = re.findall('flashvars.domain="(.*?)"', data)
        file = re.findall('flashvars.file="(.*?)"', data)
        filekey = re.findall('flashvars.filekey="(.*?)"', data)
        if domain and file and filekey:
            url = '%s/api/player.api.php?file=%s&key=%s' % (domain[0], file[0], filekey[0])
            getPage(url, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_hls1)

    def get_hls1(self, data):
        print data
        file = re.findall('file: "(.+?)",', data)
        print file
        if file:
            self.play_vid(file[0])
        else:
            file = re.findall('url=(.*?)&title=', 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.open(MoviePlayer, sref)

    def search(self):
        self.index = 'search'
        self.session.openWithCallback(self.search_filmpalast, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_filmpalast(self, searchstring = None):
        self.index = 'search'
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'https://filmpalast.to/search/title/' + searchstring_fin
            p = urllib.urlencode({'headerSearchText': searchstring_fin,
             't1': 'tags'})
            getPage(url, timeout=8, method='POST', postdata=p, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.info = 'videos'
        print data
        self.search_list = []
        videos = re.findall('<a href="(.*?)" title="(.*?)"> <img src="(.*?)" class="cover-opacity" alt=".*?"/></a>', data)
        print videos
        if videos:
            for url, title, img in videos:
                img = 'https://filmpalast.to' + img
                if 'Streams' not in title:
                    self.search_list.append(show_(title, url, img))

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

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'cat':
            url = str(selectedEntry)
            print url
            getPage(url, timeout=8, method='GET', cookies=cj, 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',
             'Referer': 'http://flash-moviez.ucoz.org/publ/alle_moviez/action/3'}).addCallback(self.get_videos)
        elif self.info == 'videos':
            url = str(selectedEntry)
            print url
            getPage(url, timeout=8, method='GET', cookies=cj, 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 == 'link':
            url = str(selectedEntry)
            print url
            id = re.findall('/stream/(.*?)/', url)[0]
            print id
            p = urllib.urlencode({'streamID': id})
            print p
            getPage(url, timeout=8, method='POST', postdata=p, cookies=cj, headers={'Content-Type': 'application/x-www-form-urlencoded',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
             'Host': 'filmpalast.to',
             'Origin': 'https://filmpalast.to',
             'X-Requested-With': 'XMLHttpRequest',
             'Referer': 'https://www.filmpalast.to'}).addCallback(self.get_hls)

    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 == 'link':
            self.info = 'videos'
            self['menulist'].l.setList(self.video_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'player':
            self.session.close(MoviePlayer)
            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'