# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/streaminghub.py
from setup import *
from about import *
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, 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 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


class streaminghub(Screen):

    def __init__(self, session):
        global old_ref
        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('StreamingHub.com')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        self.index = 'nothing'
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.get_first_page)

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

    def up(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.ch_list))
        print 'list : ' + str(comp)
        print self.cur_idx
        if self.cur_idx == 0:
            print 'moving to last idx'
            self['menulist'].moveToIndex(comp - 1)
        else:
            self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.ch_list))
        if self.cur_idx == comp - 1:
            self['menulist'].moveToIndex(0)
        else:
            self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

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

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

    def get_first_page(self):
        url = 'http://www.streaming-hub.com/category/live/'
        getPage(url, headers={'Host': 'www.streaming-hub.com',
         'Referer': 'http://www.streaming-hub.com/',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_pages)

    def get_pages(self, data):
        self.ch_list = []
        max_page_nr = re.findall("Next</a></li><li><a href='http://www.streaming-hub.com/category/live/page/(.*?)/'>Last</a></li></ul>", data)
        if max_page_nr:
            max_nr = int(max_page_nr[0]) + 1
            print max_nr
            i = 1
            for i in range(1, max_nr):
                url = 'http://www.streaming-hub.com/category/live/page/' + str(i) + '/'
                print url
                getPage(url, timeout=8, method='GET', headers={'Host': 'www.streaming-hub.com',
                 'Referer': 'http://www.streaming-hub.com/',
                 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_channels)
                i += 1
                url = 'http://www.streaming-hub.com/category/live/page/'

    def get_channels(self, data):
        channels = re.findall('<h6 class="layout-title"><a.*?href="(.*?)" title="(.*?)">.*?</a></h6>', data, re.DOTALL)
        print channels
        for url, title in channels:
            self.ch_list.append(show_(title, url, None))

        self['menulist'].l.setList(self.ch_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def ok(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print url
        getPage(url, timeout=8, method='GET', headers={'Referer': 'http://www.streaming-hub.com/category/live/',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}).addCallback(self.get_hls_link)

    def get_hls_link(self, data):
        link = re.findall('source: "(.*?)"', data)
        link1 = re.findall('src: "(.*?)",', data)
        if link:
            if 'm3u8' in str(link):
                self.play_channel(link[0])
        elif link1:
            if 'm3u8' or 'rtmp' in str(link1):
                self.play_channel(link1[0])

    def get_hls_link2(self, data):
        print data
        ln = re.findall("window\\.flashvars.src='(.*?)';", data)
        if ln:
            self.play_channel(ln[0])

    def play_channel(self, data):
        self.index = 'player'
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.nav.playService(sref)
        self.hide()

    def exit(self):
        if self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'list_hosters'
            self['menulist'].l.setList(self.ch_list)
            self['menulist'].l.setItemHeight(40)
        else:
            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: no 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(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 '[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/ exists'