# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/livefootballvideo.py
from imports import *
from Tools.Directories import fileExists, pathExists

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

    def __init__(self, session):
        path = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/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['title'] = Label('livefootballvideo.com')
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.count = 0
        self.loading = 0
        self.check = 'build_menu'
        self.onLayoutFinish.append(self.build_menu)

    def up(self):
        self[self.currentList].up()

    def down(self):
        self[self.currentList].down()

    def left(self):
        self[self.currentList].pageUp()

    def right(self):
        self[self.currentList].pageDown()

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

    def build_menu(self):
        self.cat_list = []
        category = [('Deutschland - 1.Bundesliga', 'http://livefootballvideo.com/competitions/bundesliga'),
         ('England - PREMIER LEAGUE', 'http://livefootballvideo.com/competitions/premier-league'),
         ('Spanien - La Liga', 'http://livefootballvideo.com/competitions/la-liga'),
         ('Italien - Serie A', 'http://livefootballvideo.com/competitions/serie-a'),
         ('Frankreich - Ligue 1', 'http://livefootballvideo.com/competitions/ligue-1'),
         ('Portugal - PRIMEIRA LIGA', 'http://livefootballvideo.com/competitions/primeira-liga'),
         ('UEFA CHAMPIONS LEAGUE', 'http://livefootballvideo.com/competitions/uefa-champions-league')]
        for each in category:
            name, url = each
            self.cat_list.append(cat_(name, url))

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

    def get_matches(self, data):
        self.check = 'get_matches'
        self.matches_list = []
        matches = re.findall('<span class="starttime shortdate" rel=".*?">(.*?)</span>.*?<a href="(.*?)" class="score">(.*?)</a></div>\n<div class="team column">', data, re.DOTALL)
        print matches
        for each in matches:
            date, url, score = each
            if 'http://livefootballvideo.com/highlights/germany/bundesliga/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/germany/bundesliga/', '')
            elif 'http://livefootballvideo.com/highlights/england/premier-league/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/england/premier-league/', '')
            elif 'http://livefootballvideo.com/highlights/spain/la-liga/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/spain/la-liga/', '')
            elif 'http://livefootballvideo.com/highlights/italy/serie-a/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/italy/serie-a/', '')
            elif 'http://livefootballvideo.com/highlights/france/ligue-1/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/france/ligue-1/', '')
            elif 'http://livefootballvideo.com/highlights/netherlands/eredivisie/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/netherlands/eredivisie/', '')
            elif 'http://livefootballvideo.com/highlights/portugal/primeira-liga/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/portugal/primeira-liga/', '')
            elif 'http://livefootballvideo.com/highlights/europe/uefa-europa-league/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/europe/uefa-europa-league/', '')
            elif 'http://livefootballvideo.com/highlights/europe/uefa-champions-league/' in url:
                title = str(url).replace('http://livefootballvideo.com/highlights/europe/uefa-champions-league/', '')
            name = date + ': ' + title + ': ' + score
            self.matches_list.append(cat_(name, url))

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

    def get_player_url(self, data):
        self.check = 'get_player_url'
        self.url_list = []
        player_url = re.findall('src="//cdn.playwire.com/bolt/js/.*?" data-width="..." data-height="..." data-publisher-id="....." data-video-id="......." data-config="(.*?)"></script></center>', data)
        if player_url:
            name = 'Playwire'
            url = player_url[0]
            print url
            self.url_list.append(cat_(name, url))
        self['menulist'].l.setList(self.url_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    def get_final_link(self, data):
        final_url = re.findall('stream_h264_hq_url":"(.*?)","', data)
        if final_url:
            final_url = str(final_url[0]).replace('\\', '')
            print final_url
            self.play_highlights(final_url)
        else:
            final_url = re.findall('"src":"(.*?)"', data)
            print final_url
            if final_url:
                link_to_file = geturl(final_url[0])
                param = re.findall('<baseURL>(.*?)</baseURL>', link_to_file)
                param1 = re.findall('<media url="(.*?)" bitrate', link_to_file)
                player_url = param[0] + '/' + param1[0]
                self.play_highlights(player_url)
            else:
                final_url = re.findall('"f4m":"(.*?)"', data)
                if final_url:
                    link_to_file = geturl(final_url[0])
                    param = re.findall('<baseURL>(.*?)</baseURL>', link_to_file)
                    param1 = re.findall('<media url="(.*?)" bitrate', link_to_file)
                    player_url = param[0] + '/' + param1[0]
                    self.play_highlights(player_url)

    def play_highlights(self, url):
        sref = eServiceReference(4097, 0, url)
        self.session.open(MoviePlayer, sref)

    def ok(self):
        print self.check
        if self.check == 'build_menu':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            getPage(url, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded',
             'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.get_matches)
        elif self.check == 'get_matches':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            print url
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            getPage(url, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded',
             'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13',
             'Referer': 'http://livefootballvideo.com/',
             'Host': 'livefootballvideo.com'}).addCallback(self.get_player_url)
        elif self.check == 'get_player_url':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            print url
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            getPage(url, method='GET', headers={'Referer': 'http://livefootballvideo.com/highlights/',
             'Content-Type': 'application/x-www-form-urlencoded',
             'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.get_final_link)

    def exit(self):
        print self.check
        if self.check == 'build_menu':
            self.close()
        elif self.check == 'get_matches':
            self.check = 'build_menu'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.check == 'get_player_url':
            self.check = 'get_matches'
            self['menulist'].l.setList(self.matches_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)


def geturl(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    response = urllib2.urlopen(req)
    link = response.read()
    return link


def getURL(page_url, premium = False, user = '', password = '', video_password = ''):
    print "[vk.py] getURL(page_url='%s')" % page_url
    data = geturl(page_url.replace('amp;', ''))
    videourl = ''
    regexp = re.compile('vkid=([^\\&]+)\\&')
    match = regexp.search(data)
    vkid = ''
    if match is not None:
        vkid = match.group(1)
    else:
        print 'no vkid'
    patron = "var video_host = '([^']+)'.*?"
    patron += "var video_uid = '([^']+)'.*?"
    patron += "var video_vtag = '([^']+)'.*?"
    patron += 'var video_no_flv = ([^;]+);.*?'
    patron += "var video_max_hd = '([^']+)'"
    matches = re.compile(patron, re.DOTALL).findall(data)
    video_urls = []
    if len(matches) > 0:
        for match in matches:
            if match[3].strip() == '0' and match[1] != '0':
                tipo = 'flv'
                if 'http://' in match[0]:
                    videourl = '%s/u%s/video/%s.%s' % (match[0],
                     match[1],
                     match[2],
                     tipo)
                else:
                    videourl = 'http://%s/u%s/video/%s.%s' % (match[0],
                     match[1],
                     match[2],
                     tipo)
                video_urls.append(['FLV [vk]', videourl])
            elif match[1] == '0' and vkid != '':
                tipo = 'flv'
                if 'http://' in match[0]:
                    videourl = '%s/assets/videos/%s%s.vk.%s' % (match[0],
                     match[2],
                     vkid,
                     tipo)
                else:
                    videourl = 'http://%s/assets/videos/%s%s.vk.%s' % (match[0],
                     match[2],
                     vkid,
                     tipo)
                video_urls.append(['FLV [vk]', videourl])
            else:
                quality = '1'
                if match[4] == '0':
                    video_urls.append(['240p [vk]', get_mp4_video_link(match[0], match[1], match[2], '240.mp4')])
                    print get_mp4_video_link(match[0], match[1], match[2], '240.mp4')
                    v_url = get_mp4_video_link(match[0], match[1], match[2], '240.mp4')
                elif match[4] == '1':
                    video_urls.append(['240p [vk]', get_mp4_video_link(match[0], match[1], match[2], '240.mp4')])
                    video_urls.append(['360p [vk]', get_mp4_video_link(match[0], match[1], match[2], '360.mp4')])
                    print get_mp4_video_link(match[0], match[1], match[2], '360.mp4')
                    v_url = get_mp4_video_link(match[0], match[1], match[2], '360.mp4')
                elif match[4] == '2':
                    video_urls.append(['240p [vk]', get_mp4_video_link(match[0], match[1], match[2], '240.mp4')])
                    video_urls.append(['360p [vk]', get_mp4_video_link(match[0], match[1], match[2], '360.mp4')])
                    video_urls.append(['480p [vk]', get_mp4_video_link(match[0], match[1], match[2], '480.mp4')])
                    print get_mp4_video_link(match[0], match[1], match[2], '480.mp4')
                    v_url = get_mp4_video_link(match[0], match[1], match[2], '480.mp4')
                elif match[4] == '3':
                    video_urls.append(['240p [vk]', get_mp4_video_link(match[0], match[1], match[2], '240.mp4')])
                    video_urls.append(['360p [vk]', get_mp4_video_link(match[0], match[1], match[2], '360.mp4')])
                    video_urls.append(['480p [vk]', get_mp4_video_link(match[0], match[1], match[2], '480.mp4')])
                    video_urls.append(['720p [vk]', get_mp4_video_link(match[0], match[1], match[2], '720.mp4')])
                    print get_mp4_video_link(match[0], match[1], match[2], '720.mp4')
                    print match[0]
                    print match[1]
                    print match[2]
                    v_url = get_mp4_video_link(match[0], match[1], match[2], '720.mp4')
                else:
                    video_urls.append(['240p [vk]', get_mp4_video_link(match[0], match[1], match[2], '240.mp4')])
                    video_urls.append(['360p [vk]', get_mp4_video_link(match[0], match[1], match[2], '360.mp4')])
                    print get_mp4_video_link(match[0], match[1], match[2], '360.mp4')
                    v_url = get_mp4_video_link(match[0], match[1], match[2], '360.mp4')

    result = video_urls[len(video_urls) - 1]
    return v_url


def get_mp4_video_link(match0, match1, match2, tipo):
    if match0.endswith('/'):
        videourl = '%su%s/videos/%s.%s' % (match0,
         match1,
         match2,
         tipo)
    else:
        videourl = '%s/u%s/videos/%s.%s' % (match0,
         match1,
         match2,
         tipo)
    return videourl


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