# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/shahid.py
from imports import *
from Screens.HelpMenu import HelpableScreen
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
from VirtualKeyBoard import VirtualKeyBoard
urlBase = 'http://shahid.mbc.net'
urlChannels = 'http://shahid.mbc.net/ar/channel-browser.html'
urlSearch = 'http://shahid.mbc.net/Ajax/seriesFilter?year=0&dialect=0&title=0&genre=0&channel=0&prog_type=0&media_type=0&airing=0&sort=alpha&series_id=0&offset=0&sub_type=0&limit=10000'
MBCproviderID = '2fda1d3fd7ab453cad983544e8ed70e4'
UserAgent = 'Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.0.15) Gecko/2009102815 Ubuntu/9.04 (jaunty) Firefox/3.'
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):
    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 show2_(title, url, jpg_link, chID):
    res = [(title,
      url,
      jpg_link,
      chID)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=title, 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 shahidmbcnet(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()
        Screen.__init__(self, session)
        self.session = session
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label(' ')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('shahid.mbc.net')
        self.onLayoutFinish.append(self.listChannels)
        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,
         'green': self.search,
         'red': self.exit1}, -1)

    def up(self):
        self['menulist'].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if re.match('(mbc1|streams|channels|episodes)', self.ok_info, re.S | re.I):
            self.load_poster()
        elif re.match('(search|filme)', self.ok_info, re.S | re.I):
            self.load_poster()

    def down(self):
        self['menulist'].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if re.match('(mbc1|streams|channels|episodes)', self.ok_info, re.S | re.I):
            self.load_poster()
        elif re.match('(search|filme)', self.ok_info, re.S | re.I):
            self.load_poster()

    def left(self):
        self['menulist'].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if re.match('(mbc1|streams|channels|episodes)', self.ok_info, re.S | re.I):
            self.load_poster()
        elif re.match('(search|filme)', self.ok_info, re.S | re.I):
            self.load_poster()

    def right(self):
        self['menulist'].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if re.match('(mbc1|channels)', self.ok_info, re.S | re.I):
            self.load_poster()
        elif re.match('(search|filme)', self.ok_info, re.S | re.I):
            self.load_poster()

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

    def searchshahid(self, searchstring = None):
        self.ok_info = 'search'
        self.wsection = 'search'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            print searchstring_fin
            url = 'http://shahid.mbc.net/Ajax/seriesFilter?year=0&dialect=0&title=' + searchstring_fin + '&genre=0&channel=0&prog_type=0&media_type=0&airing=0&sort=alpha&series_id=0&offset=0&sub_type=0&limit=10000'
            getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        search = re.findall('href="(.*?)" title=""><b><img src="(.*?)" width="" height="" border="0" alt="" /></b><span class="title major">(.*?)</span>', data, re.S)
        if search:
            for each in search:
                url, img, title = each
                print title
                self.search_list.append(show_(title, url, img))

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

    def listChannels(self):
        self.ok_info = 'channels'
        self.wsection = 'channels'
        self.channelliste = []
        categories = [('AlArabiya', '/ar/channel/7887/AlArabiya.html', 'http://www.shahidproject.com/mediaObject/channels/Al-Arabiyah-Thumb-Big/resolutions/res-224x128/Al-Arabiyah-Thumb-Big.jpg'),
         ('MBC+Action', '/ar/channel/7888/MBC+Action.html', 'http://shahid.mbc.net/mediaObject/channels/MBC_ACTION_THUMB/resolutions/res-224x128/MBC_ACTION_THUMB.jpg'),
         ('MBC_MASR', '/ar/channel/7900/MBC+%D9%85%D8%B5%D8%B1.html', 'http://shahid.mbc.net/mediaObject/channels/MBC_MASR_thumb/resolutions/res-224x128/MBC_MASR_thumb.jpg'),
         ('MBC_Drama', '/ar/channel/7889/MBC+Drama.html', 'http://shahid.mbc.net/mediaObject/channels/mbc_drama_Thumb/resolutions/res-224x128/mbc_drama_Thumb.jpg'),
         ('MBC2', '/ar/channel/7885/MBC2.html', 'http://www.shahidproject.com/mediaObject/channels/mbc2_thump/resolutions/res-224x128/mbc2_thump.jpg'),
         ('MBC1', '/ar/channel/7892/MBC1.html', 'http://shahid.mbc.net/mediaObject/channels/MBC1_thump/resolutions/res-224x128/MBC1_thump.jpg'),
         ('MBC3', '/ar/channel/7890/MBC3.html', 'http://shahid.mbc.net/mediaObject/channels/MBC3_Thumb/resolutions/res-224x128/MBC3_Thumb.jpg'),
         ('DW', '/ar/channel/7897/DW.html', 'http://shahid.mbc.net/mediaObject/channels/DW-Thumb-Big/resolutions/res-224x128/DW-Thumb-Big.jpg'),
         ('Al_Sumaria', '/ar/channel/7894/%D8%A7%D9%84%D8%B3%D9%88%D9%85%D8%B1%D9%8A%D8%A9.html', 'http://shahid.mbc.net/mediaObject/channels/Al_Sumaria_Big_Thumb/resolutions/res-224x128/Al_Sumaria_Big_Thumb.jpg'),
         ('Alsharqia', '/ar/channel/7895/%D8%A7%D9%84%D8%B4%D8%B1%D9%82%D9%8A%D8%A9.html', 'http://shahid.mbc.net/mediaObject/channels/Alsharqia_thump/resolutions/res-224x128/Alsharqia_thump.jpg'),
         ('Al_Rasheed', '/ar/channel/7893/%D8%A7%D9%84%D8%B1%D8%B4%D9%8A%D8%AF.html', 'http://shahid.mbc.net/mediaObject/channels/Al_Rasheed_Thumb/resolutions/res-224x128/Al_Rasheed_Thumb.jpg'),
         ('MBC4', '/ar/channel/7891/MBC4.html', 'http://shahid.mbc.net/mediaObject/channels/mbc4-thumb/resolutions/res-224x128/mbc4-thumb.jpg'),
         ('Dream_2', '/ar/channel/7902/%D8%AF%D8%B1%D9%8A%D9%85+2.html', 'http://shahid.mbc.net/mediaObject/channels/Dream_2_thumb/resolutions/res-224x128/Dream_2_thumb.jpg'),
         ('Sada_AlBalad', '/ar/channel/7901/%D8%B5%D8%AF%D9%89+%D8%A7%D9%84%D8%A8%D9%84%D8%AF.html', 'http://shahid.mbc.net/mediaObject/channels/Sada_AlBalad_Thumb/resolutions/res-224x128/Sada_AlBalad_Thumb.jpg'),
         ('MBC_Bollywood', '/ar/channel/7923/MBC+Bollywood.html', 'http://shahid.mbc.net/mediaObject/channels/MBC_Bollywood/resolutions/res-224x128/MBC_Bollywood.jpg'),
         ('DMTV', '/ar/channel/7927/DMTV.html', 'http://shahid.mbc.net/mediaObject/channels/DM_THUMB/resolutions/res-224x128/DM_THUMB.jpg')]
        for each in categories:
            show_name, url, img_path = each
            self.channelliste.append(show_(show_name, url, img_path))

        self['menulist'].l.setList(self.channelliste)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/shahidmbc_poster.jpg'
        downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image).addErrback(self.errorload)

    def show_video(self, title, url, jpg_link, imdb, quali, handlung):
        res = [(title,
          url,
          jpg_link,
          imdb,
          quali,
          handlung)]
        res.append(MultiContentEntryText(pos=(0, 0), size=(550, 40), font=4, text=title, flags=RT_HALIGN_CENTER, color=16777215, color_sel=16451625))
        return res

    def show_handlung(self):
        count_index = self['menulist'].getCurrent()
        if not count_index == None:
            handlung = self['menulist'].getCurrent()[0][3]
            self['handlung'].setText(self.umlaute(handlung))
        return

    def downloadPic(self, data, jpg_store):
        self.poster_resize(jpg_store)

    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()
        return

    def errorload_timeout(self, error):
        self['info'].setText('mbc.net is unreachable. try again later!')

    def errorload(self, error):
        print '[mbc.net]:', error

    def ok(self):
        print self.ok_info
        if re.match('(channels)', self.ok_info, re.S | re.I):
            count_index = self['menulist'].getCurrent()
            self.lastpoint = self['menulist'].getSelectedIndex()
            self.filmname = self['menulist'].getCurrent()[0][0]
            url = self['menulist'].getCurrent()[0][1]
            self.listShows(url)
        elif self.ok_info == 'streams':
            count_index = self['menulist'].getCurrent()
            self.lastpoint = self['menulist'].getSelectedIndex()
            self.filmname = self['menulist'].getCurrent()[0][0]
            url = self['menulist'].getCurrent()[0][1]
            self.listEpsodes(url)
        elif self.ok_info == 'episodes':
            count_index = self['menulist'].getCurrent()
            self.lastpoint = self['menulist'].getSelectedIndex()
            self.filmname = self['menulist'].getCurrent()[0][0]
            url = self['menulist'].getCurrent()[0][1]
            chID = self['menulist'].getCurrent()[0][1]
            url = 'http://shahid.mbc.net/' + url
            self.get_streamlink(chID)
        elif self.ok_info == 'streamlink':
            count_index = self['menulist'].getCurrent()
            self.lastpoint = self['menulist'].getSelectedIndex()
            self.filmname = self['menulist'].getCurrent()[0][0]
            url = self['menulist'].getCurrent()[0][1]
            self.prepare_MediaPlayer(url)
        elif self.ok_info == 'search':
            count_index = self['menulist'].getCurrent()
            self.lastpoint = self['menulist'].getSelectedIndex()
            self.filmname = self['menulist'].getCurrent()[0][0]
            url = self['menulist'].getCurrent()[0][1]
            self.listEpsodes(url)

    def listShows(self, ch_path):
        self.ok_info = 'streams'
        self.series_list = []
        chID = re.findall(re.compile('/ar/channel/(.*?)/'), ch_path)
        if chID:
            urlCh = 'http://shahid.mbc.net/ar/show-browser~-param-.channels-' + chID[0] + '.html'
            urlSeries = 'http://shahid.mbc.net/ar/series-browser~-param-.channels-' + chID[0] + '.html'
            if chID:
                htmlfile = urllib.urlopen(urlCh)
                htmltext = htmlfile.read()
                regex1 = '<div class="title"><a href="/ar/show/.*?/.*?">(.*?)</a></div>'
                regex2 = 'src="(.*?)" onerror="imgError\\(this\\)\\;"/>'
                regex3 = '<div class="title"><a href="(.*?)">'
                regex4 = '<div class="info">(.*?)</div>'
                pattern1 = re.compile(regex1)
                pattern2 = re.compile(regex2)
                pattern3 = re.compile(regex3)
                pattern4 = re.compile(regex4)
                show_name = re.findall(pattern1, htmltext)
                img_path = re.findall(pattern2, htmltext)
                ch_path = re.findall(pattern3, htmltext)
                info = re.findall(pattern4, htmltext)
                i = 0
                while i < len(ch_path):
                    if show_name[i] is not '':
                        self.series_list.append(show2_(show_name[i], ch_path[i], img_path[i], chID))
                    else:
                        self.series_list.append(show2_(info[i], ch_path[i], img_path[i], chID))
                    i += 1

                htmlfile = urllib.urlopen(urlSeries)
                htmltext = htmlfile.read()
                regex1 = '<div class="title"><a href="/ar/series/.*?/.*?">(.*?)</a></div>'
                regex2 = 'src="(.*?)" onerror="imgError\\(this\\)\\;"/>'
                regex3 = '<div class="title"><a href="(.*?)">'
                pattern1 = re.compile(regex1)
                pattern2 = re.compile(regex2)
                pattern3 = re.compile(regex3)
                show_name = re.findall(pattern1, htmltext)
                img_path = re.findall(pattern2, htmltext)
                ch_path = re.findall(pattern3, htmltext)
                i = 0
                while i < len(ch_path):
                    if show_name[i] is not '':
                        self.series_list.append(show2_(show_name[i], ch_path[i], img_path[i], chID))
                    i += 1

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

    def show_streams(self, hostername, url):
        res = [(hostername, url)]
        res.append(MultiContentEntryText(pos=(10, 0), size=(800, 40), font=8, text=hostername, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
        return res

    def listEpsodes(self, ch_path):
        print 'list episodes'
        self.ok_info = 'episodes'
        self.episodes_list = []
        chID = re.findall(re.compile('/ar/.*?/(.*?)/'), ch_path)
        if chID:
            urlCh = 'http://shahid.mbc.net' + ch_path
            htmlfile = urllib.urlopen(urlCh)
            htmltext = htmlfile.read()
            regex1 = '\n\t\t<a href="\\/ar\\/episode\\/.*?\\/(.+?).html">'
            regex2 = 'src="(.*?)" onerror="imgError\\(this\\)\\;"/>'
            regex3 = '\n\t\t<a href="\\/ar\\/episode\\/(.+?)">'
            regex4 = '<div class="info">(.*?)</div>'
            pattern1 = re.compile(regex1)
            pattern2 = re.compile(regex2)
            pattern3 = re.compile(regex3)
            pattern4 = re.compile(regex4)
            show_name = re.findall(pattern1, htmltext)
            info = re.findall(pattern4, htmltext)
            img_path = re.findall(pattern2, htmltext)
            ch_path = re.findall(pattern3, htmltext)
            i = 0
            while i < len(ch_path):
                if show_name[i] is not '':
                    self.episodes_list.append(show2_(show_name[i], ch_path[i], img_path[i], None))
                else:
                    self.series_list.append(show2_(info[i], ch_path[i], img_path[i], None))
                i += 1

            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        else:
            message = self.session.open(MessageBox, _('No CHID - try again'), MessageBox.TYPE_INFO, timeout=5)
        return

    def get_streamlink(self, ch_path):
        ch_path = str(ch_path).replace('[', '').replace("'", '').replace(']', '')
        ch_path = '/ar/episode/' + ch_path
        ch_path1 = re.findall('/ar/episode/(.*?)/', ch_path)
        ch_path1 = str(ch_path1).replace('[', '').replace("'", '').replace(']', '')
        get_mediaID_url = 'http://shahid.mbc.net/arContent/getPlayerContent-param-.id-' + ch_path1 + '.type-player.pricingPlanId-8879.html'
        self.ok_info = 'streamlink'
        self.play_link_list = []
        headerValues = {'host': 'shahid.mbc.net'}
        new_url = urllib2.Request(get_mediaID_url, headers=headerValues)
        htmlfile = urllib2.urlopen(new_url)
        htmltext = htmlfile.read()
        regex2 = '"url":"(.*?)","'
        pattern2 = re.compile(regex2)
        m3u8_base_link = re.findall(pattern2, htmltext)
        m3u8_base_link = str(m3u8_base_link[0]).replace('\\', '')
        m3u8_file = urllib2.urlopen(m3u8_base_link)
        htmltext = m3u8_file.read()
        media = re.findall('PROGRAM-ID=1,BANDWIDTH=(.*?)\n(.*?).m3u8', htmltext)
        for each in media:
            bandwidth, m3u8_url = each
            m3u8_url = m3u8_url + '.m3u8'
            self.play_link_list.append(show_('Bandwith : ' + bandwidth, m3u8_url, None))

        self['menulist'].l.setList(self.play_link_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        return

    def prepare_MediaPlayer(self, rtmpURL):
        link = 'http://127.0.0.1:88/hls://' + rtmpURL
        self.play_movie(link)

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

    def exit(self):
        print self.ok_info
        if re.match('(films)', self.ok_info, re.S | re.I):
            if fileExists('/tmp/shahidmbc_poster.jpg'):
                os.system('rm -r /tmp/shahidmbc_poster.jpg')
            del self.picload
            self.close(self.session, 'exit')
        elif self.ok_info == 'streams':
            self.ok_info = 'channels'
            self['menulist'].l.setList(self.channelliste)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(int(self.lastpoint))
        elif self.ok_info == 'channels':
            self.ok_info = self.wsection
            self.close(self.session, 'exit')
        elif self.ok_info == 'episodes':
            self.ok_info = 'streams'
            self['menulist'].l.setList(self.series_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(int(self.lastpoint))
        elif self.ok_info == 'streamlink':
            self.ok_info = 'episodes'
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(int(self.lastpoint))
        elif self.ok_info == 'search':
            self.ok_info = 'streams'
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(int(self.lastpoint))

    def exit1(self):
        if fileExists('/tmp/shahidmbc_poster.jpg'):
            os.system('rm -r /tmp/shahidmbc_poster.jpg')
        self.close(self.session, 'exit')


def main(session, **kwargs):
    session.openWithCallback(closen, shahidmbcnet, plugin_path)


def closen(session, result):
    if result == 'restart':
        session.openWithCallback(closen, shahidmbcnet, plugin_path)
    elif result == 'exit':
        pass