# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/telewizjada.py
from setup import *
from imports import *
import urllib2
from xml.etree import ElementTree
import json
import threading
import time
import os
import httplib
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36')]
opener.addheaders = [('X-Requested-With', 'XMLHttpRequest')]
HOST = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20121213 Firefox/19.0'

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, 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


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


class telewizjada(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('WSS-SPORT')
        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.stream_list = []
        self.onLayoutFinish.append(self.abc)

    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()
        self.load_poster()

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

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

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

    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 abc(self):
        self.ch_list = []
        self.index = 'channels'
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'Al Cinema'
        try:
            url = 'http://www.telewizjada.net/'
            uri = 'http://www.telewizjada.net/get_channels.php'
            opener.open(url)
            res = opener.open(uri)
            ans = res.read()
            print ans
        except:
            print 'shit'
            ans = 'no data'

        print cj              #"id":1,"displayName":"TVP 1","thumb":"\/media\/stream\/img\/tvp1.png","online":1,"isAdult":0
        channels = re.findall('"id":(.*?),"displayName":"(.*?)","thumb":"(.*?)"', ans, re.DOTALL)
        print channels
        for id, title, img in channels:
            url = url.replace('\\', '')
            img = 'http://www.telewizjada.net' + img.replace('\\', '')
            self.ch_list.append(show3_(title, None, img, id))

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

    def show_streams(self):
        uri = self['menulist'].l.getCurrentSelection()[0][1]
        id = self['menulist'].l.getCurrentSelection()[0][3]
        sth = Something()
        coockie = 'coockie.coock'
        data = {'cid': id}
        output = sth.getJsonFromExtendedAPI('http://www.telewizjada.net/get_mainchannel.php', post_data=data, jsonLoadsResult=True)
        data = {'url': output['url']}
        sth.getJsonFromExtendedAPI('http://www.telewizjada.net/set_cookie.php', post_data=data, cookieFile=coockie, save_cookie=True)
        data = {'cid': id}
        tmp_url = sth.getJsonFromExtendedAPI('http://www.telewizjada.net/get_channel_url.php', post_data=data, cookieFile=coockie, load_cookie=True, jsonLoadsResult=True)
        tmp_url = tmp_url['url']
        msec = sth.getCookieItem(coockie, 'msec')
        sessid = sth.getCookieItem(coockie, 'sessid')
        print 'Url: ' + tmp_url.split('?')[0]
        print 'msec: ' + msec
        print 'sessid: ' + sessid
        fin_uri = 'http://127.0.0.1:88/hlsvariant://' + str(tmp_url.split('?')[0]) + ' headers={"Cookie":"msec=' + str(msec) + '; sessid=' + str(sessid) + ';","Referer":"http://www.telewizjada.net/live.php?cid=2","X-Requested-With":"ShockwaveFlash/20.0.0.267"}'
        self.play_that_shit(fin_uri)

    def ok(self):
        if self.index == 'channels':
            self.show_streams()

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

    def exit(self):
        print self.index
        if self.index == 'channels':
            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 = '/usr/lib/enigma2/python/Plugins/Extensions/teledunet/images/'
        jpg_name = 'no_cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(jpg_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 '[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 stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found, try again later on'), MessageBox.TYPE_INFO, timeout=3)

    def errorload2(self, error):
        print '[teledunet] error %s' % error
        count_movies = len(self.letter_movielist)
        self.loading_ok = True
        self.loading = 0
        self.count = 0

    def errorload(self, error):
        print error

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


class Something:

    def logCall(self, message):
        print self.__class__.__name__ + ' ' + message

    def getJsonFromExtendedAPI(self, url, post_data = None, save_cookie = False, load_cookie = False, cookieFile = None, jsonLoadsResult = False):
        result_json = None
        customOpeners = []
        cj = cookielib.LWPCookieJar()

        def urlOpen(req, customOpeners):
            if len(customOpeners) > 0:
                opener = urllib2.build_opener(*customOpeners)
                response = opener.open(req, timeout=4)
            else:
                response = urllib2.urlopen(req, timeout=4)
            return response

        try:
            if cookieFile is not None:
                customOpeners.append(urllib2.HTTPCookieProcessor(cj))
                if load_cookie == True:
                    cj.load(cookieFile, ignore_discard=True)
            headers = {'User-Agent': HOST}
            data = urllib.urlencode(post_data)
            reqUrl = urllib2.Request(url, data, headers)
            failedCounter = 0
            while failedCounter < 50:
                try:
                    raw_json = urlOpen(reqUrl, customOpeners)
                    result_json = raw_json.read()
                    if jsonLoadsResult == True:
                        result_json = json.loads(result_json)
                    break
                except (httplib.IncompleteRead, socket.timeout) as ex:
                    failedCounter = failedCounter + 1
                    self.logCall('getJsonFromExtendedAPI exception: %s - retrying failedCounter = %s' % (str(ex), failedCounter))
                    if xbmc.abortRequested:
                        break
                    time.sleep(0.05)

            if cookieFile is not None and save_cookie == True:
                cj.save(cookieFile, ignore_discard=True)
        except (urllib2.URLError,
         NameError,
         ValueError,
         httplib.BadStatusLine) as ex:
            self.logCall('ShowList getJsonFromExtendedAPI exception: %s - aborting!' % str(ex))
            return

        return result_json

    def getCookieItem(self, cookiefile, item):
        ret = ''
        if os.path.isfile(cookiefile):
            cj = cookielib.LWPCookieJar()
            cj.load(cookiefile, ignore_discard=True)
            for cookie in cj:
                if cookie.name == item:
                    ret = cookie.value

        return ret