# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/teledunet.py
from setup import *
from imports import *
import datetime
import time
from teledunet_list import *
import random
from operator import itemgetter, attrgetter, methodcaller

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


class teledunet(Screen):

    def __init__(self, session):
        global old_ref
        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,
         'cancel': self.exit,
         'yellow': self.login,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('teledunet.com')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('Login'))
        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()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.abc)

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

    def login(self):
        userName = config.Albatros.teledunet_name.value
        password = config.Albatros.teledunet_password.value
        req = urllib2.Request('http://www.teledunet.com/')
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        page = urllib2.urlopen(req)
        response = page.read()
        cookie = page.info()['Set-Cookie']
        req = urllib2.Request('http://www.teledunet.com/boutique/connexion.php')
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        req.add_header('Cookie', cookie)
        post = {'login_user': userName,
         'pass_user': password}
        post = urllib.urlencode(post)
        page = urllib2.urlopen(req, post)
        response = page.read()
        post = {'onData': '[type Function]',
         'secure': '1'}
        post = urllib.urlencode(post)
        req = urllib2.Request('http://www.teledunet.com/mobile/access_id.php')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Encoding', 'gzip,deflate,sdch')
        req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
        req.add_header('Connection', 'keep-alive')
        req.add_header('Referer', 'http://www.teledunet.com/player.swf?')
        req.add_header('Host', 'www.teledunet.com')
        req.add_header('Cookie', cookie)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36')
        page = urllib2.urlopen(req, post)
        res = page.read()
        print res
        tmp_id0 = res.replace('?id1=', '')
        req = urllib2.Request('http://www.teledunet.com/mobile')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Encoding', 'gzip,deflate,sdch')
        req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
        req.add_header('Connection', 'keep-alive')
        req.add_header('Referer', 'http://www.teledunet.com/player.swf?')
        req.add_header('Host', 'www.teledunet.com')
        req.add_header('Cookie', cookie)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36')
        page = urllib2.urlopen(req)
        result = page.read()
        ip_patt = "ip='(.*?)';"
        dz_patt = "dz='(.*?)';"
        today = datetime.datetime.now()
        v1 = 234 * (366 - (today - datetime.datetime(today.year, 1, 1)).days + 0)
        v2 = 222
        dz = re.findall(dz_patt, result)[0]
        ip = re.findall(ip_patt, result)[0]
        acc_id = re.findall("access_id='\\?idu=(.*?)';", result)[0]
        print acc_id
        ip2 = ''.join(ip.split('.')[0:4])
        access_id = str((365 - int(dz)) * long(ip2) * v1 + v2)
        access_id = '' + access_id
        print access_id
        config.Albatros.teledunet_id1.setValue(acc_id)
        config.Albatros.teledunet_myip.setValue(ip2)
        config.Albatros.teledunet_dz.setValue(dz)
        rnd = str(int(time.time() * 1000))
        post = {'rndval': rnd}
        post = urllib.urlencode(post)
        req = urllib2.Request('http://www.teledunet.com/update_connect_date.php')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Encoding', 'gzip,deflate,sdch')
        req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
        req.add_header('Connection', 'keep-alive')
        req.add_header('Referer', 'http://www.teledunet.com/')
        req.add_header('Host', 'www.teledunet.com')
        req.add_header('Cookie', cookie)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36')
        page = urllib2.urlopen(req, post)
        res = page.read()
        print 'connection_data updated' + post

    def get_id0(self):
        id = config.plugins.teledunet.id0.value
        if id == 'get':
            req = urllib2.Request('http://www.teledunet.com/')
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
            page = urllib2.urlopen(req)
            response = page.read()
            cookie = page.info()['Set-Cookie']
            print cookie
            req = urllib2.Request('http://www.teledunet.com/mobile/access_id.php')
            req.add_header('Host', 'www.teledunet.com')
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0')
            req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
            req.add_header('Accept-Language', 'de,en-US;q=0.7,en;q=0.3')
            req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
            req.add_header('Referer', 'http://www.teledunet.com/mobile/')
            req.add_header('Cookie', 'cookie')
            req.add_header('Connection', 'keep-alive')
            req.add_header('X-Requested-With', 'ShockwaveFlash/16.0.0.305')
            page = urllib2.urlopen(req)
            res = page.read()
            print res
            if 'id1' in res:
                tmp_id0 = res.replace('?id1=', '')
                return tmp_id0
            else:
                return 'fuck'

    def export(self):
        id0 = config.plugins.teledunet.id0.value
        idu = config.plugins.teledunet.idu.value
        target_file = '/etc/enigma2/userbouquet.arabteledunet.tv'
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        tmp_swf = 'http%3A//www.teledunet.com/mobile//player.swf'
        tmp_page_url = 'http%3A//www.teledunet.com/mobile/'
        old = ':'
        new = '%3A'
        if idu is not '0':
            tmp_idu = str(idu)
            print 'IDU : %s' % tmp_idu
            open(target_file, 'w').close()
            f = open(target_file, 'r+')
            newf = '#NAME Arabic Teledunet \n'
            f.writelines(newf)
            url = 'http://www.pastebin.com/download.php?i=fKh4gG5s'
            req = urllib2.Request(url)
            try:
                html = urllib2.urlopen(req).read()
                channels = re.findall('onclick="set_favoris\\(\'(.*)\',\'.*?\',\'(rtmp://.*teledunet/)(.*)\'', html)
                for line in channels:
                    channelname, url, playpath = line
                    url = re.sub(old, new, url)
                    newf = ('#SERVICE 4097:0:1:0:0:0:0:0:0:0:',
                     'rtmp%3a//www.teledunet.com%3a1935/live?idu=',
                     tmp_idu,
                     '/',
                     playpath,
                     ':',
                     playpath,
                     '\n',
                     '#DESCRIPTION ',
                     channelname,
                     '\n')
                    f.writelines(newf)

                os.system('wget -qO - http://127.0.0.1/web/servicelistreload?mode=2 > /dev/null 2>&1')
            except URLError as e:
                print e.reason
                self.session.open(MessageBox, _('Export went wrong - try again in a minute!'), MessageBox.TYPE_INFO)

        elif id0 is not '0':
            tmp_id0 = str(id0)
            print 'ID0 : %s' % tmp_id0
            open(target_file, 'w').close()
            f = open(target_file, 'r+')
            newf = '#NAME Arabic Teledunet \n'
            f.writelines(newf)
            url = 'http://www.pastebin.com/download.php?i=fKh4gG5s'
            req = urllib2.Request(url)
            try:
                html = urllib2.urlopen(req).read()
                channels = re.findall('onclick="set_favoris\\(\'(.*)\',\'.*?\',\'(rtmp://.*teledunet/)(.*)\'', html)
                for line in channels:
                    channelname, url, playpath = line
                    if 'bein_sport_' in str(playpath):
                        url = 'rtmp://178.33.241.201:1935/bein/'
                    token = str(int('11' + str(int(999999 + random.random() * 99000000))) * 65)
                    url = re.sub(old, new, url)
                    newf = ('#SERVICE 4097:0:1:0:0:0:0:0:0:0:',
                     url,
                     '%20playpath=',
                     playpath,
                     '%20swfUrl=',
                     tmp_swf,
                     '?id0=',
                     tmp_id0,
                     '&channel=',
                     playpath,
                     '&user=teledunet',
                     '&token=',
                     token,
                     ' live=1 flashVer=0 ',
                     'pageUrl=',
                     tmp_page_url,
                     ':',
                     playpath,
                     '\n',
                     '#DESCRIPTION ',
                     channelname,
                     '\n')
                    f.writelines(newf)

                os.system('wget -qO - http://127.0.0.1/web/servicelistreload?mode=2 > /dev/null 2>&1')
            except urllib2.URLError as e:
                print e.reason
                self.session.open(MessageBox, _('Export went wrong - try again in a minute!'), MessageBox.TYPE_INFO)

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.currentList == 'menulist':
            self.load_poster_teledunet()

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.currentList == 'menulist':
            self.load_poster_teledunet()

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.currentList == 'menulist':
            self.load_poster_teledunet()

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.currentList == 'menulist':
            self.load_poster_teledunet()

    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'
        url = 'http://www.teledunet.com/'
        self.load_data_channels()

    def load_data_channels(self):
        self.index = 'channels'
        self.letter_list = []
        for each in teledunet_list:
            url, img_path, playpath = each
            img_path = str(img_path).replace(' ', '%20')
            self.letter_list.append(show_(playpath, url, img_path))

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

    def stringToCode(self, str):
        r = 0
        for i in range(0, len(str)):
            r += ord(str[i])

        return r

    def ok(self):
        if self.check == 'abc':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            id = config.Albatros.teledunet_id1.value
            idu = config.Albatros.teledunet_idu.value
            myip = config.Albatros.teledunet_myip.value
            chID = str(selectedName).lower().replace(' ', '_')
            third_url = 'http://www.teledunet.com/mobile/'
            import random
            print 'chID= %s' % chID
            print 'myip= %s' % myip
            dz = config.Albatros.teledunet_dz.value
            myip = int(str(myip).replace('.', ''))
            token = myip * int(dz)
            epoch_time = int(time.time())
            token = str(long(myip) * long(dz)) + '_' + str(int(time.time()))
            print 'real token : ' + token
            if id == 'get':
                tmp_id = str(self.get_id0())
                print tmp_id
                if tmp_id == 'fuck':
                    idu = 'ayechy_70521647130'
                    selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
                    playpath = str(selectedName).lower().replace(' ', '_')
                    link = 'rtmp://167.114.101.234:1935/live?idu=' + idu + '/' + playpath
                    self.play_that_shit(link)
                else:
                    selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
                    link = str(selectedEntry)
                    splitted = str(selectedEntry).split('/')
                    selectedStreamer = str(splitted[0]) + '/' + str(splitted[1]) + '/' + str(splitted[2]) + '/' + str(splitted[3])
                    swfUrl0 = 'http://www.teledunet.com/mobile/player.swf?id1='
                    swfUrl1 = swfUrl0 + tmp_id
                    swfUrl2 = swfUrl1 + '&channel=%s' % str(selectedName).lower().replace(' ', '_')
                    swfUrl3 = swfUrl2 + '&user=teledunet&tOken=%s' % token
                    playpath = str(selectedName).lower().replace(' ', '_')
                    pageUrl = 'http://www.teledunet.com/mobile/'
                    final_url = link + ' ' + 'playpath=' + playpath + ' swfUrl=' + swfUrl3 + ' pageUrl=' + pageUrl + ' flashVer=WIN/2017,0,0,169'
                    self.play_that_shit(final_url)
            elif id is not 'get' and idu is '0':
                userName = config.Albatros.teledunet_name.value
                req = urllib2.Request('http://www.teledunet.com/mobile')
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0')
                req.add_header('Referer', 'http://www.teledunet.com/')
                page = urllib2.urlopen(req)
                res = page.read()
                selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
                link = str(selectedEntry)
                if 'nothing' in link:
                    self.play_that_shit(link)
                else:
                    playpath = str(selectedName).lower().replace(' ', '_')
                    url = 'http://www.teledunet.com/mobile/http_player/?channel=' + playpath
                    req = urllib2.Request(url)
                    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0')
                    req.add_header('Referer', 'http://www.teledunet.com/mobile/http_player/?channel=teledunet_tv')
                    page = urllib2.urlopen(req)
                    res = page.read()
                    file = re.findall('src: "(.*?)",', res)
                    if file:
                        print file
                        file = file[0] + id
                        print file
                        self.play_that_shit(file)
            elif idu is not '0':
                selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
                playpath = str(selectedName).lower().replace(' ', '_')
                link = 'rtmp://www.teledunet.com:1935/live?idu=' + idu + '/' + playpath
                self.play_that_shit(link)
            else:
                self.session.open(MessageBox, _('You have to enter id0 OR idu in setup screen !'), MessageBox.TYPE_INFO)

    def play_that_shit(self, data):
        self.index = '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 exit(self):
        if self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'channels'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        else:
            self.close()

    def load_poster_teledunet(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 '[ArabicEntertainment : teledunet] shit no cover.. '
        return

    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

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