from imports import *
from about import *
from cookielib import CookieJar
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
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, image, idx):
    res = [(name,
      link,
      image,
      idx)]
    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 orflive(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,
         '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['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('ORF LiveTV')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.info = ''
        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 = [] #http://apasfiisl.apa.at/ipad/orf2/q6a.sdp/playlist.m3u8 15.06.2016 #http://apasfiisl.apa.at/ipad/orf3/q8c.sdp/playlist.m3u8
        self.cat_list = [('http://orf2n.orf.cdn.ors.at/orf1/q6a.sdp/chunklist.m3u8', 'ORF1 HD', 'http://www.lyngsat-logo.com/logo/tv/oo/orf_eins_hd.png', '1'),
         ('http://orf2n.orf.cdn.ors.at/orf2/q6a.sdp/chunklist.m3u8', 'ORF2 HD', 'http://www.lyngsat-logo.com/logo/tv/oo/orf_2_at_hd.png', '1'),
         ('http://orf2n.orf.cdn.ors.at/orf3/q6a.sdp/chunklist.m3u8', 'ORF III HD', 'http://www.lyngsat-logo.com/logo/tv/oo/orf_3_at_hd.png', '1'),
         ('http://orf2n.orf.cdn.ors.at/orfs/q6a.sdp/chunklist.m3u8', 'ORF SPORT PLUS', 'http://www.lyngsat-logo.com/logo/tv/oo/orf_sport_plus_hd.png', '1'),
         ('rtmp://streaming.austria24.tv/live/mp4:stream_720p', 'Austria24TV', 'http://austria24.tv/wp-content/uploads/2014/01/Logo3.png', '1'),
         ('rtmp://lb.hd-livestream.de:1935/live/TirolTV', 'TirolTV', 'http://www.tiroltv.at/wp-content/uploads/2014/04/cropped-logo.png', '1'),
         ('http://hdiosstv-f.akamaihd.net/i/servustvhd_1@51229/master.m3u8', 'ServusTV', 'http://www.servustv.com/img/layout/logo_schrift.png', '1'),
         ('http://d25u5wcs71awbk.cloudfront.net/videos-hl/live-dd502481-7a0d-441b-b907-6a0ab32f11d7_low.mp4', 'M\xc3\xbchlviertelTV', 'http://www.lyngsat-logo.com/logo/tv/mm/muhlviertel_tv_at.png', '1'),
         ('rtmp://stream007.gotv.at:1935/live/gotvlive_576p', 'gotv.at', 'http://www.lyngsat-logo.com/logo/tv/gg/go_tv_at.png', '1')]
        for url, title, img, idx in self.cat_list:
            self.cat.append(show_(title, url, img, idx))

        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):
        url = self['menulist'].getCurrent()[0][1]
        if 'rtmp://' in url:
            self.play_vid(url)
        elif 'servustvhd' in url:
            self.play_vid(url)
        elif 'videos-hl' in url:
            self.play_vid(url)
        else:
            #cj = CookieJar()
            #opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
            #opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0')]
            #req = opener.open('http://webproxy.at')
            #values = {'u': url}
            #data = urllib.urlencode(values)
            #response = opener.open('http://webproxy.at/surf/includes/process.php?action=update', data)
            #inhalt = response.read()
            #print inhalt
            #match = re.compile('(http://.+)', re.DOTALL).findall(inhalt)
            #if match:
           #     newurl = match[0].strip()
           #     newurl = newurl.replace('%25', '%')
# http://apasfiisl.apa.at/ipad/orfsx_q6a/orf.sdp/chunklist_w639970781.m3u8?ip=81.16.32.14&ua=Mozilla%2f5.0%2B%28Windows%2BNT%2B6.1%3b%2Brv%3a23.0%29%2BGecko%2f20100101%2BFirefox%2f23.0&lbs=20161231145434898&origin=http%3a%2f%2f185.85.29.1%3a1935%2fsystem_clips%2fgeoprotection_q4a.mp4%2fchunklist_w639970781.m3u8%3fip%3d81.16.32.14%26ua%3dMozilla%25252f5.0%252B%2528Windows%252BNT%252B6.1%25253b%252Brv%25253a23.0%2529%252BGecko%25252f20100101%252BFirefox%25252f23.0%26lbs%3d20161231145434898
            #    print newurl
            #    pattern='ip=.*?&'
            #    newurl=re.sub(pattern,'ip=77.119.130.255&',newurl)
            #    pattern1='%3fip%3d.*?%26'
            #    newurl=re.sub(pattern,'%3fip%3d77.119.130.255%26',newurl) 
            #    print newurl
#"Cookie":"ASP.NET_SessionId=t1obqwfd20kge445vcskpxzq","Host":"apasfiisl.apa.at","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36","X-Requested-With":"ShockwaveFlash/24.0.0.186"				
            #    vid_url = 'http://127.0.0.1:88/hls://' + newurl + ' headers={"X-Forwarded-For":"77.119.130.255","Cookie":"ASP.NET_SessionId=t1obqwfd20kge445vcskpxzq","Host":"apasfiisl.apa.at","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36","X-Requested-With":"ShockwaveFlash/24.0.0.186"}'
            #    self.play_vid(vid_url)
            #else:

            vid_url = 'http://127.0.0.1:88/hls://' + url #+ ' headers={"Referer":"","Origin":"http://www.freetvstream.in","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"}'
            self.play_vid(vid_url)

    def get_videos1(self, url):
        cj = CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0')]
        req = opener.open('http://webproxy.at')
        values = {'u': url}
        data = urllib.urlencode(values)
        response = opener.open('http://webproxy.at/surf/includes/process.php?action=update', data)
        inhalt = response.read()
        match = re.compile('(http://.+)', re.DOTALL).findall(inhalt)
        newurl = match[0].strip()
        self.play_vid(newurl)

    def list_media(self):
        self.info = 'media'
        self.media_list = []
        url = self['menulist'].getCurrent()[0][1]
        cj = CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0')]
        req = opener.open(url)
        res = req.read()
        media = re.findall('href="(.*?)"><figure class="item_image"><img data-src="(.*?)" alt=".*?" class="lazy" /></figure><header class="item_header clearfix"><h4 class="item_title">(.*?)</h4>', res)
        if media:
            for url, img, title in media:
                title = title.replace('&#039;', "'").replace('&amp; ', '')
                self.media_list.append(show_(title, url, img, None))

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

    def get_episodes(self):
        self.info = 'episodes'
        self.media_more_list = []
        url = self['menulist'].getCurrent()[0][1]
        cj = CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0')]
        req = opener.open(url)
        res = req.read()
        self.media_more_list.append(cat_('Aktuelle Sendung', url))
        more_media = re.findall('<a href="(.*?)" title=".*?" class="base_list_item_inner icon_align">.*?<span class="meta meta_date">(.*?)</span><span class="meta meta_time">(.*?)</span>.*?<span class="meta meta_duration">(.*?)</span>', res, re.DOTALL)
        print more_media
        if more_media:
            for url, prog_date, prog_time, duration in more_media:
                title = prog_date + ' ' + prog_time + ' ' + duration
                self.media_more_list.append(cat_(title, url))

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

    def get_link(self):
        print 'here in get_link'
        url = self['menulist'].getCurrent()[0][1]
        print url
        cj = CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0')]
        req = opener.open(url)
        res = req.read()
        link = re.findall('"quality":"Q6A","quality_string":"hoch","src":"(.*?)","type":"video.*?","delivery":"progressive","protocol":"http"', res)
        print link
        if link:
            link = link[0].replace('\\', '')
            self.play_vid(link)

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

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        if self.info == 'cat':
            idx = self['menulist'].l.getCurrentSelection()[0][3]
            if idx == '1':
                self.get_videos()
            elif idx == '2':
                self.list_media()
        elif self.info == 'media':
            self.get_episodes()
        elif self.info == 'episodes':
            self.get_link()

    def exit(self):
        print self.info
        if self.info == 'cat':
            self.close()
        elif self.info == 'episodes':
            self.close()
        elif self.info == 'player':
            self.info = 'cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()

    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'