# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/sonara.py
from imports import *
import sys
stdin, stdout = sys.stdin, sys.stdout
reload(sys)
sys.stdin, sys.stdout = stdin, stdout
sys.setdefaultencoding('utf-8')

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


class sonara(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['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('Sonara')
        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.show_cat)

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == '1':
            self.load_poster()

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == '1':
            self.load_poster()

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == '1':
            self.load_poster()

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == '1':
            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 show_cat(self):
        self.index = '0'
        self.cat_list = []
        self.cat_list.append(show_('\xd9\x85\xd8\xb3\xd9\x84\xd8\xb3\xd9\x84\xd8\xa7\xd8\xaa \xd8\xb1\xd9\x85\xd8\xb6\xd8\xa7\xd9\x86 2014', 'http://www.sonara.net/vncat/86/%D9%85%D8%B3%D9%84%D8%B3%D9%84%D8%A7%D8%AA_%D8%B1%D9%85%D8%B6%D8%A7%D9%86_2014', None))
        self.cat_list.append(show_('\xd9\x85\xd8\xb3\xd9\x84\xd8\xb3\xd9\x84\xd8\xa7\xd8\xaa \xd8\xb1\xd9\x85\xd8\xb6\xd8\xa7\xd9\x86 2013', 'http://www.sonara.net/videon-85.html', None))
        self.cat_list.append(show_('\xd9\x85\xd8\xb3\xd9\x84\xd8\xb3\xd9\x84\xd8\xa7\xd8\xaa \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9', 'http://www.sonara.net/vncat/49/%D9%85%D8%B3%D9%84%D8%B3%D9%84%D8%A7%D8%AA_%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9', None))
        self.cat_list.append(show_('\xd9\x83\xd8\xb1\xd8\xaa\xd9\x88\xd9\x86 ', 'http://www.sonara.net/vncat/53/%D9%83%D8%B1%D8%AA%D9%88%D9%86', None))
        self.cat_list.append(show_('\xd8\xa7\xd9\x81\xd9\x84\xd8\xa7\xd9\x85 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9', 'http://www.sonara.net/vcat/603/%D8%A7%D9%81%D9%84%D8%A7%D9%85_%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9', None))
        self.cat_list.append(show_('\xd8\xa7\xd9\x81\xd9\x84\xd8\xa7\xd9\x85 \xd8\xa7\xd8\xb3\xd9\x88\xd8\xaf \xd9\x88 \xd8\xa7\xd8\xa8\xd9\x8a\xd8\xb6', 'http://www.sonara.net/vcat/722/%D8%A7%D9%81%D9%84%D8%A7%D9%85_%D8%A7%D8%A8%D9%8A%D8%B6_%D9%88%D8%A7%D8%B3%D9%88%D8%AF', None))
        self.cat_list.append(show_('\xd8\xa8\xd8\xb1\xd8\xa7\xd9\x85\xd8\xac', 'http://www.sonara.net/vncat/52/%D8%A8%D8%B1%D8%A7%D9%85%D8%AC', None))
        self.cat_list.append(show_('\xd9\x85\xd8\xb3\xd9\x84\xd8\xb3\xd9\x84\xd8\xa7\xd8\xaa \xd8\xaa\xd8\xb1\xd9\x83\xd9\x8a\xd8\xa9', 'http://www.sonara.net/vncat/50/%D9%85%D8%B3%D9%84%D8%B3%D9%84%D8%A7%D8%AA_%D8%AA%D8%B1%D9%83%D9%8A%D8%A9', None))
        self.cat_list.append(show_('\xd8\xa7\xd9\x81\xd9\x84\xd8\xa7\xd9\x85 \xd8\xaa\xd8\xb1\xd9\x83\xd9\x8a\xd8\xa9', 'http://www.sonara.net/vcat/860/%D8%A7%D9%81%D9%84%D8%A7%D9%85_%D8%AA%D8%B1%D9%83%D9%8A%D8%A9', None))
        self.cat_list.append(show_('\xd9\x85\xd8\xb3\xd9\x84\xd8\xb3\xd9\x84\xd8\xa7\xd8\xaa-\xd8\xb1\xd9\x85\xd8\xb6\xd8\xa7\xd9\x86-2015', 'http://www.sonara.net/vncat/90/%D9%85%D8%B3%D9%84%D8%B3%D9%84%D8%A7%D8%AA-%D8%B1%D9%85%D8%B6%D8%A7%D9%86-2015', None))
        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        return

    def abc(self):
        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'
        url = 'http://tv1.sonara.net/'
        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.load_data_channels)

    def load_data_channels(self, data):
        self.index = '1'
        self.content_list = []
        print sys.getdefaultencoding()
        print data
        shows = re.findall("<div class='videocase'>.*?<a href='(.*?)'><img src='(.*?)'.*?<h4>(.*?)</h4>", data, re.DOTALL)
        if shows:
            for each in shows:
                url, img, title = each
                url = 'http://www.sonara.net' + url
                img = 'http://www.sonara.net' + img
                print title
                self.content_list.append(show_(title, url, img))

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

    def get_episodes(self, data):
        self.index = '2'
        print data
        self.episodes_list = []
        episodes = re.findall("<div class='videocase'>\n.*?<a href='/player/(.*?)/.*?'><img src='(.*?)'>\n.*?<h4>(.*?)</h4></a>", data, re.DOTALL)
        print episodes
        if episodes:
            for each in episodes:
                videoid, img, title = each
                url = 'http://www.sonara.net/video_player_new.php?ID=' + videoid
                img = 'http://www.sonara.net' + img
                print url, title
                self.episodes_list.append(show_(title, url, img))

            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()
        else:
            link = re.findall("<div class='right'><a id='iframe' href='(.*?)' title=", data, re.DOTALL)
            getPage(link[0], method='GET', headers={'Referer': 'http://www.sonara.net',
             '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_link)

    def get_link(self, data):
        self.index = '3'
        print data#'file','http://vod2.sonara.net/hd3/sham/sham_30a.mp4&image=http://images.sonara.net/575x327/20130626202712681501050.jpg');
        file = re.findall("'file','(.*?)&image=", data)
        if file:
            final_link = file[0]
            self.play_that_shit(final_link)

    def ok(self):
        print self.index
        if self.index == '0':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            print url
            getPage(url, method='GET', headers={'Referer': 'http://tv1.sonara.com',
             '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.load_data_channels)
        elif self.index == '1':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            print url
            getPage(url, method='GET', headers={'Referer': 'http://tv1.sonara.com',
             '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_episodes)
        elif self.index == '2':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            print url
            getPage(url, method='GET', headers={'Referer': 'http://tv1.sonara.com',
             '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_link)
        elif self.index == '3':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            title = self['menulist'].l.getCurrentSelection()[0][0]
            print url
            getPage(url, method='GET', headers={'Referer': 'http://tv1.sonara.com',
             '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_episodes)

    def exit(self):
        print self.index
        if self.index == '0':
            self.close()
        elif self.index == '1':
            self.index = '0'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.index == '2':
            self.index = '1'
            self['menulist'].l.setList(self.content_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.index == '3':
            self.index = '1'
            self['menulist'].l.setList(self.content_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def play_that_shit(self, data):
        sref = eServiceReference(4097, 0, data)
        self.session.open(MoviePlayer, sref)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/sonara_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/sonara/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 '[sonara] 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 '[sonara] no poster.. 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 '[sonara] 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/sonara/'):
            os.system('mkdir /tmp/sonara/')
        else:
            print '[sonara] /tmp/sonara/ allready present'