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


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


class mykino(Screen):

    def __init__(self, session):
        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('mykino.to')
        self.currentList = 'menulist'
        self.menulist = []
        self.m_list = []
        self.dir()
        self.index = ''
        self.get_cat()

    def about(self):
        self.about()

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def get_cat(self):
        self.index = 'get_cat'
        self.cat_list = []
        self.cat = [('http://mykino.to/abenteuer', 'Abenteuer'),
         ('http://mykino.to/action', 'Action'),
         ('http://mykino.to/biographie', 'Biographie'),
         ('http://mykino.to/drama', 'Drama'),
         ('http://mykino.to/familie', 'Familie'),
         ('http://mykino.to/fantasy/', 'Fantasy'),
         ('http://mykino.to/horror', 'Horror'),
         ('http://mykino.to/komoedie/', 'Kom\xc3\xb6die'),
         ('http://mykino.to/krimi', 'Krimi'),
         ('http://mykino.to/romantik', 'Romantik'),
         ('http://mykino.to/sci-fi', 'Sci-Fi'),
         ('http://mykino.to/thriller', 'Thriller'),
         ('http://mykino.to/trickfilm', 'Trickfilm'),
         ('http://mykino.to/western', 'Western'),
         ('http://mykino.to/krieg', 'Krieg'),
         ('http://mykino.to/sport', 'Sport')]
        for url, title in self.cat:
            self.cat_list.append(cat_(title, url))

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

    def get_mlist(self, data):
        self.index = 'get_mlist'
        movies = re.findall('<div class="boxgrid2 caption2">\n<a href="(.*?)">\n<img class="images3" src="(.*?)" alt=""/>\n<div class="cover2 boxcaption2">\n<div class="boxgridtext">\n(.*?)\n</div>', data, re.DOTALL)
        for url, img, title in movies:
            self.m_list.append(show_(title, url, img))

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

    def get_hosters(self, data):
        print data
        hoster = re.findall('<ul class="mirrors-selector">.*?<li><a href="#" target="_blank" data-href="(http://streamcloud.eu/.*?),', data, re.DOTALL)
        print hoster
        if hoster:
            getPage(hoster[0], headers={'Origin': 'http://streamcloud.eu',
             'Host': 'streamcloud.eu',
             'Referer': 'http://streamcloud.eu/cpmx9mroxvnc/aced-und.dann.noch.paula.s01e01-480p.mkv.html',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.resolve_vivo, hoster[0])

    def resolve_vivo(self, data, url):
        print data
        if 'http://vivo.sx/' in url:
            param1 = re.findall('type="hidden" name="hash".*?value="(.*?)"', data)[0]
            param2 = re.findall('type="hidden" name="timestamp".*?value="(.*?)"', data)[0]
            if param1:
                post = urllib.urlencode({'hash': param1,
                 'timestamp': param2})
                getPage(url, method='POST', postdata=post, headers={'Host': 'vivo.sx',
                 'Origin': 'http://vivo.sx',
                 'Referer': '%s',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_vid_link) % url
        elif 'http://streamcloud.eu/' in url:
            form_values = {}
            for i in re.finditer('<input.*?name="(.*?)".*?value="(.*?)">', data):
                form_values[i.group(1)] = i.group(2).replace('download1', 'download2')

            post = urllib.urlencode(form_values)
            getPage(url, method='POST', postdata=post, headers={'Origin': 'http://streamcloud.eu',
             'Host': 'streamcloud.eu',
             'Referer': '%s',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_vid_link) % url

    def get_vid_link(self, data):
        print data
        final_uri = re.findall('class="stream-content" data-url="(.*?)"', data)
        if final_uri:
            self.play_channel(final_uri[0])
        else:
            final_uri = re.findall('file: "(.*?)",', data)
            if final_uri:
                self.play_channel(final_uri[0])

    def play_channel(self, data):
        selected = self['menulist'].getCurrent()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selected)
        self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.index == 'get_cat':
            url = self['menulist'].getCurrent()[0][1]
            header = [('User-Agent', '')]
            page = getUrl(url, headers=header, jsonpost=False)
            max_nr = re.findall('\\.\\.\\.</span> <a href="http://mykino.to/filme/.*?/">(.*?)</a>', page)
            if max_nr:
                max_nr = max_nr[0]
                i = 1
                for i in range(1, int(max_nr)):
                    url = url + '/page/' + str(i) + '/'
                    print url
                    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_mlist)
                    i += 1
                    url = self['menulist'].getCurrent()[0][1]

            else:
                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_mlist)
        elif self.index == 'get_mlist':
            url = self['menulist'].getCurrent()[0][1]
            header = [('User-Agent', '')]
            page = getUrl(url, headers=header, jsonpost=False)
            self.get_hosters(page)

    def exit(self):
        if self.index == 'get_cat':
            self.close()
        elif self.index == 'get_mlist':
            self.index = 'get_cat'
            self.m_list[:] = []
            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/albatros/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 = '/tmp/albatros/poster.jpg'
        jpg_name = 'cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(jpg_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 '[Albatros] 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 '[WWE] no cover.. error'
        return

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


def getUrl(url, cookieJar = None, post = None, timeout = 20, headers = None, returnResponse = False, noredirect = False, jsonpost = False):
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
    req.add_header('Referer', 'http://mykino.to/abenteuer')
    if jsonpost:
        req.add_header('Content-Type', 'application/json')
    if headers:
        for h, hv in headers:
            req.add_header(h, hv)

    response = opener.open(req, post, timeout=timeout)
    if returnResponse:
        return response
    link = response.read()
    response.close()
    return link