# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/shahidSeries.py
from imports import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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 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 shahidSeries(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,
         'blue': self.dnitnow}, -1)
        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('shahidSeries with all Seasons')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.list_cat)

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

    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]

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_cat':
            self.load_poster()
        elif self.info == 'list_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][2]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

        elif self.info == 'list_episodes':
            self.load_poster()
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_cat':
            self.load_poster()
        elif self.info == 'list_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][2]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

        elif self.info == 'list_episodes':
            self.load_poster()
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_cat':
            self.load_poster()
        elif self.info == 'list_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][2]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

        elif self.info == 'list_episodes':
            self.load_poster()
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_cat':
            self.load_poster()
        elif self.info == 'list_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][2]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

        elif self.info == 'list_episodes':
            self.load_poster()
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
            except:
                self['text'].setText('')

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = ['http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%220%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=eO%2F%2FmzPnBg1ZnQ8BJs%2F5cOVQ9ltldabuPOe6P4VEmWo%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%221%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=SMA8wBnr9YGtdF0i962YIf%2B%2Bt49ik4Eepkeh0z211dc%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%222%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=7iXNgCZ8jh%2BRb%2FyhVNKRf7HCK62JmaE%2Fwng4%2BJHnWDo%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%223%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=xz2lKp9nvIfO1AmyO8svkeKFnqqFF9%2FGSe1mQQ85GxE%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%224%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=Fv7Mavuz1Ctz9tnyEnKXYFAdWNoPjOEBy0c6Wk2SvU8%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%225%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=dmXhI5PvJCfrInFZloKRwDInaN2t5Oldux686LDPd8w%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%226%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=pxM4XdUUTuWXzniomCWquT2%2B5WBxzYDVlh7FeirAVZQ%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%227%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=%2ByAsgQr67SMVxxtqOxvw%2BLoL3huvXY0xSeIZjHVfYds%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%228%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=i7fNPeGeeYFL26Ib73rp8RNHNYFnrlOarsCw6jywf7Y%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%229%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=ZpwIWK68uZTmojlVAv8AdVJqFq5MEcOQGe2fH%2B%2BHpsU%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2210%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=rE9vqYWdRvN7qN6cpGald6QmK%2BgZ8gji8szJtmOMwuk%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2211%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=J6V3wQbqvnU1VsDMoLdFh5JPs8aV9yPTgEmOnnBD4mg%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2212%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=OWH55y74fze5JHV1Ig4%2Bjjqar%2BK9DHQgGy8auIWu%2FE0%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2213%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=gxxER5xMxK4Qbrcwf%2BkGfl0ONMGrE7yY4IFNjnCwWWc%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2214%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=Avkg3utcCR8WT8tKr7%2FiFKzCtC1UOuDkEtYCC9PO3wg%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2215%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=1X57rK%2FPspw0KtbgCCKPkfzNWmNv%2Fvku0JAd3qYGHuI%3D',
         'http://api.shahid.net/api/series/filter?seriesSearchParamRequest=%7B%22pageSize%22%3A%2220%22%2C%22pageNumber%22%3A%2216%22%2C%22facet%22%3A%22true%22%2C%22sort%22%3A%7B%22name%22%3A%22ASC%22%7D%7D&apiKey=sh%40hid0nlin3&hash=zNBybORVJsm0nQUrPtqKGyki%2BIVzGrViMmBq%2FkUYhkg%3D']
        for url in cat:
            getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_cat)

    def get_cat(self, data):
        shows = re.findall('\\"showName":"(.*?)","showId":(.*?),.*?"thumbnailUrl":"(.*?)","plus":false,', data, re.DOTALL)
        for each in shows:
            title, url, img = each
            self.cat_list.append(show_(title, url, img))

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

    def list_shows(self, url):
        self.info = 'list_shows'
        self.show_list = []
        uri = 'http://api.shahid.net/api/series/' + url + '?apiKey=sh%40hid0nlin3&hash=b2wMCTHpSmyxGqQjJFOycRmLSex%2BBpTK%2Fooxy6vHaqs%3D'
        getPage(uri, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_it, url)

    def list_it(self, data, url):
        showID = url
        regex1 = '{"seasonNumber":.,"title":"(.*?)","id":(.*?)}'
        regex2 = '{"title":"(.*?)","seasonNumber":.,"id":(.*?)}'
        regexList = [regex1, regex2]
        for regex in regexList:
            shows = re.findall(regex, data, re.DOTALL)
            for each in shows:
                title, url = each
                seasonID = url
                url = 'http://api.shahid.net/api/series/season/' + showID + '/' + seasonID + '?apiKey=sh%40hid0nlin3&hash=b2wMCTHpSmyxGqQjJFOycRmLSex%2BBpTK%2Fooxy6vHaqs%3D'
                self.show_list.append(cat_(title, url))

        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)
        uri = showID

    def list_episodes(self, url):
        self.info = 'list_episodes'
        self.episodes_list = []
        getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_episodes1, url)

    def list_episodes1(self, data, url):
        showID = url[0:45].replace('http://api.shahid.net/api/series/season/', '')
        showSection = re.findall('"showSectionId":(.*?),"', data)
        episodeURL = 'https://shahid.mbc.net/ar/series/autoGeneratedContent/relatedEpisodeListingDynamic~listing~-param-.ptype-series.seriesId-' + str(showID) + '.showSection-' + showSection[0] + '.sort-number:DESC.pageNumber-'
        i = 0
        for i in range(0, 8):
            uri = episodeURL + str(i) + '.html'
            getPage(uri, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded',
             'Host': 'shahid.mbc.net'}).addCallback(self.list_episodes2)
            i += 1

    def list_episodes2(self, data):
        episodes = re.findall('<a href="(\\/ar\\/episode.*?)">\\s.*\\s.*\\s.*\\s.*\\s.*\\s.*<img .*?alt="(.*?)" src="(.*?)".*\\s.*.*\\s.*.*\\s.*.*\\s.*.*\\s.*.*\\s.*\\s*.*?>(.*?)<\\/div>\\s*.*?>(.*?)<\\/div>', data, re.UNICODE)
        for each in episodes:
            url, info, img, title, date = each
            episodeID = url[0:18].replace('/ar/episode/', '')
            episodeID = episodeID.replace('/', '')
            info = info.replace('&quot;', '')
            url = 'http://api.shahid.net/api/Content/Episode/' + episodeID + '/8879?apiKey=sh%40hid0nlin3&hash=b2wMCTHpSmyxGqQjJFOycRmLSex%2BBpTK%2Fooxy6vHaqs%3D'
            self.episodes_list.append(episodes_(title, url, img, info))

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

    def get_play_link(self, data, url):
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        login_data = urllib.urlencode({'encodeURL': 'on',
         'allowCookies': 'on',
         'stripJS': 'on',
         'stripObjects': 'on',
         'u': url,
         'submit': 'Begin Browsing'})
        opener.addheaders = [('Host', 'global-proxy.com')]
        opener.addheaders = [('Origin', 'http://global-proxy.com')]
        opener.addheaders = [('Referer', 'http://global-proxy.com/')]
        opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36')]
        opener.open('http://global-proxy.com/includes/process.php?action=update', login_data)
        resp = opener.open('http://global-proxy.com/includes/process.php?action=update', login_data)
        print 'now we search the rtmp url'
        url = resp.read()
        url = re.findall('{"error":{},"url":"(.*?)","', url)
        print url
        if url:
            self.play_movie('http://127.0.0.1:88/hlsvariant://' + url[0])
        else:
            self.session.open(MessageBox, _('Sorry the user has to be subscriber\n SHAHID PLUS \xd8\xa7\xd9\x84\xd9\x85\xd8\xad\xd8\xaa\xd9\x88\xd9\x89 \xd9\x81\xd9\x82\xd8\xb7 \xd9\x85\xd8\xaa\xd8\xa7\xd8\xad \xd9\x84\xd9\x85\xd8\xb4\xd8\xaa\xd8\xb1\xd9\x83\xd9\x8a'), MessageBox.TYPE_INFO, timeout=5)

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

    def ok(self):
        if self.info == 'list_cat':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_shows(url)
        elif self.info == 'list_shows':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_episodes(url)
        elif self.info == 'list_episodes':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.filmname = str(selectedName)
            self.get_play_link(self.filmname, url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/shahidSeries_poster.jpg'):
                os.system('rm -r /tmp/shahidSeries_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_shows':
            self.info = 'list_cat'
            self['blue'].hide()
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_episodes':
            self.info = 'list_shows'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_streams':
            self.info = 'list_episodes'
            self['blue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/shahidSeries_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/shahidSeries/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 '[shahidSeries] 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 '[shahidSeries] no cover.. error'
        return

    def dir(self):
        if not pathExists('/tmp/shahidSeries/'):
            os.system('mkdir /tmp/shahidSeries/')
        else:
            print '[shahidSeries] /tmp/shahidSeries/ allready present'


def main(session, **kwargs):
    session.open(shahidSeries)


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='shahidSeries', description='shahidSeries Streamer', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]