# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/streamcomplete.py
from imports import *
if fileExists('/usr/lib/enigma2/python/Plugins/Extensions/MediaPlayer/plugin.pyo'):
    from Plugins.Extensions.MediaPlayer import *
    MediaPlayerInstalled = True
else:
    MediaPlayerInstalled = False
UserAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'

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 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 streamcomplete(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['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('Streamcomplet')
        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.show_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)
        if self.index == '1':
            self.load_poster()

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

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

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        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 show_cat(self):
        self.index = '0'
        self.cat_list = []
        self.cat_list.append(show_('ACCUEIL', 'http://streamcomplet.com/', None))
        self.cat_list.append(show_('ACTION', 'http://streamcomplet.com/film/action/page/', None))
        self.cat_list.append(show_('THRILLER', 'http://streamcomplet.com/film/thriller/page/', None))
        self.cat_list.append(show_('DRAME', 'http://streamcomplet.com/film/drame/page/', None))
        self.cat_list.append(show_('ANIMATION', 'http://streamcomplet.com/film/animation/page/', None))
        self.cat_list.append(show_('POLICIER', 'http://streamcomplet.com/film/policier/page/', None))
        self.cat_list.append(show_('FICTION', 'http://streamcomplet.com/film/fiction/page/', None))
        self.cat_list.append(show_('HORREUR', 'http://streamcomplet.com/film/horreur/page/', None))
        self.cat_list.append(show_('HISTORIQUE', 'http://streamcomplet.com/film/historique/page/', None))
        self.cat_list.append(show_('AVENTURE', 'http://streamcomplet.com/film/aventure/page/', None))
        self.cat_list.append(show_('MUSIQUE', 'http://streamcomplet.com/film/musique/page/', None))
        self.cat_list.append(show_('ROMANCE', 'http://streamcomplet.com/film/romance/page/', None))
        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        return

    def load_data_channels(self, url):
        self.index = '1'
        self.content_list = []
        i = 1
        for i in range(1, 10):
            url = url + str(i) + '/'
            req = urllib2.Request(url)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36')
            req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
            req.add_header('Referer', 'http://streamcomplet.com/')
            req.add_header('Host', 'streamcomplet.com')
            resp = urllib2.urlopen(req)
            html = resp.read()
            mov = re.findall('<div class="moviefilm">.*?<a href="(http://streamcomplet.com/.*?)">.*?<img src="(.*?)" alt="(.*?)" height="125px" width="180px" /></a>', html, re.DOTALL)
            for each in mov:
                url, img, title = each
                self.content_list.append(show_(title, url, img))

            i = i + 1
            url = self['menulist'].l.getCurrentSelection()[0][1]

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

    def get_link(self, url):
        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', 'http://streamcomplet.com/film/action/page/1')
        page = urllib2.urlopen(req)
        cookie = page.info()['Set-Cookie']
        response = page.read()
        page.close()
        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', 'http://streamcomplet.com/film/action/page/1')
        req.add_header('Cookie', cookie)
        req.add_header('X-Forwarded-FOR', '89.179.33.161')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        iframe = re.findall('<iframe src="(http://media.vimple.me/player.*?)" width="..." height="..." webkitAllowFullScreen', response)
        print iframe
        if iframe:
            print iframe
            id_link = iframe[0].replace('swf', 'swf/').replace('#038;', '')
            req = urllib2.Request(id_link)
            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', 'http://streamcomplet.com/film/action/page/1')
            req.add_header('X-Forwarded-FOR', '89.179.33.161')
            page = urllib2.urlopen(req)
            print page.info()
            response = page.read()
            page.close()
            new = re.findall('src: "(.*?)", type: "video/mp4"', response)
            print new
            if new:
                new = new[0].replace('skin', 'skin/')
                new_uri = 'http://media.vimple.me/player0.swf/' + new
                req = urllib2.Request(new_uri)
                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', 'http://streamcomplet.com/film/action/page/1')
                req.add_header('X-Forwarded-FOR', '89.179.33.161')
                req.add_header('Cookie', cookie)
                page = urllib2.urlopen(req)
                print page.info()
                location = page.geturl()
                print location
                id = re.findall('&id=(.*?)&type', location)[0]
                location = location
                h = hmm = 'http://127.0.0.1:88/hls://' + location + ' headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36","Host": "vd4.mycdn.me","Range": "bytes=0-","Referer": "http://media.vimple.me/player0.swf/?i=anarchy&f=33750977215","Connection": "keep-alive"}'
                self.play_that_shit(h)

    def setExtraHeaders(self, dictHeaders):
        headersString = '|'.join([ key + ':' + value for key, value in dictHeaders.iteritems() ])
        config.mediaplayer.extraHeaders.setValue(headersString)

    def resetExtraHeaders(self):
        config.mediaplayer.extraHeaders.setValue('')

    def ok(self):
        print self.index
        if self.index == '0':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            self.load_data_channels(url)
        elif self.index == '1':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            self.get_link(url)

    def exit(self):
        print self.index
        if self.index == '0':
            self.close()
        elif self.index == '1':
            self.index = '0'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def play_that_shit(self, data):
        sref = eServiceReference(4097, 0, data)
        self.session.open(MoviePlayer, sref)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/alarab_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/alarab/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 '[alarab] 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 '[alarab] no poster.. error'
        return

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