# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/filmon.py
from setup import *
from imports import *
cj = {}

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, session):
    res = [(name,
      link,
      img,
      session)]
    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 filmon(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}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['title'] = Label('filmon.com')
        self['name'] = Label('')
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.onLayoutFinish.append(self.cat)

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

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

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

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

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        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 cat(self):
        self.index = 'cat'
        self.cat_list = []
        session = self.get_session()
        #url = 'http://eu.api.filmon.com/api/channels?session_key=%s&quality=low' % session
        url='https://www.filmon.com/channels/'
        req = urllib2.Request(url)
        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('Referer', 'https://www.filmon.com/')#XMLHttpRequest
        req.add_header('X-Requested-With', 'XMLHttpRequest')#
        page = urllib2.urlopen(req)
        r = page.read()
        print r
#{"id":364,"logo":"https:\/\/static.filmon.com\/assets\/channels\/364\/logo.png?v2","big_logo":"https:\/\/static.filmon.com\/assets\/channels\/364\/big_logo.png","title":"M6 BOUTIQUE LA CHAINE","alias":"m6-boutique-la-chaine","description":"French Variety and News Broadcaster.","has_description":true,"group":"FRENCH TV","group_id":27,"group_alias":"french-tv","type":"standard","is_free":false,"is_free_sd_mode":true,"free_sd":true,"is_adult":false,"adult_content":false,"is_interactive":false,"is_vod":false,"is_vox":false,"has_tvguide":true,"recordable":true,"chat_keyword":"m6-boutique-la-chaine","created_at":1314662114,"is360":false,"has360Sound":false,"jwplatform_media_id":"XlW9aoAh","is_favorite":false}
        channels = re.findall('"id":(.*?),"logo":".*?","big_logo":"(.*?)","title":"(.*?)",', r)
        print channels
        for id, img,title in channels:
            img = img.replace('\\', '')
            self.cat_list.append(show_(title, id, img, session))

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

    def get_session(self):
        url = 'http://www.filmon.com/tv/api/init?app_android_device_model=GT-N7000&app_android_test=false&app_version=2.0.90&app_android_device_tablet=true&app_android_device_manufacturer=SAMSUNG&app_secret=wis9Ohmu7i&app_id=android-native&app_android_api_version=10%20HTTP/1.1&channelProvider=ipad&supported_streaming_protocol=rtmp'
        req = urllib2.Request(url)
        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)
        r = page.read()
        session = re.findall('"session_key":"(.*?)"', r)
        if session:
            return str(session[0])
        else:
            return 'none'

    def ok(self):
        if self.index == 'cat':
            id = self['menulist'].getCurrent()[0][1]
            session = self['menulist'].getCurrent()[0][3]
            url = 'https://www.filmon.com/ajax/getChannelInfo?channel_id=%s' % str(id)
            print url
            getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host':'www.filmon.com','X-Requested-With':'XMLHttpRequest','Referer':'https://www.filmon.com','User-Agent': 'Android'}).addCallback(self.get_rtmp)

    def get_rtmp(self, data):
        print data
        rtmp = re.findall('"quality":"high","url":"(.*?)"', data)
        if rtmp:
            first = rtmp[0].replace('\\', '')
            fin_url = first
            self.play_that_shit(fin_url)

    def play_that_shit(self, data):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        if self.index == 'cat':
            self.close()
        elif self.index == 'channels':
            self.index = 'cat'
            self['menulist'].l.setList(self.cat_list)

    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'