# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/cinemay.py
from setup import *
from imports import *

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, img, info):
    res = [(name,
      link,
      img,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


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


class cinemay(Screen):

    def __init__(self, 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()
        self.session = session
        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,
         'red': self.exit,
         'green': self.search,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Cinemay.com')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(_('Search'))
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.list_cat)

    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 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.index == '2' or self.index == 'search_data':
            self.load_poster()

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == '2' or self.index == 'search_data':
            self.load_poster()

    def left(self):
        self[self.currentList].pageUp()
        if self.index == '2' or self.index == 'search_data':
            self.load_poster()

    def right(self):
        self[self.currentList].pageDown()
        if self.index == '2' or self.index == 'search_data':
            self.load_poster()

    def switchList(self):
        if self.currentList == 'menulist':
            self['ButtonBlue'].hide()
            self['TextBlue'].hide()
            self['menulist'].selectionEnabled(0)
            self.currentList = 'menulist2'
            self.check = 'abc'
        else:
            self['ButtonBlue'].show()
            self['TextBlue'].show()
            self['menulist'].selectionEnabled(1)
            self.currentList = 'menulist'
            self.check = 'letter_movie'

    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 list_cat(self):
        self.index = '1'
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_movielist = []
        self.catlist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        cat_list = [('Action', 'http://www.cinemay.com/action/page/1/'),
         ('Animation', 'http://www.cinemay.com/animation/page/1/'),
         ('Arts Martiaux', 'http://www.cinemay.com/arts-martiaux/page/1/'),
         ('Aventure', 'http://www.cinemay.com/aventure/page/1/'),
         ('Biopic', 'http://www.cinemay.com/biopic/page/1/'),
         ('Com\xc3\xa9die', 'http://www.cinemay.com/comedie-dramatique/page/1/'),
         ('Com\xc3\xa9die dramatique', 'http://www.cinemay.com/comedie-dramatique/page/1/'),
         ('Disney', 'http://www.cinemay.com/disney/page/1/'),
         ('Documentaire', 'http://www.cinemay.com/documentaire/page/1/'),
         ('Drame', 'http://www.cinemay.com/drame/page/1/'),
         ('Epouvante-horreur', 'http://www.cinemay.com/epouvante-horreur/page/1/'),
         ('Espionnage', 'http://www.cinemay.com/espionnage/page/1/'),
         ('Famille', 'http://www.cinemay.com/famille/page/1/'),
         ('Fantastique', 'http://www.cinemay.com/fantastique/page/1/'),
         ('Guerre', 'http://www.cinemay.com/guerre/page/1/'),
         ('historique', 'http://www.cinemay.com/historique/page/1/'),
         ('Manga', 'http://www.cinemay.com/manga/page/1/'),
         ('Musical', 'http://www.cinemay.com/musical/page/1/'),
         ('Non class\xc3\xa9', 'http://www.cinemay.com/non-classe/page/1/'),
         ('Peplum', 'http://www.cinemay.com/peplum-2/page/1/'),
         ('Policier', 'http://www.cinemay.com/policier/page/1/'),
         ('Romance', 'http://www.cinemay.com/romance/page/1/'),
         ('Science fiction', 'http://www.cinemay.com/science-fiction/page/1/'),
         ('Spectacle', 'http://www.cinemay.com/spectacle/page/1/'),
         ('T\xc3\xa9l\xc3\xa9', 'http://www.cinemay.com/tele/page/1/'),
         ('Thriller', 'http://www.cinemay.com/thriller/page/1/'),
         ('Western', 'http://www.cinemay.com/western/page/1/')]
        for title, url in cat_list:
            self.catlist.append(show_(title, url, None, None))
            self['menulist'].l.setList(self.catlist)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def load_data_channels(self, data, url):
        print 'load_data_channels'
        self.movie_list = []
        print data
        page_max_nr = re.findall("<span class='pages'>(.*?)</span>", data)
        print page_max_nr
        getPage(url, timeout=8, method='GET', headers={'Referer': 'http://www.cinemay.com/voir/56247/',
         'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_movies)

    def list_movies(self, data):
        print 'list_movies'
        self.index = '2'
        self.movie_list = []
        movies = re.findall('<div class="unfilm">.*?<div class="post" id="post-.*?">.*?<a href="(.*?)" rel="bookmark" title=".*?">.*?<div class="imgpic">.*?<img class="imgpic" src="(.*?)" title="(.*?)"', data, re.DOTALL)
        print movies
        for url, img, title in movies:
            self.movie_list.append(show_(title, url, img, None))

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

    def list_hosters(self, data):
        print 'list_hosters'
        self.index = '3'
        self.hoster_list = []
        hosters = re.findall('<td><a href="(.*?)"> (.*?) </a>.*?<br />.*?<span class="user-icn"> <small> <em>.*?</em></small> <small><em>.*?</em></small></span></td>.*?<td>(.*?)</td>.*?<td><span class="bold insist"> Streaming </span>', data, re.DOTALL)
        for url, hoster, info in hosters:
            print hoster
            url = 'http://www.cinemay.com' + url
            if hoster == 'youwatch.org':
                title = hoster + '-' + info
                self.hoster_list.append(show_(title, url, None, None))

        self['menulist'].l.setList(self.hoster_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        return

    def get_link(self, data):
        print 'get_link'
        new_uri = re.findall('<iframe src="(.*?)" frameborder="0" allowfullscreen scrolling="no" width="..." height="..."></iframe>', data)
        if new_uri:
            getPage(new_uri[0], timeout=8, method='GET', headers={'Referer': 'http://www.cinemay.com/voir/56247/',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_final_link, new_uri[0])
        else:
            new_uri = re.findall('<iframe.*?src="(.*?)"', data)
            ref = new_uri[0]
            if new_uri:
                getPage(new_uri[0], timeout=8, method='GET', headers={'Referer': 'http://www.cinemay.com/voir/56247/',
                 'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_final_link, new_uri[0])

    def get_final_link(self, data, ref):
        print data
        new_uri = re.findall('src="(.*?)"', data, re.DOTALL)
        print new_uri
        new_uri = new_uri[0].replace('\n', '')
        if new_uri:
            getPage(new_uri, timeout=8, method='GET', headers={'Referer': ref,
             'Host': 'va6.thand.info',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_final_link1, new_uri)

    def get_final_link1(self, data, ref):
        print data
        new_uri = re.findall('<iframe.*?src="(.*?)"', data)
        print new_uri
        getPage(new_uri[0], timeout=8, method='GET', headers={'Referer': ref,
         'Host': 'va6.thand.info',
         'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_final_link5, new_uri[0])

    def get_final_link5(self, data, ref):
        print data
        file = re.findall('file:"(.*?)",', data)
        if file:
            self.play_that_shit(file[0])

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

    def search_cinemay(self, searchstring = None):
        self.index = 'search'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://www.cinemay.com/?s=' + searchstring_fin
            getPage(url, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.index = 'search_data'
        search = re.findall('<div class="unfilm"><div class="post" id="post-.*?"> <a href="(.*?)" rel="bookmark" title=".*?"><div class="imgpic"> <img class="imgpic" src="(.*?)" title="(.*?)"', data)
        if search:
            for each in search:
                url, img, title = each
                print title
                self.search_list.append(show_(title, url, img, None))

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

    def ok(self):
        if self.index == '1':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(url, timeout=8, method='GET', headers={'Referer': 'http://stream-oase.tv/movies/39-the-dark-knight',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.load_data_channels, url)
        elif self.index == '2':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(url, timeout=8, method='GET', headers={'Referer': 'http://stream-oase.tv/movies/39-the-dark-knight',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hosters)
        elif self.index == '3':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(url, timeout=8, method='GET', headers={'Referer': 'http://stream-oase.tv/movies/39-the-dark-knight',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)
        elif self.index == 'search_data':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(uri, timeout=8, method='GET', headers={'Referer': 'http://stream-oase.tv/movies/39-the-dark-knight',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hosters)

    def play_that_shit(self, data):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        if self.index == '1':
            self.close()
        elif self.index == '2':
            self.index = '1'
            self['menulist'].l.setList(self.catlist)
            self['menulist'].l.setItemHeight(40)
        elif self.index == '3':
            self.index = '2'
            self['menulist'].l.setList(self.movie_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()
        elif self.index == 'search_data':
            self.close()
        elif self.index == 'list_streams':
            self.index = 'search_data'
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()
        elif self.index == 'search_data':
            self.index = 'search'
            self.search()
        elif self.index == 'search':
            self.index = '1'
            self.abc()

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

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