# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/iptv_planet.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):
    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 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 iptv_planet(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['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('IPTV-Planet.com')
        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.abc)

    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.load_poster()

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

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

    def right(self):
        self[self.currentList].pageDown()
        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 abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'Al Cinema'
        uri = 'http://iptv-planet.com/'
        getPage(uri, timeout=8, method='GET', headers={'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)

    def load_data_channels(self, data):
        self.index = '1'
        self.letter_list = []
        channels = re.findall('<a href="(.*?)"  ><img src="(.*?)" alt="" width=".." height=".." border="0"></a><br>', data)
        for each in channels:
            url, img = each
            title = str(url).replace('.php', '').upper()
            img = 'http://iptv-planet.com/' + img
            url = 'http://iptv-planet.com/' + url
            self.letter_list.append(show_(title, url, img))

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

    def ok(self):
        final_uri = self['menulist'].l.getCurrentSelection()[0][1]
        getPage(final_uri, timeout=8, method='GET', headers={'Host': 'iptv-planet.com',
         'Referer': 'http://iptv-planet.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.get_link)

    def get_link(self, data):
        iframe = re.findall("<iframe frameborder='0' marginheight='0' marginwidth='0' scrolling='no' src='(.*?)' width='600' height='400'></iframe>", data)
        if iframe:
            getPage(iframe[0], timeout=8, method='GET', headers={'Host': 'iptv-planet.com',
             'Referer': 'http://iptv-planet.com/',
             '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_link1, iframe[0])

    def get_link1(self, data, ref):
        javascript = re.findall("file='(.*?)';", data)
        print javascript
        if javascript:
            width=600
            height=400
            uri='http://embed.iptv-pla.net/embedPlayer.js'			
            req = urllib2.Request(uri)
            req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36')
            req.add_header('Referer','http://iptv-planet.com/mbcmasr.html')
            page = urllib2.urlopen(req)
            response = page.read()
            print response
            weval=re.findall('width.*?= (.*?);',response)[0];
            heval=re.findall('height.*?= (.*?);',response)[0];
            kval=re.findall('(&key.*?)>',response)[0];
            print kval
            weval=weval.replace('parseInt','int')
            heval=heval.replace('parseInt','int')
            fh=eval(heval)
            fw=eval(weval)
            print fh
            print fw
            print javascript
            pagename=javascript[0]
            if '_' in pagename:
                pagename=pagename.split('_')[1]
            else:
                pagename=pagename.replace('mbc1notallowedinunitedstates','hi_mbc1') #http://embed.iptv-pla.net/embed.php?id='+file+'&width='+width2+'&height='+height2+'&key2=1118
            pageurl="http://embed.iptv-pla.net/embed.php?id=%s&width=%s&height=%s&%s"%(pagename,str(fw),str(fh),kval)
            print pageurl
            getPage(pageurl, timeout=8, method='GET', headers={'Host': 'embed.iptv-pla.net',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded',
             'Cookie':'__cfduid=d6c425cd258f625400b9e8fded252bbef1477319269; HstCfa2736446=1477319473354; HstCmu2736446=1477319473354; c_ref_2736446=http%3A%2F%2Fiptv-planet.com%2Fcbc.html; HstCla2736446=1477320517396; HstPn2736446=2; HstPt2736446=2; HstCnv2736446=1; HstCns2736446=2',
             'Referer': 'http://iptv-planet.com/%s.html'}).addCallback(self.get_link2, pageurl)%pagename

            #req1 = urllib2.Request(pageurl)
            #req1.add_header('Connection','keep-alive')
            #req1.add_header('Cookie','__cfduid=d6c425cd258f625400b9e8fded252bbef1477319269')
            #req1.add_header('Host','embed.iptv-pla.net')
            #req1.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36')		
            #req1.add_header('Referer','http://iptv-planet.com/%s.html')%pagename
            #page = urllib2.urlopen(req1)
            #response = page.read() 
            #print response
    def get_link2(self,data,pageurl):
            print data	
            rtmpUrl = re.search(r'var myPlayer="(.*?)".\n.*streamer="(.*?)"', data)
            file = re.findall("file.+'(.*key.*)'", data)[0]
            file=file.replace('mbc1notallowedinunitedstates','hi_mbc1')
            pageurl=pageurl.replace('mbc1notallowedinunitedstates','hi_mbc1')
            url=rtmpUrl.group(2) + ' playpath=' + file + ' swfUrl=http://embed.iptv-pla.net/' + rtmpUrl.group(1) + ' live=1 timeout=15 flashVer=WIN\\2019,0,0,245 swfVfy=true pageUrl=' + pageurl
            #streamer=re.findall('streamer="(.*?)";',data)
            #print streamer
            #streamer=streamer[0]
            #playpath=re.findall('var channelname="(.*?)";',data)[0]
            #url='%s/%s swfUrl=http://embed.iptv-pla.net/swfs/player.swf pageUrl=%s swfVfy=1'%(streamer,playpath,pageurl)
            print url
            self.play_that_shit(url)

    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):
        self.close()

    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 = '/usr/lib/enigma2/python/Plugins/Extensions/shahidSeries/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 '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 'no cover.. error'
        return

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

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found, try again later on'), MessageBox.TYPE_INFO, timeout=3)

    def errorload2(self, error):
        print '[teledunet] error %s' % error
        count_movies = len(self.letter_movielist)
        self.loading_ok = True
        self.loading = 0
        self.count = 0

    def errorload(self, error):
        print error