# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/nowtv.py
from imports import *
import os
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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


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 nowtv(Screen):

    def __init__(self, session):
        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,
         'blue': self.dnitnow}, -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('NowTV')
        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.list_cat)

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

    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]

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

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

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

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

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('RTL Now', 'rtl', None),
         ('Vox Now', 'vox', None),
         ('RTL2 Now', 'rtl2', None),
         ('RTLNitro Now', 'rtlnitro', None),
         ('SuperRTL Now', 'superrtl', None),
         ('NTV Now', 'ntv', None)]
        for each in cat:
            category, link, thumb = each
            self.cat_list.append(show_(category, link, thumb))

        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return None

    def list_shows(self, link):
        self.info = 'list_shows'
        self.show_list = []
        filter_param = '{"Station":"%s","Disabled":"0","CategoryId":{"containsIn":["serie","news"]}}&maxPerPage=1000' % link
        uri = 'https://api.nowtv.de/v3/formats?fields=title,station,title,titleGroup,seoUrl,categoryId,*&filter=' + urllib.quote(filter_param)
        uri = uri.replace('%3A', ':').replace('%3D', '=').replace('%2C', ',').replace('%26', '&')
        print uri
        getPage(uri, timeout=8, method='GET', headers={'Host': 'api.nowtv.de',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.list_it)

    def list_it(self, data):
        print data
        movies = re.findall('"title":"(.*?)","station":".*?","titleGroup":".*?","seoUrl":"(.*?)"', data, re.DOTALL)
        for each in movies:
            name, seourl = each
            seourl = 'https://api.nowtv.de/v3/formats/seo?fields=*,.*,formatTabs.*,formatTabs.formatTabPages.*&name=' + seourl + '.php'
            name = name.replace('\\u00c4', '\xc3\x84').replace('\\u00e4', '\xc3\xa4').replace('\\u00d6', '\xc3\x96').replace('\\u00f6', '\xc3\xb6').replace('\\u00dc', '\xc3\x9c').replace('\\u00fc', '\xc3\xbc').replace('\\u00df', '\xc3\x9f')
            self.show_list.append(show_(name, seourl, None))

        self['menulist'].l.setList(self.show_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def list_episodes(self, path):
        self.info = 'list_episodes'
        self.episodes_list = []
        getPage(path, timeout=8, method='GET', headers={'Host': 'api.nowtv.de',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.list_episodes_a)

    def list_episodes_a(self, data):
        print data
        id = re.findall('"formatTabs":\\{"items":\\[\\{"id":(.*?),"headline":"Aktuell"', data)
        print id
        if id:
            id = id[0]
            path = 'https://api.nowtv.de/v3/formatlists/%s?fields=*,formatTabPages.*,formatTabPages.container.*,formatTabPages.container.movies.*,formatTabPages.container.movies.format.*,formatTabPages.container.movies.paymentPaytypes.*,formatTabPages.container.movies.pictures' % id
            print path
            getPage(path, timeout=8, method='GET', headers={'Host': 'api.nowtv.de',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.list_episodes1)

    def list_episodes1(self, data):
        print data
        episodes = re.findall('\\{"id":([0-9]{6}),"title":"(.*?)","free":true,"broadcastStartDate":".*?","articleShort":".*?","articleLong":".*?","teaserText":".*?","exclusive":false,', data, re.DOTALL)
        for each in episodes:
            video_id, name = each
            path = 'http://rtl-now.rtl.de/hds/videos/%s/manifest-hds.f4m' % video_id
            print path
            self.episodes_list.append(episodes_(name, path, None, None))

        self['menulist'].l.setList(self.episodes_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def get_play_link(self, data, path):
        print 'now we search the rtmp url'
        getPage(path, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.read_link)

    def read_link(self, data):
        link = re.findall('<media href="(.*?)" bitrate=".*?"/>', data, re.DOTALL)
        print link
        playp = link[1].replace('hds', 'hls').replace('.mp4.f4m', '.mp4.m3u8')
        print playp
        if link:
            comand = 'python /usr/lib/enigma2/python/Plugins/Extensions/Albatros/hlsclientnow.py ' + playp + ' 1 '
            os.system(comand + '&')
            os.system('sleep 5')
            self.play_movie('/tmp/shahid.avi')

    def play_movie(self, link):
        if link:
            sref = eServiceReference(4097, 0, link)
            self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.info == 'list_cat':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_shows(url)
        elif self.info == 'list_shows':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_episodes(url)
        elif self.info == 'list_episodes':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.filmname = str(selectedName)
            self.get_play_link(self.filmname, url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/hayyes_poster.jpg'):
                os.system('rm -r /tmp/hayyes_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_shows':
            self.info = 'list_cat'
            self['blue'].hide()
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_episodes':
            self.info = 'list_shows'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_streams':
            self.info = 'list_episodes'
            self['blue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)

    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'


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


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