# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/hdmoviezone.py
from imports import *
from about import *
from StringIO import StringIO
import gzip
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
import urllib2
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36')]

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 show1_(name, link, image, index, url):
    res = [(name,
      link,
      image,
      index,
      url)]
    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 hdmoviezone(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}, -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('hdmoviezone')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.video_list = []
        self.loading_ok = False
        self.dir()
        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://www.hdmoviezone.net/category/Australia/feed/?paged=1', 'Australia'),
         ('http://www.hdmoviezone.net/category/Canada/feed/?paged=1', 'Canada'),
         ('http://www.hdmoviezone.net/category/China/feed/?paged=1', 'China'),
         ('http://www.hdmoviezone.net/category/Finland/feed/?paged=1', 'Finland'),
         ('http://www.hdmoviezone.net/category/France/feed/?paged=1', 'France'),
         ('http://www.hdmoviezone.net/category/Germany/feed/?paged=', 'Germany'),
         ('http://www.hdmoviezone.net/category/Hong-Kong/feed/?paged=1', 'Hong Kong'),
         ('http://www.hdmoviezone.net/category/India/feed/?paged=1', 'India'),
         ('http://www.hdmoviezone.net/category/Italy/feed/?paged=1', 'Italy'),
         ('http://www.hdmoviezone.net/category/Japan/feed/?paged=1', 'Japan'),
         ('http://www.hdmoviezone.net/category/South-Korea/feed/?paged=1', 'South Korea'),
         ('http://www.hdmoviezone.net/category/Spain/feed/?paged=1', 'Spain'),
         ('http://www.hdmoviezone.net/category/Sweden/feed/?paged=1', 'Sweden'),
         ('http://www.hdmoviezone.net/category/Thailand/feed/?paged=1', 'Thailand'),
         ('http://www.hdmoviezone.net/category/UK/feed/?paged=1', 'UK'),
         ('http://www.hdmoviezone.net/category/USA/feed/?paged=1', 'USA')]
        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('<title>(.*?)</title>.*?<link>(.*?)</link>.*?center;"><a href="(.*?)" style.*?<p><span class="summary">(.*?)</span></p>.*?<div file="(.*?)" height', data, re.DOTALL)
        if videos:
            for title, link, img, info, file in videos:
                self.video_list.append(show1_(title, file, img, info, link))

            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):
        url = 'http://gl.hdmoviezone.net/hdmzgl.php'
        ref = self['menulist'].getCurrent()[0][4]
        opener.open('http://gl.hdmoviezone.net/getimage.php')
        print cj
        file = self['menulist'].getCurrent()[0][1]
        req = urllib2.Request(ref)
        req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Referer', 'http://www.hdmoviezone.net/category/Germany/')
        req.add_header('Host', 'www.hdmoviezone.net')
        req.add_header('Cookie', '__cfduid=d07aa2105bd9a20c5b0568bccacae4a831448745939; hdmz_host=http%3A//tools.hdmoviezone.net/hdmzgl.php; jwplayer.captionLabel=Off; nopopatall=1448746059; popcashpu=1; popcashpuCap=1; defaults=4; __atuvc=9%7C47%2C1%7C48; MarketGidStorage=%7B%220%22%3A%7B%22svspr%22%3A%22https%3A%2F%2Fwww.google.de%2F%22%2C%22svsds%22%3A16%2C%22TejndEEDj%22%3A%22MTQ0ODc0NTk0OTIyODIyMzQ2MTA1%22%7D%2C%22C22346%22%3A%7B%22page%22%3A2%2C%22time%22%3A1448749115855%7D%2C%22C22352%22%3A%7B%22page%22%3A1%2C%22time%22%3A1448759809556%7D%7D; _ga=GA1.2.574419023.1448745953; _gat=1; popup_id=0; noadvtday=0')
        resp = urllib2.urlopen(req)
        ans = opener.open(ref)
        ht = ans.read()
        match = re.compile('<div file="(.*?)"').findall(ht)
        if match:
            file_hash = match[0]
            print file_hash
            opener.addheaders = [('Origin', 'http://www.hdmoviezone.net')]
            opener.open('http://gl.hdmoviezone.net/getimage.php')
            print cj
            form_data = urllib.urlencode({'url': file_hash})
            opener.addheaders = [('Host', 'gl.hdmoviezone.net')]
            opener.addheaders = [('Origin', 'http://www.hdmoviezone.net')]
            ans = opener.open(url, form_data)
            data = ans.read()
            print data
            buf = StringIO(ans.read())
            f = gzip.GzipFile(fileobj=buf)
            data = f.read()
            print data
            file = re.compile('"url":"(.+?)"').findall(data)
            if file:
                file = file[1].replace('\\', '')
                self.play_vid(file)

    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 ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'cat':
            url = str(selectedEntry)
            i = 1
            for i in range(1, 52):
                url = url + 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_videos)
                i = i + 1
                url = str(selectedEntry)

        elif self.info == 'videos':
            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)
            self.video_list = []
        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'