from imports import *
from about import *
import requests,urllib,urllib2,re,cookielib,json,base64
global mainUrl
global username
global password
global useragent 
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, image,index):
    res = [(name, link, image,index)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, 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 solidstreamz(Screen):

    def __init__(self, session):
        self.session = 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()
        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}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('Solidstreamz')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        global old_ref
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.list_cat)

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

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

    def down(self):
        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 list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        api_URL = 'http://solidstreamz.com/api/soliddata.php'
        r=requests.post(api_URL,headers={"Authorization": "Basic U29saWRTdHJlYW16OkAhU29saWRTdHJlYW16IUA="}) 
        value=r.text.replace('eyi','ey')
        if len(value) % 4 != 0: #check if multiple of 4
            while len(value) % 4 != 0:
                value = value + "="
            req_str = base64.b64decode(value)
        else:
            req_str = base64.b64decode(value)
        print req_str
		#result = json.loads(req_str)
        global mainUrl
        #mainUrl	= result["DATA"][0]["MainURL"]
        global username
        #username = result["DATA"][0]["Username"]
        global password
        #password = result["DATA"][0]["Password"]
        global useragent 
        #useragent = result["DATA"][0]["UserAgent"]
        try:
            mainUrl	= re.findall('"MainURL":"(.*?)"',req_str)[0]
            username =re.findall('"Username":"(.*?)"',req_str)[0]
            password =re.findall('"Password":"(.*?)",',req_str)[0]
            useragent =re.findall('"UserAgent":"(.*?)",',req_str)[0]
        except:
            print 'no data'
        liveCategories = [('ALL')]#,('UK'),('DE'),('PT'),('SPORTS'),('PK'),('NL'),('RG'),('PB'),('IN')]
        for category in liveCategories:
            self.cat_list.append(show_(category,None,None,None))
        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def list_channels(self):
        self.info = 'list_channels'
        self.show_list = []
        self.ch_list = []
        selected = self['menulist'].getCurrent()[0][0]
        url = url = '%s/get.php?username=%s&password=%s&type=m3u' % (mainUrl, username, password)
        req = urllib2.Request(url)
        try:
            response = urllib2.urlopen(req)
            data = response.read()
        except:
            data='Page changed again'
        print data
##EXTINF:-1,BEIN SPORTS 8 HD (AR)-SP
#http://217.182.192.199:25461/live/ChmQC/SDYSu/151.ts
#EXTINF:-1,BEIN SPORTS 5 HD SP-AR
#http://217.182.192.199:25461/live/sports/bt/148.ts

#		
        if selected=='ALL':
            ch=re.findall('#EXTINF:-1,(.*?)\n(http.*?)\n',data)
        elif selected=='UK':
            ch=re.findall('#EXTINF:-1,(.*?)-UK\n(http.*?)ts',data)
        elif selected=='DE':
            ch=re.findall('#EXTINF:-1,(.*?)-DE\n(http.*?)ts',data)
        elif selected=='RG':
            ch=re.findall('#EXTINF:-1,(.*?)-RG\n(http.*?)ts',data)
        elif selected=='PT':
            ch=re.findall('#EXTINF:-1,(.*?)-PT\n(http.*?)ts',data)
        elif selected=='IT':
            ch=re.findall('#EXTINF:-1,IT.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='FR':
            ch=re.findall('#EXTINF:-1,FR.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='SPORTS':
            ch=re.findall('#EXTINF:-1,(.*?)-SP\n(http.*?)ts',data)
        elif selected=='TAMIL':
            ch=re.findall('#EXTINF:-1,TM.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='TG':
            ch=re.findall('#EXTINF:-1,TG.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='PK':
            ch=re.findall('#EXTINF:-1,(.*?)-PK\n(http.*?)ts',data)
        elif selected=='KD':
            ch=re.findall('#EXTINF:-1,Kids.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='KN':
            ch=re.findall('#EXTINF:-1,KN.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='KRD':
            ch=re.findall('#EXTINF:-1,KRD.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='MR':
            ch=re.findall('#EXTINF:-1,MR.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='PB':
            ch=re.findall('#EXTINF:-1,(.*?)-PB\n(http.*?)ts',data)
        elif selected=='IN':
            ch=re.findall('#EXTINF:-1,(.*?)-IN\n(http.*?)ts',data)
        elif selected=='OD':
            ch=re.findall('#EXTINF:-1,OD.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='NP':
            ch=re.findall('#EXTINF:-1,NP.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='IS':
            ch=re.findall('#EXTINF:-1,IS.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='IND':
            ch=re.findall('#EXTINF:-1,IND.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='IN':
            ch=re.findall('#EXTINF:-1,IN.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='GUJ':
            ch=re.findall('#EXTINF:-1,GUJ.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='EN':
            ch=re.findall('#EXTINF:-1,EN.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='BD':
            ch=re.findall('#EXTINF:-1,BD.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='AFG':
            ch=re.findall('#EXTINF:-1,AFG.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='AR':
            ch=re.findall('#EXTINF:-1,AR.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='PH':
            ch=re.findall('#EXTINF:-1,PH.*?: (.*?)\n(http.*?)ts',data)
        elif selected=='SP':
            ch=re.findall('#EXTINF:-1,(.*?)-SP\n(http.*?)ts',data,re.DOTALL)
        elif selected=='PEHLA':
            ch=re.findall('#EXTINF:-1,PEHLA.*?: (.*?)\n(http.*?)ts',data)
        if ch:
            for each in ch:
                title,url=each
                url=url#+'ts'
                self.show_list.append(show_(title, url, None,None))
        else:
            self.show_list.append(show_('Sorry - no channels found', 'http://', None,None))
        self['menulist'].l.setList(self.show_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def play_movie(self, link):
        link=str(link)
        self.info='player'
        if link:
            link='http://127.0.0.1:88/httpstream://'+link+' headers={"User-Agent":"%s","Host":"217.182.192.199:25461","Icy-MetaData":"1","Range":"bytes=0-"}' %useragent
            link=str(link)
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, link)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        selectedIndex= self['menulist'].l.getCurrentSelection()[0][3]
        if self.info == 'list_cat':
            self.list_channels()
        elif self.info=='list_channels':
            url = str(selectedEntry)
            self.play_movie(url)
           

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            self.close(self.session, 'exit')
        elif self.info == 'list_channels':
            self.list_cat()
        elif self.info=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info='list_channels'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)