# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/yooanime.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, 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


class yooanime(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,
         'cancel': self.exit,
         'red': self.exit,
         'yellow': self.login,
         'blue': self.dnitnow}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('Login'))
        self['blue'] = Label('Free CH')
        self['Menu'] = Label(_(' '))
        self['poster'] = Pixmap()
        self['title'] = Label('yooanime')
        self['name'] = Label('')
        self['text'] = 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.abc)

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

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

    def dnitnow(self):
        self.index = 'freelist'
        self.free_list = []
        yoolive_freelist = [('2m', '2m'),
         ('bein_movie1', 'Bein Movie HD 1'),
         ('bein_movie2', 'Bein Movie HD 2'),
         ('rtm', 'RTM'),
         ('2m', '2M'),
         ('medi_1', 'Medi 1'),
         ('riyadiya', 'Riyadiya'),
         ('algerie', 'Algerie'),
         ('m6', 'M6'),
         ('mbc_1', 'MBC 1'),
         ('mbc2', 'MBC 2'),
         ('mbc3', 'MBC 3'),
         ('mbc4', 'MBC 4'),
         ('mbc_action', 'MBC Action'),
         ('mbc_max', 'MBC Max'),
         ('mbc_drama', 'MBC Drama'),
         ('mbc_bollywood', 'MBC Bollywood'),
         ('art_cinema', 'ART Cinema'),
         ('art_aflam', 'ART Aflam 1'),
         ('art_aflam2', 'ART Aflam 2'),
         ('art_hekayat', 'ART Hekayat 1'),
         ('art_hekayat2', 'ART Hekayat 2'),
         ('cplus_cinema', 'C+ Cinema'),
         ('national_ar', 'National Geo AR'),
         ('star_cinema_1', 'Star Cinema 1'),
         ('star_cinema_2', 'Star Cinema 2'),
         ('zee_alwan', 'Zee Alwan'),
         ('zee_aflam', 'Zee Aflam'),
         ('eska', 'ESKA'),
         ('cbc', 'CBC'),
         ('melody', 'Melody'),
         ('melody_aflam', 'Melody Aflam'),
         ('melody_classic', 'Melody Classic'),
         ('cartoon_ar', 'Cartoon Arabic'),
         ('cplus_decale', 'Canal+ Decale'),
         ('cplus_serie', 'Canal+ Serie'),
         ('cplus_family', 'Canal+ Family')]
        for each in yoolive_freelist:
            playpath, title = each
            url = 'http://yooanime.com/free/embed.php?channel=%s&W=600&H=400&skin=&logo=#' % playpath
            img = 'http://'
            self.free_list.append(show_(title, url, img))

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

    def login(self):
        COOKIEFILE = '/tmp/cookie_yoolive.txt'
        userName = config.Albatros.yoolive_name.value
        password = config.Albatros.yoolive_password.value
        req = urllib2.Request('http://yooanime.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://yooanime.com/login.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('Host', 'yooanime.com')
        req.add_header('Origin', 'http://yooanime.com/')
        req.add_header('Referer', 'http://yooanime.com/index.php')
        req.add_header('Cookie', cookie)
        post = {'username': userName,
         'password': password}
        post = urllib.urlencode(post)
        page = urllib2.urlopen(req, post)
        response = page.read()
        print response
        f = open(COOKIEFILE, 'w')
        f.writelines(cookie)
        f.close()
        print cookie

    def up(self):
        self[self.currentList].up()
        if self.index == '1':
            self.load_poster()

    def down(self):
        self[self.currentList].down()
        if self.index == '1':
            self.load_poster()

    def left(self):
        self[self.currentList].pageUp()
        if self.index == '1':
            self.load_poster()

    def right(self):
        self[self.currentList].pageDown()
        if self.index == '1':
            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'
        self.load_data_channels()

    def load_data_channels(self):
        self.index = '1'
        self.letter_list = []
        url = 'http://yooanime.com/'
        req = urllib2.Request(url)
        req.add_header('Referer', 'http://yooanime.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()
        print response
        page.close()
        yoolive_list = re.findall('<li id="focus"><a href="(.*?)"><img src = "(.*?)" style="margin:5px;width:40px;height:40px;vertical-align:middle"/>(.*?)</a></li>', response)
        for each in yoolive_list:
            url, img, playpath = each
            url = 'http://yooanime.com/' + str(url)
            self.letter_list.append(show_(playpath, url, img))

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

    def ok(self):
        rest = ' flashVer=WIN%2015,0,0,189 app=live/ swfUrl=http://yoolive.com/player/jwplayer.flash.swf pageUrl=http://yooanime.com/?Channel=arena_sport live=1 timeout=15'
        from cookielib import CookieJar, DefaultCookiePolicy
        policy = DefaultCookiePolicy(rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict, blocked_domains=['ads.net', '.ads.net'])
        cj = CookieJar(policy)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        if self.index == '1':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            import os
            import os.path
            PATH = '/tmp/cookie_yoolive.txt'
            req = urllib2.Request(selectedEntry)
            req.add_header('Referer', 'http://yooanime.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()
            print response
            page.close()
            rtmp_link = re.findall('file:"(.*?)",type:\'rtmp\'', response)
            print rtmp_link
            if rtmp_link:
                if rtmp_link[0].startswith('rtmp://yoolive') and rtmp_link[0]:
                    final_url = rtmp_link[0] + rest
                else:
                    final_url = rtmp_link[0]
                self.play_that_shit(final_url)
            else:
                rtmp = re.findall('file: "(.*?)",', response)
                if rtmp:
                    self.play_that_shit(rtmp[0])
        elif self.index == 'freelist':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            req = urllib2.Request(selectedEntry)
            req.add_header('Referer', 'http://yooanime.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()
            print response
            page.close()
            streamer = re.findall("var _popx = '(.*?)';", response)
            print streamer
            playpath = re.findall("var _popy=_popx\\+'(.*?)';", response)
            print playpath
            add1 = re.findall("var _popz=_popy\\+'(.*?)';", response)
            print add1
            add2 = re.findall("var ppv=_popz\\+'(.*?)';", response)
            print add2
            add3 = re.findall("var codev=ppv\\+'(.*?)';", response)
            print add3
            add4 = re.findall("var codev_=ppv\\+'(.*?)';", response)
            print add4
            if streamer and playpath and add2 and add3:
                fin_u = streamer[0] + playpath[0] + '?code=' + add2[0] + add3[0] + ' swfUrl=http://yooanime.com/player/jwplayer.flash.swf pageUrl=' + selectedEntry
                print fin_u
                self.play_that_shit(fin_u)

    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/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 '[teledunet] no cover.. error'
        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'


def main(session, **kwargs):
    session.open(yooanime)


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='Teledunet', description='Teledunet Streamer', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]