# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/onemovies.py
from imports import *
cj = {}
import urlparse, cookielib, urllib2
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 show_all_(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 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 NoRedirection(urllib2.HTTPErrorProcessor):

    def http_response(self, request, response):
        return response


class onetwothreemovies(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('123movies')
        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_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
                self.load_poster()
            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_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
                self.load_poster()
            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_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
                self.load_poster()
            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_shows':
            try:
                seasoninfo = self['menulist'].getCurrent()[0][3]
                self['text'].setText(seasoninfo)
                self.load_poster()
            except:
                self['text'].setText('')

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        self.load_list = [('Action', 'http://123movies.to/genre/action/'),
         ('Adventure', 'http://123movies.to/genre/adventure/'),
         ('Animation', 'http://123movies.to/genre/animation/'),
         ('Biography', 'http://123movies.to/genre/biography/'),
         ('Comedy', 'http://123movies.to/genre/comedy/'),
         ('Costume', 'http://123movies.to/genre/costume/'),
         ('Crime', 'http://123movies.to/genre/crime/'),
         ('Documentary', 'http://123movies.to/genre/documentary/'),
         ('Drama', 'http://123movies.to/genre/drama/'),
         ('Family', 'http://123movies.to/genre/family/'),
         ('Fantasy', 'http://123movies.to/genre/fantasy/'),
         ('History', 'http://123movies.to/genre/history/'),
         ('Horror', 'http://123movies.to/genre/horror/'),
         ('Kungfu', 'http://123movies.to/genre/kungfu/'),
         ('Musical', 'http://123movies.to/genre/musical/'),
         ('Mystery', 'http://123movies.to/genre/mystery/'),
         ('Mythological', 'http://123movies.to/genre/mythological/'),
         ('Psychological', 'http://123movies.to/genre/psychological/'),
         ('Romance', 'http://123movies.to/genre/romance/'),
         ('Sci-Fi', 'http://123movies.to/genre/sci-fi/'),
         ('Sitcom', 'http://123movies.to/genre/sitcom/'),
         ('Sport', 'http://123movies.to/genre/sport/'),
         ('Thriller', 'http://123movies.to/genre/thriller/'),
         ('TV Show', 'http://123movies.to/genre/show/'),
         ('War', 'http://123movies.to/genre/war/')]
        for each in self.load_list:
            title, url = each
            self.cat_list.append(show_(title, url, 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_shows(self, data, url, cj):
        self.info = 'list_shows'
        self.show_list = []
        cj = cookielib.CookieJar()
        agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'
        max_page_nr = re.findall(';</a></li><li><a href=".*?" data-ci-pagination-page="(.*?)">Last >></a></li></ul>', data)
        print max_page_nr
        if max_page_nr:
            max_nr = int(max_page_nr[0]) + 1
            print max_nr
            i = 1
            for i in range(1, max_nr):
                url = str(url) + str(i)
                print url
                getPage(url, timeout=8, method='GET', headers={'Host': '123movies.to',
                 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
                 'Cookie': '__cfduid=d91a1ddfa76794de1cd7791633d73898e1441799219; ci_session=217a589c891adc2f3ae4cafb32e18ce943aefa51; _gat=1; csrf_cookie=8d72a9561f5411ee6b3f179696815c7f; _ga=GA1.2.1130587725.1441799239; __zlcmid=WdewMq4QlyHKb9; __PPU_SESSION_1_366832_false=1441816567840|2|1441816818997|2|1',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_shows1)
                i += 1
                url = self['menulist'].getCurrent()[0][1]

        else:
            cj = {}
            getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host': '123movies.to',
             'Referer': 'http://123movies.to/',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_it, cj, url)

    def parseJSString(self, s):
        try:
            offset = 1 if s[0] == '+' else 0
            val = int(eval(s.replace('!+[]', '1').replace('!![]', '1').replace('[]', '0').replace('(', 'str(')[offset:]))
            return val
        except:
            pass

    def get_it(self, data, cj, url):
        print
        print cj
        getPage(url, timeout=8, method='GET', headers={'Host': '123movies.to',
         'Referer': 'http://123movies.to/',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
         'Content-Type': 'application/x-www-form-urlencoded'}, cookies=cj).addCallback(self.list_shows1)

    def list_shows1(self, data):
        print data
        movies = re.findall('<div class="ml-item">.*?<a href="(.*?)".*?title="(.*?)">.*?<img data-original="(.*?)"', data, re.DOTALL)
        for each in movies:
            url, title, img = each
            if url is not '/':
                self.show_list.append(show_all_(title, url, img, None))

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

    def get_play_link(self, url):
        print url
        url = str(url) + 'watching.html'
        cj = {}
        getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host': '123movies.to',
         'Referer': 'http://123movies.to/genre/biography/',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.read_link, url, cj)

    def read_link(self, data, url, cj):
        print data
        med_id = re.findall('movie-id="(.*?)"', data)
        med_token = re.findall('player-token="(.*?)"', data)
        if med_id:
            med_id = med_id[0]
            med_token = med_token[0]
            uri = 'http://123movies.to/ajax/get_episodes/' + med_id + '/' + med_token
            getPage(uri, timeout=8, method='GET', cookies=cj, headers={'Host': '123movies.to',
             'Referer': 'http://123movies.to/film/sharknado-3-oh-hell-no-27279/watching.html',
             'User-Agent': 'Android'}).addCallback(self.read_link2)

    def read_link2(self, data):
        print data
        files = re.findall('onclick="loadEpisode\\((.*?),(.*?),\'(.*?)\'\\)"', data)
        print files
        if files:
            uri = 'http://123movies.to/ajax/load_episode/' + files[0][1] + '/' + files[0][2]
            print uri
            getPage(uri, timeout=8, method='GET', cookies=cj, headers={'Cookie': '__cfduid=dff644bd1a642ec48585f3062efcadd7b1454598894; __PPU_SESSION_1_366832_false=1454598899586|2|1454599256882|2|1; __zlcmid=Z1fItysWPjylq0; _ga=GA1.2.2080024227.1454598896; MarketGidStorage=%7B%220%22%3A%7B%22svspr%22%3A%22%22%2C%22svsds%22%3A9%2C%22TejndEEDj%22%3A%22MTQ1NDU5ODg5NzY4ODMzNjA3NDMwMQ%3D%3D%22%7D%2C%22C33607%22%3A%7B%22page%22%3A1%2C%22time%22%3A1454601807249%7D%2C%22C33608%22%3A%7B%22page%22%3A1%2C%22time%22%3A1454600108846%7D%7D; __atuvc=9%7C5; __atuvs=56b36af0c0b1d423008; ci_session=71e696460a14a204c323684658e5244df889d83e',
             'User-Agent': 'Android'}).addCallback(self.play_movie)

    def play_movie(self, link):
        print link
        uri = re.findall('file="(.*?)"', link)
        print uri
        if len(uri) > 1:
            self.play_movie2(uri[1])
        else:
            self.play_movie2(uri[0])

    def play_movie2(self, data):
        title = self['menulist'].getCurrent()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(title)
        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)
            cj = {}
            getPage(url, timeout=8, method='GET', cookies=cj, headers={'Host': '123movies.to',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_shows, url, cj)
        elif self.info == 'list_shows':
            selectedEntry = self['menulist'].getCurrent()[0][1]
            selectedName = self['menulist'].getCurrent()[0][0]
            url = selectedEntry
            self.filmname = str(selectedName)
            self.get_play_link(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)

    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'