# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/zoptv.py
from setup import *
from imports import *
import urllib2
import cloudflare
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/46.0.2490.86 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, img):
    res = [(name, link, img)]
    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 zoptv(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,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('zoptv.com')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        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.load_data_countries)

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

    def jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]
            self.get_play_link(self.filmname, link)

    def up(self):
        self[self.currentList].up()
        self.show_cover()

    def down(self):
        self[self.currentList].down()
        self.show_cover()

    def left(self):
        self[self.currentList].pageUp()
        self.show_cover()

    def right(self):
        self[self.currentList].pageDown()
        self.show_cover()

    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 load_data_countries(self):
        self.index = '1'
        self.letter_list = [('http://www.zoptv.com/channels/international', 'International'),
         ('http://www.zoptv.com/channels/united-kingdom', 'United Kingdom'),
         ('http://www.zoptv.com/channels/united-states', 'United States'),
         ('http://www.zoptv.com/channels/china', 'China'),
         ('http://www.zoptv.com/channels/france', 'France'),
         ('http://www.zoptv.com/channels/germany', 'Germany'),
         ('http://www.zoptv.com/channels/india', 'India'),
         ('http://www.zoptv.com/channels/russia', 'Russia'),
         ('http://www.zoptv.com/channels/south-korea', 'South Korea'),
         ('http://www.zoptv.com/', 'Turkey')]
        self.country_list = []
        for url, title in self.letter_list:
            self.country_list.append(cat_(title, url))

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

    def load_data_channels(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        ans = cloudflare.createCookie(url)
        print ans
        self.load_data_channels1(ans)
        

    def load_data_channels1(self, data):
        self.index = '2'
        self.channels_list = [] #<a class="zp-channel" href="/live/3sat"> <img src="/assets/logo/3sat.png"> <span>3sat</span>
        channels = re.findall('<a class="zp-channel" href="(.*?)"> <img src="(.*?)"> <span>(.*?)</span>', data)
        if channels:
            for url, img, title in channels:
                url = 'http://www.zoptv.com' + url
                img = 'http://www.zoptv.com' + img
                self.channels_list.append(show_(title, url, img))

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

    def load_final_page(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print url
        cj = {}
        getPage(url, timeout=8, cookies=cj, method='GET', headers={'Host': 'www.zoptv.com',
         '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.play_that_shit)

    def ok(self):
        if self.index == '1':
            self.load_data_channels()
        elif self.index == '2':
            self.load_final_page()

    def play_that_shit(self, data):
        print data
        string_to_decode = re.findall("eval\\(decodeURIComponent\\(atob\\('(.*?)'\\)", data)
        print string_to_decode
        if string_to_decode:
            string_to_decode = string_to_decode[0]
            import base64
            decoded = base64.b64decode(string_to_decode)
            while 'atob' in decoded:
                decoded = re.findall("eval\\(decodeURIComponent\\(atob\\('(.*?)'\\)", decoded)[0]
                print decoded
                decoded = base64.b64decode(decoded)
                print decoded

            embed = re.findall('"src":"(.*?)"', decoded)
            if embed:
                print embed[0]
                if 'rtmp://' in embed[0]:
                    data = embed[0]
                    sref = eServiceReference(4097, 0, data)
                    self.session.open(MoviePlayer, sref)
                elif 'chunklist.m3u8' in embed[0]:
                    data = 'http://127.0.0.1:88/hls://' + embed[0]
                    sref = eServiceReference(4097, 0, data)
                    self.session.open(MoviePlayer, sref)
                else:
                    opener.addheaders = [('Host', 'www.juhe.ml')]
                    opener.addheaders = [('Referer', 'http://www.zoptv.com/live/atv')]
                    page = opener.open(embed[0])
                    ans = page.read()
                    print ans
                    if 'VERSION' or 'EXTM3U' in ans:
                        sref = eServiceReference(4097, 0, embed[0])
                        self.session.open(MoviePlayer, sref)
                    else:
                        file = re.findall("var src = '(.*?)';", ans)
                        print file
                        if file:
                            if file[0].startswith('live'):
                                file[0] = file[0].replace('live', '/live')
                                file = 'http://www.juhe.ml' + file[0]
                                data = 'http://127.0.0.1:88/hls://' + file + ' headers={"X-Requested-With":"ShockwaveFlash/19.0.0.226","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"}'
                                sref = eServiceReference(4097, 0, data)
                                self.session.open(MoviePlayer, sref)
                            elif file[0].startswith('/'):
                                file[0] = file[0]
                                file = 'http://www.juhe.ml' + file[0]
                                data = 'http://127.0.0.1:88/hls://' + file + ' headers={"X-Requested-With":"ShockwaveFlash/19.0.0.226","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"}'
                                sref = eServiceReference(4097, 0, data)
                                self.session.open(MoviePlayer, sref)
                            elif 'stream/playlist.m3u8?id' in file[0]:
                                file = file[0]
                                data = 'http://127.0.0.1:88/hls://' + file + ' headers={"X-Requested-With":"ShockwaveFlash/19.0.0.226","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"}'
                                sref = eServiceReference(4097, 0, data)
                                self.session.open(MoviePlayer, sref)
                            elif file[0].startswith('http://'):
                                file[0] = file[0]
                                file = file[0]
                                data = 'http://127.0.0.1:88/hlsvariant://' + file + ' headers={"X-Requested-With":"ShockwaveFlash/19.0.0.226","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"}'
                                sref = eServiceReference(4097, 0, data)
                                self.session.open(MoviePlayer, sref)

    def exit(self):
        self.close()

    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 = '/tmp'
        jpg_name = 'no_cover.png'
        file_name = 'test.jpg'
        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'

    def fetchHttp(self, url, args = {}, hdrs = {}, post = False):
        hdrs['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0'
        hdrs['X-Forwarded-For'] = '85.2.3.45'
        req = urllib2.Request(url, urllib.urlencode(args), hdrs)
        response = urllib2.urlopen(req)
        text = response.read()
        responsetext = text
        print responsetext
        response.close()
        return responsetext