# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/okgoals.py
from imports import *

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 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=6, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class OKGoals(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,
         'yellow': self.about}, -1)
        self['menulist'] = m2list([])
        self['title'] = Label('OKGoals')
        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.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.count = 0
        self.loading = 0
        self.check = 'build_menu'
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        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 = [('England', 'http://www.okgoals.com/england.php'),
         ('Spain', 'http://www.okgoals.com/spain.php'),
         ('Spanien - La Liga', 'http://livefootballvideo.com/competitions/la-liga'),
         ('Italy', 'http://www.okgoals.com/italy.php'),
         ('Germany', 'http://www.okgoals.com/germany.php'),
         ('France', 'http://www.okgoals.com/france.php'),
         ('International', 'http://www.okgoals.com/international.php')]
        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 = []
#                             <div class="matchslisting"><a href="match-highlights-1463519974---40"><img style="border: none;" alt="England icon" src="images/en.png" /> &nbsp; &nbsp;2016.05.17 (20h00) - Manchester United	3-1	Bournemouth</a></div>
        matches = re.findall('<div id="matchlistng"><a href="(.*?)"><img style="border: none;" alt=".*?" src=".*?" />(.*?)</a></div>', data, re.DOTALL)
        print matches
        for each in matches:
            url, title = each
            title = title.replace(' &nbsp; &nbsp;', '')
            title = title.replace('\t', ' ')
            url = 'http://www.okgoals.com/' + url
            self.matches_list.append(cat_(title, 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 = []
        print data
#<div align="center" class="matchcontainer"><script data-config="//config.playwire.com/19850/videos/v2/5059211/zeus.json" data-height="333" data-width="600" src="//cdn.playwire.com/bolt/js/zeus/embed.js" type="text/javascript"></script></div>
        player_url = re.findall('<script data-config="//(.*?)"', data)
        print player_url
        if player_url:
            name = 'Playwire'
            url = 'http://' + player_url[0]
            print url
            self.url_list.append(cat_(name, url))
        else:#<div align="center" class="matchcontainer"><iframe frameborder="0" width="600" height="333" src="http://www.dailymotion.com/embed/video/x4ll2t8_fc-bayern-munchen-3-0-spvgg-landshut-hd-all-goals-full-highlights-friendly-23-07-2016_sport?syndication=117181"></iframe></div>
            player_url = re.findall('class="matchcontainer"><iframe frameborder="0" width="..." height="..." src="(.*?)"></iframe>', data)
            name = 'Dailymotion'
            url = player_url[0]
            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):
        print data
        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)
        else:
#"480":\[\{"type":"video\\\/mp4","url":"(.*?)"
            final_url = re.findall('"480":\[\{"type":"video\\\/mp4","url":"(.*?)"', data)
            if final_url:
                final_url = str(final_url[0]).replace('\\', '')
                print final_url
                self.play_highlights(final_url)

    def play_highlights(self, url):
        self.check = 'player'
        sref = eServiceReference(4097, 0, url)
        self.session.nav.playService(sref)
        self.hide()

    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'}).addCallback(self.get_player_url)#,
             #'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]
            if 'dailymotion' in url:
                getPage(url, method='GET', headers={'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)
            elif 'playwire' in url:
                content=geturl(url) #Page(url, method='GET', headers={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Encoding':'gzip, deflate, sdch','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)
                self.get_final_link(content)
    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)
        elif self.check == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.check = 'get_matches'
            self['menulist'].l.setList(self.matches_list)
            self['menulist'].l.setItemHeight(40)


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(OKGoals)