# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/kinoger.py
from imports import *
from about import *
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=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def show3_(name, link, image):
    res = [(name, link, image)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, 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 freetvstream(Screen):

    def __init__(self, session):
        global old_ref
        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,
         'green': self.search,
         '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(_('About'))
        self['green'] = Label(_('Search'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('FreeTVStream')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.info = ''
        self.index = ''
        self.video_list = []
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        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.info == 'cat':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'cat':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'cat':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'cat':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def show_cat(self):
        self.info = 'cat'
        self.cat = []
        self.cat_list = [
        ("http://freetvstream.in/de/filme/lady56.php","http://freetvstream.in/de/img/ustream.png","Lady56 Filme"),
        ("http://freetvstream.in/de/filme/edelsmovies.php","http://freetvstream.in/de/img/ustream.png","Edels Movies"),
        ("http://freetvstream.in/de/filme/dumbo.php","http://freetvstream.in/de/img/ustream.png","Dumbo Tv"),
        ("http://freetvstream.in/de/filme/dumbo2.php","http://freetvstream.in/de/img/ustream.png","Dumbo Tv 2"),
        ("http://freetvstream.in/de/filme/movie4.php","http://freetvstream.in/de/img/ustream.png","Movie 4"),
        ("http://freetvstream.in/de/filme/moviesgerman.php","http://freetvstream.in/de/img/ustream.png","Movies German"),
        ("http://freetvstream.in/de/filme/letzfetz.php","http://freetvstream.in/de/img/ustream.png","LetzFetz Movies"),
        ("http://freetvstream.in/de/filme/movieland.php","http://freetvstream.in/de/img/ustream.png","Movie Land"),
        ("http://freetvstream.in/de/filme/movielandcrime.php","http://freetvstream.in/de/img/ustream.png","Movie Land Crime"),
        ("http://freetvstream.in/de/filme/movielandkids.php","http://freetvstream.in/de/img/ustream.png","Movie Land Kids/Family"),
        ("http://freetvstream.in/de/filme/germanmovies.php","http://freetvstream.in/de/img/ustream.png","German Movies"),
        ("http://freetvstream.in/de/filme/cloudtv.php","http://freetvstream.in/de/img/ustream.png","Cloud Tv"),
        ("http://freetvstream.in/de/filme/dhunter.php","http://freetvstream.in/de/img/ustream.png","Dhunter"),
        ("http://freetvstream.in/de/filme/rappelkiste.php","http://freetvstream.in/de/img/ustream.png","Rappelkiste"),
        ("http://freetvstream.in/de/filme/gmovies.php","http://freetvstream.in/de/img/ustream.png","Gangster Movies"),
        ("http://freetvstream.in/de/filme/moviemix.php","http://freetvstream.in/de/img/ustream.png","Movie Mix"),
        ("http://freetvstream.in/de/filme/marvel.php","http://freetvstream.in/de/img/ustream.png","MarvelDc Movies"),
        ("http://freetvstream.in/de/filme/budhill.php","http://freetvstream.in/de/img/ustream.png","Bud Spencer & Terence Hill"),
        ("http://freetvstream.in/de/doku/boogie.php","http://freetvstream.in/de/img/ustream.png","BoogiesDoku"),
        ("http://freetvstream.in/de/doku/crime.php","http://freetvstream.in/de/img/ustream.png","Crime Central"),
        ("http://freetvstream.in/de/doku/dokumix.php","http://freetvstream.in/de/img/ustream.png","Doku Mix"),
        ("http://freetvstream.in/de/doku/ufo.php","http://freetvstream.in/de/img/ustream.png","UFO - Universum Mix"),
        ("http://freetvstream.in/de/doku/flussmonster.php","http://freetvstream.in/de/img/ustream.png","Flussmonster"),
        ("http://freetvstream.in/de/doku/mythbusters.php","http://freetvstream.in/de/img/ustream.png","Mythbusters"),
        ("http://freetvstream.in/anim/animemix.php","http://freetvstream.in/de/img/ustream.png","Anime Mix"),
        #("http://freetvstream.in/anim/southpark.php","http://freetvstream.in/de/img/leton.png","South Park"),
        #("http://freetvstream.in/anim/simpsons.php","http://freetvstream.in/de/img/castamp.png","Die Simpsons"),
        ("http://freetvstream.in/anim/simpsons2.php","http://freetvstream.in/de/img/ustream.png","Die Simpsons 2"),
        #("http://freetvstream.in/anim/conan.php","http://freetvstream.in/de/img/leton.png","Detektiv Conan"),
        #("http://freetvstream.in/anim/onepiece.php","http://freetvstream.in/de/img/leton.png","One Piece"),
        ("http://freetvstream.in/anim/familyguy.php","http://freetvstream.in/de/img/ustream.png","Family Guy"),
        ("http://freetvstream.in/anim/americandad.php","http://freetvstream.in/de/img/ustream.png","American Dad"),]
        for url, img, title in self.cat_list:
            self.cat.append(show_(title, url,img))
        self['menulist'].l.setList(self.cat)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        self.load_poster()

    def get_videos(self, data):
        self.info = 'videos'
        video_link = re.findall('onclick="Popup=window\.open\(\'(.*?)\',\'Popup\'', data)
        if video_link:
            getPage(video_link[0], timeout=8, method='GET', headers={'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.get_hls)

    def get_link(self, data):
        link = re.findall("namba\\.show\\(1,\\[\\['(.*?)'\\]\\]", data)
        if link:
            url = 'http://v1.kinoger.pw/stream/' + link[0]
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Host': 'v1.kinoger.pw',
             'Referer': 'http://kinoger.com/main/2562-ted-2-2015.html'}).addCallback(self.get_hls)

    def get_hls(self, data):
        file = re.findall('"contentId":(.*?),', data)
        if file:
            data="http://iphone-streaming.ustream.tv/uhls/"+file[0]+"/streams/live/iphone/playlist.m3u8"
            player_u = self.get_ustream(data)
            self.play_vid(player_u)
			
    def get_ustream(self, url):
        try:
            for i in range(1, 51):
                result = getUrl(url)
                if 'EXT-X-STREAM-INF' in result:
                    return url
                if 'EXTM3U' not in result:
                    return
                os.sleep(2)

            return
        except:
            return
			
    def StreamIsReady(self, video_id, i = 0, progressed = 0):
        RE_PROGRESSED = '#PROGRESSED (\\d+)%'
        url = 'http://iphone-streaming.ustream.tv/uhls/%s/streams/live/iphone/playlist.m3u8' % video_id
        print ' -->      url: %s' % url
        print ' -->        i: %d' % i
        if i < 20:
            playlist = urllib2.urlopen(url).read()
            if '#PROGRESSED' in playlist:
                progress = int(re.findall('#PROGRESSED (\\d+)%', playlist)[0])
                print ' --> progress: %d' % progress
                if progress > progressed:
                    return self.StreamIsReady(video_id=video_id, i=i, progressed=progress)
                else:
                    return self.StreamIsReady(video_id=video_id, i=i + 1, progressed=progress)
            else:
                i = 99
                return True
        else:
            return False


    def play_vid(self, data):
        self.info = '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 search(self):
        index = '1'
        self.session.openWithCallback(self.search_kinoger, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_kinoger(self, searchstring = None):
        index = '2'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://kinoger.com/?do=search&subaction=search&titleonly=3&story=%s&x=0&y=0&submit=submit' % searchstring_fin
            getPage(url, timeout=8, headers={'Host': 'kinoger.com',
             'Referer': 'http://kinoger.com',
             'Origin': 'http://kinoger.com',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.index = '3'
        search = re.findall('<div class="content_text">.*?<img src="(.*?)" style="float:left;" alt="(.*?)" title=".*?<span class="buttons"><a href="(.*?)"><span><b>Play</b></span>', data, re.DOTALL)
        if search:
            for each in search:
                img, title, url = each
                self.search_list.append(show3_(title, url, img))

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

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.index == '3':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)
        elif self.info == 'cat':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_videos)

        elif self.info == 'videos':
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)

    def exit(self):
        print self.info
        if self.info == 'cat':
            self.close()
        elif self.info == 'videos':
            self.info = 'cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info = 'cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)


    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 getUrl(url, cookieJar = None, post = None, timeout = 20, headers = None, returnResponse = False, noredirect = False, jsonpost = False):
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
    if jsonpost:
        req.add_header('Content-Type', 'application/json')
    if headers:
        for h, hv in headers:
            req.add_header(h, hv)

    response = opener.open(req, post, timeout=timeout)
    if returnResponse:
        return response
    link = response.read()
    response.close()
    return link