 # -*- coding: utf-8 -*-
from setup import *
from imports import *
from StringIO import StringIO
import gzip
from enigma import eTimer
cj={}

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,info):
    res = [(name, link, img,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_(name, link,url):
    res = [(name, link, url)]
    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 streamoase(Screen):

    def __init__(self, session):
        sz_w = getDesktop(0).size().width()
        if sz_w == 1920:
            path = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen_new.xml'
        else:
            path = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/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.search,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Stream-Oase.tv')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(_('Search'))
        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.letter_list = []
        self.search_list = []
        self.vid_list=[]
        self.dir()
        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()
        auswahl = self['menulist'].getCurrent()[0][0]
        info = self['menulist'].getCurrent()[0][3]
        self['name'].setText(auswahl)
        self['text'].setText(info)

    def down(self):
        self[self.currentList].down()
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        info = self['menulist'].getCurrent()[0][3]
        self['name'].setText(auswahl)
        self['text'].setText(info)

    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.index = '1'
        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'
        #uri='http://stream-oase.tv/titles/paginate?_token=nN5mGex8KD8EMnIhKRJu72vLn6Y1MrlSlvTwefC4&perPage=18&page=1&order=mc_num_of_votesDesc&genres%5B%5D=action&type=movie&minRating=&maxRating=&availToStream=true'
        #uri = 'http://stream-oase.tv/titles/paginate?_token=7uifJkc3c3o2V4tYU1hhwsRspSbyhqv0KDrXoZ3A&perPage=300&page=1&order=mc_num_of_votesDesc&type=movie&minRating=&maxRating=&availToStream=true'
        #getPage(uri, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}).addCallback(self.load_data_channels)
        self.load_data_channels('too slow')

    def load_data_channels(self, data):
        self.index='load_data_channels'
        #import json
        #j = json.loads(data)
        #js = json.loads(data)
        #parent =  j["items"]
        #print parent
        #for item in parent:
        #    title=str(item["title"])
        #    print title
        #    url=str(item["link"])
        #    url= re.findall('u\'url\': u\'(.*?)\'',url)
        #    print url
        #    url=url[0]
        #    info=str(item["plot"])
        #    print info
        #    img=str(item["poster"])
        #    print img
        self.letter_list.append(show_('Use search buttom', 'http://', None,None))
        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        #self.load_poster()
        #auswahl = self['menulist'].getCurrent()[0][0]
        #info = self['menulist'].getCurrent()[0][3]
        #self['name'].setText(auswahl)
        #self['text'].setText(info)
		
    def get_episodes(self,data):
        print data
        self.index='2'
        self.episodes_list=[]
        episodes=re.findall('<td style="float:left;text-align:left;margin-left:..px; "width=".*?"><a href="(.*?)">(.*?)</a></td>.*?<td width=".*?"><a href=".*?"><img src="(.*?)" /></a></td>',data,re.DOTALL)
        for each in episodes:
            url,title,img=each
            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()
        return

    def search(self):
        self.index='search'
        self.session.openWithCallback(self.search_streamoase, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_streamoase(self, searchstring = None):
        self.index='search'
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://stream-oase.tv/search?q=' + searchstring_fin
            getPage(url, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.index='search_data'
        block=re.findall('<h2>Movies</h2>(.*?)<h2>Series</h2>',data,re.DOTALL)
        search = re.findall('<a href="(.*?)"><img class ="img-responsive" src="(.*?)" alt="(.*?)"></a>',block[0])
        print search
        if search:
            for each in search:
                url, img, title = each
                print title
                self.search_list.append(show_(title, url, img,None))
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    def list_streams(self, data):
        self.index='list_streams'
        urls=re.findall('<td class="name hover" data-bind="click: playVideo\.bind\(\$data, \'(.*?)\', \'embed\'\)"><img data-bind="attr: \{src: app\.utils\.getFavicon\(\'(.*?)\'\)\}">(.*?)</td>.*?<td>(.*?)</td>',data,re.DOTALL)
        print urls
        if urls:
            for each in urls:
                vidurl,img,title,title_add = each
                title=title+' '+title_add
                print title
                if 'openload' in vidurl:
                    self.vid_list.append(show_(title, vidurl, img, None))
            self['menulist'].l.setList(self.vid_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    def get_hls(self, url):
        print url
        new_url='https://api.openload.io/1/file/dlticket?file=%s' %url
        print new_url
        getPage(new_url, timeout=8, method='GET', headers={'Referer':'http://stream-oase.tv/movies/39-the-dark-knight','User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}).addCallback(self.get_hls_2,url)
		 
    def get_hls_2(self, data,url):
        print 'get_hls_2'
        print data
        self.data_list=[]
        ticket=re.findall('"ticket":"(.*?)"',data)[0]
        if '.mp4' in ticket:
            ticket=ticket.replace('\\','')
            self.play_that_shit(ticket)
        else:
            capture_url=re.findall('"captcha_url":"(.*?)"',data)
            self.data_list.append(ticket)
            self.data_list.append(url)
            print self.data_list
            print capture_url
            if capture_url:
                capture_url=capture_url[0].replace('\\\\','').replace('\\','')
                print capture_url
                self.load_capture(capture_url)
                self.show_cover()
                self.Timer = eTimer()
                self.Timer.callback.append(self.startkeyboard)
                self.Timer.start(1000*5, 1)
            else: #https:\/\/openload.co\/embed\/bQod3qq2GgQ\/~~1451574183~n~~0~mEGVx2OEszqWRrXj
                ticket=ticket.replace('\\','')
                getPage(ticket, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.decode_data)

    def decode_data(self,data):
        print data
        aastring = re.search(r"<video(?:.|\s)*?<script\s[^>]*?>((?:.|\s)*?)</script", data, re.DOTALL | re.IGNORECASE).group(1)
        print aastring
        if aastring:
            aastring = aastring.replace("((ﾟｰﾟ) + (ﾟｰﾟ) + (ﾟΘﾟ))", "9")
            aastring = aastring.replace("((ﾟｰﾟ) + (ﾟｰﾟ))","8")
            aastring = aastring.replace("((ﾟｰﾟ) + (o^_^o))","7")
            aastring = aastring.replace("((o^_^o) +(o^_^o))","6")
            aastring = aastring.replace("((ﾟｰﾟ) + (ﾟΘﾟ))","5")
            aastring = aastring.replace("(ﾟｰﾟ)","4")
            aastring = aastring.replace("((o^_^o) - (ﾟΘﾟ))","2")
            aastring = aastring.replace("(o^_^o)","3")
            aastring = aastring.replace("(ﾟΘﾟ)","1")
            aastring = aastring.replace("(c^_^o)","0")
            aastring = aastring.replace("(ﾟДﾟ)[ﾟεﾟ]","\\")
            aastring = aastring.replace("(3 +3 +0)","6")
            aastring = aastring.replace("(3 - 1 +0)","2")
            aastring = aastring.replace("(1 -0)","1")
            aastring = aastring.replace("(4 -0)","4")
            
            print">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> \n %s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" % aastring

            decodestring = re.search(r"\\\+([^(]+)", aastring, re.DOTALL | re.IGNORECASE).group(1)
            decodestring = "\\+"+ decodestring
            decodestring = decodestring.replace("+","")
            decodestring = decodestring.replace(" ","")
            
            decodestring = self.decode(decodestring)
            decodestring = decodestring.replace("\\/","/")
            print">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> \n %s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" % decodestring 
            fl=re.findall('vr ="(.*?)"',decodestring)
            if fl:
                print fl[0]
                fl=fl[0].replace('https://', 'http://')
                req = urllib2.Request(fl)
                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)
                ln=page.geturl()
                if ln:
                    self.play_that_shit(ln)			

    def decode(self,encoded):
        for octc in (c for c in re.findall(r'\\(\d{2,3})', encoded)):
            encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
        return encoded.decode('utf8')			
			
    def startkeyboard(self):
            self.session.openWithCallback(self.puzzle, VirtualKeyBoard, title=_('Solve the puzzle'))


    def puzzle(self,puzzlestring = None ):
        if puzzlestring:
            url=self.data_list[1]
            ticket=self.data_list[0]
            puzzlestring_fin = puzzlestring.replace(' ', '+')
            url = 'https://api.openload.io/1/file/dl?file=%s&ticket=%s' % (url, ticket)
            uri = url+'&captcha_response=%s' % urllib.quote(puzzlestring_fin)
            print uri
            getPage(uri, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.puzzle_data) 


    def puzzle_data(self,data):
        print data
        video_url=re.findall('"url":"(.*?)"',data)		
        if video_url:
            print video_url
            video_url=video_url[0].replace('\\','')
            video_url=video_url+'?mime=true'
            self.play_that_shit(video_url)
        else:
            print 'shit - nice try'
		 
    def ok(self):
        print self.index
        #if self.index == '1':
        #    uri = self['menulist'].l.getCurrentSelection()[0][1]
        #    getPage(uri, timeout=8, method='GET',cookies=cj, headers={'Host':'www.stream-oase.tv','Referer':'http://www.stream-oase.tv/','User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        #    'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_streams)
        if self.index == 'load_data_channels':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            print uri
            getPage(uri, timeout=8, method='GET',cookies=cj, headers={'Host':'www.stream-oase.tv','Referer':'http://www.stream-oase.tv/','User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_streams1)
        elif self.index == '2':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_hls_2(uri)
        elif self.index=='search_data':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(uri, timeout=8, cookies=cj,method='GET', headers={'Host':'www.stream-oase.tv','Referer':'http://www.stream-oase.tv/','User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_streams)
        elif self.index=='list_streams':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_hls(uri)


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


    def exit(self):
        print self.index
        if self.index=='load_data_channels':
            self.close()
        elif self.index=='1':
            self.close()
        elif self.index=='2':
            self.index = '1'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster() 
        elif self.index=='search_data':
            self.close()
        elif self.index=='list_streams':
            self.index='1'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            #self.load_poster()
        elif self.index=='search_data':
            self.index='search'
            self.search()
        elif self.index=='search':
            self.index='1'
            self.abc()
			
    def load_capture(self,jp_link):
        tmp_image = jpg_store = '/tmp/teledunet_poster.jpg'
        headers = {':host':'openload.co',':method':'GET',':path':'/dlcaptcha/xweNP3UWXqA.png',':scheme':'https',':version':'HTTP/1.1'}
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            print "Error: can't find file or read data"
            		

    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'