from setup import *
from about import *
from imports import *
fav_file='/usr/lib/enigma2/python/Plugins/Extensions/Albatros/fav'

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 burning(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,
         'green': self.addtofav,
         'blue': self.openfav,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Burning Series')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Add to FAV')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('OPEN FAV')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.get_bs_abc)
		
    def addtofav(self):
        title = self['menulist'].l.getCurrentSelection()[0][0]
        url = self['menulist'].l.getCurrentSelection()[0][1]
        f = open(fav_file,'a+')
        f.write('title:'+title+';url='+url+'end')
        f.close()     
	
    def openfav(self):
        with open(fav_file, "r") as ins:
            array = []
            for line in ins:
                array.append(line)
            print array
        self.index = 'list_series'
        self.series_list = []
        ser=re.findall('title:(.*?);url=(.*?)end',str(array))
        for title,url in ser:
            self.series_list.append(cat_(title, url))
        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.series_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.series_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_bs_abc(self):
        url = 'https://bs.to/serie-alphabet'
        getPage(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_series)

    def list_series(self, data):
        self.index = 'list_series'
        self.series_list = []
        series_block = re.findall('<div id="seriesContainer">(.*?)<script type="text/javascript">', data, re.DOTALL)
        series = re.findall('<li><a href="(.*?)" title=".*?">(.*?)</a></li>', series_block[0])
        for url, title in series:
            url = 'https://bs.to/' + url
            self.series_list.append(cat_(title, url))

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

    def ok(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print url
        if self.index == 'list_series':
            getPage(url, headers={'Cookie': '__ddg_=3990; ads=[1,1480865570789]; _ga=GA1.2.1131997825.1480785906',
             'Host': 'bs.to',
             'Referer': 'https://bs.to/andere-serien',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_staffel)
        if self.index == 'list_staffel':
            getPage(url, headers={'Host': 'bs.to',
             'Referer': 'https://bs.to/andere-serien',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_titles)
        if self.index == 'list_titles':
            getPage(url, headers={'Host': 'bs.to',
             'Referer': 'https://bs.to/andere-serien',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hosters)
        if self.index == 'list_hosters':
            getPage(url, headers={'Host': 'bs.to',
             'Referer': 'https://bs.to/andere-serien',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.resolve_link, url)

    def exit(self):
        print 'index : ' + self.index
        if self.index == 'list_series':
            self.close()
        elif self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'list_hosters'
            self['menulist'].l.setList(self.hosters_list)
            self['menulist'].l.setItemHeight(40)
        elif self.index == 'list_hosters':
            self.index = 'list_titles'
            self['menulist'].l.setList(self.titles_list)
            self['menulist'].l.setItemHeight(40)
        elif self.index == 'list_titles':
            self.index = 'list_staffel'
            self['menulist'].l.setList(self.staffel_list)
            self['menulist'].l.setItemHeight(40)
        elif self.index == 'list_staffel':
            self.index = 'list_series'
            self['menulist'].l.setList(self.series_list)
            self['menulist'].l.setItemHeight(40)

    def list_staffel(self, data):
        print data
        self.index = 'list_staffel'
        self.staffel_list = []
        staffel_block = re.findall('<strong>Staffeln</strong>(.*?)<table class="episodes">', data, re.DOTALL)
        staffel = re.findall('<li><a href="(serie/.*?)">(.*?)</a></li>', staffel_block[0])
        print staffel
        for url, title in staffel:
            url = 'https://bs.to/' + url
            self.staffel_list.append(cat_(title, url))

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

    def list_titles(self, data):
        self.index = 'list_titles'
        self.titles_list = []
        titles = re.findall('<td><a href="(serie/.*?)"', data, re.DOTALL)
        for url in titles:
            url = 'https://bs.to/' + url
            title = re.findall('/\\d+/\\d+-(.*[0-9a-z]+)', url, re.S | re.I)[0]
            self.titles_list.append(cat_(title, url))

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

    def list_hosters(self, data):
        self.index = 'list_hosters'
        self.hosters_list = []
        block = re.findall('<ul class="hoster-tabs top">(.*?)<ul class="hoster-tabs bottom">', data, re.DOTALL)
        hosters = re.findall('href="(.*?)">.*?<span class="icon (.*?)">', block[0], re.DOTALL)
        for url,title in hosters:
            url = 'https://bs.to/' + url
            if 'Vivo' in title:
                self.hosters_list.append(cat_(title, url))
            elif 'Streamcloud' in title:
                self.hosters_list.append(cat_(title, url))

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

    def resolve_link(self, data, url):
        link = re.findall('<a href="(https://bs.to/out/.*?)" target="_blank" class="hoster-player">', data)
        print 'this is the link : ' + link[0] + ' parsed to vivo'
        uri = link[0]
        print uri
        opener = urllib2.build_opener(NoRedirection)
        opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')]
        location = opener.open(uri).info().getheader('Location')
        print location
        req = urllib2.Request(location)
        req.add_header('User-Agent', 'stagefright')
        page = urllib2.urlopen(req)
        response = page.read()
        self.resolve_vivo(response,uri)

    def resolve_vivo(self, data, url):
        print data
        print url
        param=url.replace('https://vivo.sx/','')
        print param
        if param:
            self.get_vid_link(data)

    def get_vid_link(self, data):
        print data
        pattern=re.findall('Core\.InitializeStream \(\'(.*?)\'\);',data)
        if pattern:
            pattern=pattern[0]
            print pattern
            pattern=base64.b64decode(pattern)
            print pattern
            fin_url=re.findall('"(.*?)",',pattern)
            if fin_url:
                fin_url=fin_url[0].replace('\\','')
                self.play_channel(fin_url)

    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 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'
			
class NoRedirection(urllib2.HTTPErrorProcessor):
  def http_response(self, request, response):
    return response
  https_response = http_response