# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/watchgames.py
from setup import *
from imports import *
import urllib, urllib2, cookielib
cookie_file = '/tmp/cookies_teleboy'
cj = cookielib.LWPCookieJar(cookie_file)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0')]
opener.addheaders = [('X-Forwarded-For', '85.2.3.45')]
opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')]
api_key = 'f0e7bdfb822fa88c0c7a13f752a7e8d5c3757a13f757a13f9c0c7a13f7dfb822'

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_(name, link):
    res = [(name, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def show_(name, link, img):
    res = [(name, link, img)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class watchgames(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,
         'red': self.exit,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('watchgames.se')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        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.load_data_channels)

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

    def jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]
            self.get_play_link(self.filmname, link)

    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 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 load_data_channels(self):
        self.index = '1'
        self.letter_list = []
        self.channel_list = []
        url = 'http://watchgames.se/'
        try:
            resp = opener.open(url)
            channels = re.findall('<hr>(.*?) <font color="#5185C9"><b>Football</b></font> (.*?) <a href="(.*?)" target="_blank">.*?</a><br/>', resp.read())
            print channels
        except:
            print 'code changed again'

        for matchtime, title, url in channels:
            url = 'http://watchgames.se/' + url
            title = matchtime + ' :: ' + title
            self.channel_list.append(cat_(title, url))

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

    def ok(self):
        final_uri = self['menulist'].l.getCurrentSelection()[0][1]
        print final_uri
        self.get_file(final_uri)

    def get_file(self, url):
        opener.addheaders = [('referer', url)]
        resp = opener.open(url)
        np = re.findall('<iframe frameborder="0" marginheight="0" marginwidth="0" height="..." id="iframe" allowfullscreen="true" src="(.*?)" id="myfr" scrolling="no" width="', resp.read())
        print np
        if np:
            np = 'http://watchgames.se/' + np[0]
            self.get_file1(np)

    def get_file1(self, url):
        opener.addheaders = [('referer', url)]
        resp = opener.open(url)
        np = re.findall('src="(stream.*?)" id="myfr"', resp.read(), re.DOTALL)
        print np
        if np:
            np = 'http://watchgames.se/' + np[0]
            self.play_that_shit(np, url)

    def play_that_shit(self, data, url):
        opener.addheaders = [('referer', url)]
        resp = opener.open(data)
        file = re.findall("file: window\\.atob\\('(.*?)'\\),", resp.read())
        if file:
            file = base64.b64decode(file[0])
            file = 'http://127.0.0.1:88/httpstream://' + file + ' headers={"Accept":"*/*","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4","Connection":"keep-alive","Host":"154.57.145.182","Referer":"http://watchgames.se/streamplayer6.php","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36","X-Forwarded-For":"190.54.16.216","X-Requested-With":"ShockwaveFlash/20.0.0.306"}'
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, file)
            sref.setName(selectedName)
            self.session.open(MoviePlayer, sref)

    def exit(self):
        self.close()

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/teledunet_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 = '/tmp/'
        jpg_name = 'cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(jpg_store, 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 '[teledunet] 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 '[teledunet] no cover.. error'
        return

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

    def fetchHttp(self, url, args = {}, hdrs = {}, post = False):
        hdrs['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0'
        hdrs['X-Forwarded-For'] = '85.2.3.45'
        req = urllib2.Request(url, urllib.urlencode(args), hdrs)
        response = urllib2.urlopen(req)
        text = response.read()
        responsetext = text
        print responsetext
        response.close()
        return responsetext