# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/veetle.py
from imports import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
from VirtualKeyBoard import VirtualKeyBoard

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 Veetle(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,
         'cancel': self.exit,
         'red': self.exit,
         'green': self.search}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Search')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label(' ')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('veetle.com')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = -1
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.abc)

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie':
            self.show_cover()

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie':
            self.show_cover()

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie':
            self.show_cover()

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie':
            self.show_cover()

    def abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_list = []
        self.letter_movielist = []
        self.genre_name = 'Veetle Streams'
        cat = [('Animation', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/60/0/39/0'),
         ('Comedy', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/50/0/39/0'),
         ('Education', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/90/0/39/0'),
         ('Gaming', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/40/0/39/0'),
         ('Mobile', 'http://veetle.com/index.php/stream/ajaxStreamBySearch/0/39/0/2.0/'),
         ('Entertainment', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/10/0/39/0'),
         ('Shows', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/20/0/39/0'),
         ('Sports', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/80/0/39/0'),
         ('Music', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/70/0/39/0'),
         ('News', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/30/0/39/0'),
         ('Religion', 'http://veetle.com/index.php/listing/ajaxStreamByCategory/100/0/39/0')]
        for each in cat:
            category, link = each
            self.letter_list.append(cat_(category, link))

        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        genre_link = self['menulist'].getCurrent()[0][1]
        self.count = 0

    def search(self):
        self.session.openWithCallback(self.searchVeetle, VirtualKeyBoard, title=_('Enter name of the Channel'))

    def searchVeetle(self, searchstring = None):
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            print searchstring_fin
            url = 'http://veetle.com/index.php/stream/ajaxStreamBySearch/0/39/0/2.0/' + searchstring_fin
            getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        movies = re.findall('{"userId":".*?username":".*?","channelId":"(.*?)",".*?","thumbnailUrl":"(.*?)","thumbnailUrlSmall":".*?title":"(.*?)","description":".*?"', data, re.DOTALL)
        for each in movies:
            url, thumb, title = each
            url = 'http://veetle.com/index.php/stream/ajaxStreamLocation/' + url + '/flash'
            thumb = str(thumb).replace('\\', '')
            title = str(title).replace('\\u25ba', '').replace('\\u25c4', '').replace('\\u25c4', '').replace('\\u1d0f', '').replace('\\u026a', '').replace('\\u0274', '').replace('\\u1d1cs', '').replace('\\u1d0f', '').replace('\\u0280', '').replace('\\u1d07', '').replace('\\u1d21', '').replace('\\u2134', '').replace('\\u0475', '').replace('\\u212f', '').replace('\\u25ac', '')
            title = str(title).replace('\\u029f', '').replace('\\u1d00', '').replace('\\u028f', '').replace('\\u026as', '').replace('\\u1d1bs', '').replace('\\u1d05', '').replace('\\u2666', '').replace('\\u00a8', '').replace('\\u25b2', '').replace('\\u2665', '').replace('\\u2022', '').replace('\\u2112', '').replace('\\u266a', '').replace('\\u2588', '').replace('\\u2580', '')
            title = str(title).replace('\\u00bb', '').replace('\\u00ab', '').replace('\\u000c', '').replace('\\u00a0', '').replace('\\u2460', '').replace('\\u2122', '').replace('\\u00b4', '').replace('\\u2606', '')
            self.search_list.append(show_(title, url, thumb))

        self['menulist'].l.setList(self.search_list)
        self['menulist'].l.setItemHeight(40)

    def start(self, main_url, count):
        getPage(main_url, timeout=8, method='GET', headers={'Host': 'veetle.com',
         'Referer': 'http://veetle.com/index.php/listing/index/entertainment',
         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
         'X-Prototype-Version': '1.7',
         'X-Requested-With': 'XMLHttpRequest'}).addCallback(self.load_data, main_url)

    def load_data(self, data, main_url):
        self.check = 'letter_movie'
        movies = re.findall('\\{"userId":".*?","username":".*?","channelId":"(.*?)","sessionId":".*?","thumbnailUrl":"(.*?)","thumbnailUrlSmall":".*?","title":"(.*?)","description":".*?","location"', data, re.DOTALL)
        for each in movies:
            url, thumb, title = each
            url = 'http://veetle.com/index.php/stream/ajaxStreamLocation/' + url + '/flash'
            thumb = str(thumb).replace('\\', '')
            title = str(title).replace('\\u25ba', '').replace('\\u25c4', '').replace('\\u25c4', '').replace('\\u1d0f', '').replace('\\u026a', '').replace('\\u0274', '').replace('\\u1d1cs', '').replace('\\u1d0f', '').replace('\\u0280', '').replace('\\u1d07', '').replace('\\u1d21', '').replace('\\u2134', '').replace('\\u0475', '').replace('\\u212f', '').replace('\\u25ac', '')
            title = str(title).replace('\\u029f', '').replace('\\u1d00', '').replace('\\u028f', '').replace('\\u026as', '').replace('\\u1d1bs', '').replace('\\u1d05', '').replace('\\u2666', '').replace('\\u00a8', '').replace('\\u25b2', '').replace('\\u2665', '').replace('\\u2022', '').replace('\\u2112', '').replace('\\u266a', '').replace('\\u2588', '').replace('\\u2580', '')
            title = str(title).replace('\\u00bb', '').replace('\\u00ab', '').replace('\\u000c', '').replace('\\u00a0', '').replace('\\u2460', '').replace('\\u2122', '').replace('\\u00b4', '').replace('\\u2606', '')
            title = str(title).replace('(((\\u246)))', '').replace('\\u25cf', ' ').replace('\\u06e9', '').replace('\\u06de', '').replace('\\u2605', '').replace('\\u008c', '').replace('\\u2461', '').replace('\\u2462', '').replace('\\u2263', '').replace('\\u0262', '').replace('\\u0493', '').replace('\\u1d1c.', '').replace('\\u041d', '').replace('\\u0435', '').replace('\\u0442', '').replace('\\u0432', '').replace('\\u2462', '').replace('\\u00f3', '').replace('\\u00e0', '')
            self.letter_movielist.append(show_(title, url, thumb))

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

    def get_play_link(self, name, url):
        uri = 'http://veetle.com/index.php/channel/view'
        req = urllib2.Request(uri)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        cookie = page.info()['Set-Cookie']
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        req.add_header('Referer', 'http://veetle.com/index.php/search/video/')
        req.add_header('Cookie', cookie)
        page = urllib2.urlopen(req)
        response = page.read()
        self.read_link(response)

    def read_link(self, data):
        link = re.findall('{"success":true,"payload":"(.*?)","', data)
        print data
        playp = str(link[0]).replace('\\', '')
        print playp
        if link:
            self.play_movie(playp)

    def play_movie(self, link):
        if link:
            sref = eServiceReference(4097, 0, link)
            sref.setName(self.filmname)
            self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.check == 'abc':
            self.index_nr = self['menulist'].getSelectedIndex()
            self.genre_name = self['menulist'].getCurrent()[0][0]
            genre_link = self['menulist'].getCurrent()[0][1]
            self.start(genre_link, -1)
        elif self.check == 'letter_movie':
            self.filmname = self['menulist'].getCurrent()[0][0]
            link = self['menulist'].getCurrent()[0][1]
            self.dnfile = 'False'
            self.get_play_link(self.filmname, link)

    def exit(self):
        os.system('rm -rf /tmp/Veetle')
        self.close()

    def show_cover(self):
        jpg_link = self['menulist'].getCurrent()[0][2]
        jpg_name = self['menulist'].getCurrent()[0][0]
        jpg_store = '/tmp/Veetle/%s' % jpg_name
        if not os.path.exists(jpg_store):
            downloadPage(jpg_link, jpg_store).addCallback(self.downloadPic, 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 '[Veetle] thumb 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 '[Veetle] no thumb.. error'
        return

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