# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/dramacafe.py
from imports import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
from VirtualKeyBoard import VirtualKeyBoard
UserAgent = 'Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.0.15) Gecko/2009102815 Ubuntu/9.04 (jaunty) Firefox/3.'

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 dramacafe(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()
        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,
         'cancel': self.exit,
         'red': self.exit,
         'yellow': self.about,
         'green': self.search}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['text'].setText('Loading data..')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('Dramacafe')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.menulist2 = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = -1
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.abc)

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

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie' or 'episodes':
            try:
                self.show_cover()
            except:
                print ' error loading cover'

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie' or 'episodes':
            try:
                self.show_cover()
            except:
                print ' error loading cover'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie' or 'episodes':
            try:
                self.show_cover()
            except:
                print ' error loading cover'

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.check == 'letter_movie' or 'episodes':
            try:
                self.show_cover()
            except:
                print ' error loading cover'

    def abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_list = []
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['text'].setText('Select category.')
        self.genre_name = 'this section'
        cat = [('Asian Drama', 'http://www.online.dramacafe.tv/browse-AsianDrama-videos-'),
         ('Anime And Cartoon', 'http://www.online.dramacafe.tv/browse-AnimeAndCartoon-videos-'),
         ('Cartoons', 'http://www.online.dramacafe.tv/browse-Cartoons-videos-'),
         ('Anime Series', 'http://www.online.dramacafe.tv/browse-AnimeSeries-videos-'),
         ('Movies', 'http://www.online.dramacafe.tv/browse-AnimeMovies-videos-'),
         ('Ramadan 2013', 'http://www.online.dramacafe.tv/browse-Ramadan2013-videos-'),
         ('Khaleeji Drama', 'http://www.online.dramacafe.tv/browse-Khaleeji-videos-'),
         ('Khaleeji Comedy', 'http://www.online.dramacafe.tv/browse-KhaleejiComedy-videos-'),
         ('Khaleeji Drama', 'http://www.online.dramacafe.tv/browse-KhaleejiDrama-videos-'),
         ('Non-Arabic Series', 'http://www.online.dramacafe.tv/browse-NonArabicSeries-videos-'),
         ('Syrian Drama', 'http://www.online.dramacafe.tv/browse-SyrianDrama-videos-'),
         ('Syrian Drama 2', 'http://www.online.dramacafe.tv/browse-SyrianDrama2-videos-'),
         ('SyrianComedy', 'http://www.online.dramacafe.tv/browse-SyrianComedy-videos-'),
         ('Egyptian Drama', 'http://www.online.dramacafe.tv/browse-EgyptianDrama-videos-'),
         ('Lebanese Drama', 'http://www.online.dramacafe.tv/browse-LebaneseDrama-videos-'),
         ('Historical', 'http://www.online.dramacafe.tv/browse-Historical-videos-'),
         ('Historical Drama', 'http://www.online.dramacafe.tv/browse-HistoricalDrama-videos-'),
         ('Bedouin Drama', 'http://www.online.dramacafe.tv/browse-BedouinDrama-videos-'),
         ('Dubbed Drama', 'http://www.online.dramacafe.tv/browse-DubbedDrama-videos-'),
         ('TurkishDrama', 'http://www.online.dramacafe.tv/browse-TurkishDrama-videos-'),
         ('MexicanDrama', 'http://www.online.dramacafe.tv/browse-MexicanDrama-videos-'),
         ('IranianDrama', 'http://www.online.dramacafe.tv/browse-IranianDrama-videos-'),
         ('Arabic Movies', 'http://www.online.dramacafe.tv/browse-ArabicMovies-videos-'),
         ('Ramadan 2011', 'http://www.online.dramacafe.tv/browse-Ramadan2011-videos-'),
         ('Ramadan 2012', 'http://www.online.dramacafe.tv/browse-Ramadan2012-videos-'),
         ('Iraqi Drama', 'http://www.online.dramacafe.tv/browse-IraqiDrama-videos-'),
         ('Clips & Short Videos', 'http://www.online.dramacafe.tv/browse-Clips-videos-'),
         ('Theatre', 'http://www.online.dramacafe.tv/browse-Theatre-videos-'),
         ('Movies Pack', 'http://www.online.dramacafe.tv/browse-MoviesPacks-videos-'),
         ('Bollywood', 'http://www.online.dramacafe.tv/browse-Bollywood-videos-')]
        for each in cat:
            category, link = each
            self.letter_list.append(cat_(category, link))

        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        genre_link = self['menulist'].getCurrent()[0][1]
        self.count = -1

    def start(self, main_url, count):
        print ' got data - now processing'
        self.check = 'letter_movie'
        self.count += 1
        url = main_url + str(self.count) + '-title.html'
        getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.load_data, main_url)

    def load_data(self, data, main_url):
        movies = re.findall('<a href="(.*?)" class="pm-thumb-fix pm-thumb-145"><span class="pm-thumb-fix-clip"><img src="(.*?)" alt="(.*?)" width="145"><span class="vertical-align"></span></span></a>', data, re.DOTALL)
        for each in movies:
            path, thumb, name = each
            if str(thumb).endswith('g'):
                self.letter_movielist.append(show_(name, path, thumb))

        self['menulist'].l.setList(self.letter_movielist)
        self['menulist'].l.setItemHeight(40)
        self.loading += 10
        self.show_cover()
        if int(self.count) == -1:
            pro = 'Loading.. %s/100%%' % self.loading
            self['text'].setText(pro)
            self.start(main_url, -1)
        elif int(self.count) > 9:
            count_movies = len(self.letter_movielist)
            self['text'].setText('Found %s series in -%s-' % (count_movies, self.genre_name))
            self.loading_ok = True
            self.loading = 0
            self.count = -1
        else:
            pro = 'Loading.. %s/100%%' % self.loading
            self['text'].setText(pro)
            self.start(main_url, -1)

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

    def search_dramacafe(self, searchstring = None):
        self.check = 'letter_movie'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://www.online.dramacafe.tv/search.php?keywords=' + searchstring_fin
            getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        movies = re.findall('<a href="(.*?)" class="pm-thumb-fix pm-thumb-145" target="_blank"><span class="pm-thumb-fix-clip"><img src="(.*?)" alt="(.*?)" width="145"><span class="vertical-align"></span></span></a>', data, re.DOTALL)
        for each in movies:
            path, thumb, name = each
            print name
            if str(thumb).endswith('g'):
                self.search_list.append(show_(name, path, thumb))

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

    def listEpisodes(self, data):
        self.check = 'episodes'
        self.episodes_list = []
        episodes = re.findall('\t\t<a title="(.*?)" href="(.*?)">\n\t  <img src="(.*?)" width="150" height="225" border="1" /><br />', data, re.DOTALL)
        for items in episodes:
            name, path, thumb = items
            path = 'http://mosalsalat.alqudseyes.com' + str(path)
            thumb = 'http://mosalsalat.alqudseyes.com' + str(thumb)
            if str(thumb).endswith('f'):
                self.episodes_list.append(show_(name, path, thumb))

        self['menulist'].l.setList(self.episodes_list)
        self['menulist'].l.setItemHeight(40)

    def get_play_link(self, name, url):
        print 'now get the player url'
        videoid = re.findall('-video_(.*?).html', url)
        url = 'http://www.online.dramacafe.in/ajax.php?p=video&do=getplayer&vid=' + videoid[0] + '&aid=4&player=detail'
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link = response.read()
        target = re.findall('src="(.+?)"', link)
        print target
        if 'http://www.dailymotion.com/' in str(target[0]):
            print 'Dailymotion url detected'
            url = target[0]
            req = urllib2.Request(url)
            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')
            req.add_header('Referer', 'http://www.dailymotion.com/de')
            page = urllib2.urlopen(req)
            response = page.read()
            stream720 = re.findall('"720":\[\{"type":".*?","url":"(.*?)"\}\]', response)
            stream480 = re.findall('"480":\[\{"type":".*?","url":"(.*?)"\}\]', response)
            stream380 = re.findall('"380":\[\{"type":".*?","url":"(.*?)"\}\]', response)
            stream240 = re.findall('"240":\[\{"type":".*?","url":"(.*?)"\}\]', response)
            if stream720:
                final_url = str(stream720[0]).replace('\\', '')
                self.play_movie(final_url)
            else:
                final_url = str(stream480[0]).replace('\\', '')
                self.play_movie(final_url)
        elif 'player.vimeo.com' in str(target[0]):
            req1 = urllib2.Request('http:' + target[0])
            req1.add_header('Referer', 'http://www.online.dramacafe.in/ajax.php?p=video&do=getplayer&vid=536b4276e')
            req1.add_header('Host', 'player.vimeo.com')
            req1.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
            response = urllib2.urlopen(req1)
            link1 = response.read()
            final_url = re.findall('"hd":"(.*?)"\\}', link1)
            if final_url:
                self.play_movie(final_url[0])

    def read_link(self, data):
        print 'read_link'
        link = re.findall('<iframe frameborder="0" width="560" height="317" src="(.*?)?', data)
        daily = getPage(link, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'})
        matchFullHD = re.compile('"stream_h264_hd1080_url":"(.+?)"', re.DOTALL).findall(daily)
        matchHD = re.compile('"stream_h264_hd_url":"(.+?)"', re.DOTALL).findall(daily)
        matchHQ = re.compile('"stream_h264_hq_url":"(.+?)"', re.DOTALL).findall(daily)
        matchSD = re.compile('"stream_h264_url":"(.+?)"', re.DOTALL).findall(daily)
        matchLD = re.compile('"stream_h264_ld_url":"(.+?)"', re.DOTALL).findall(daily)
        final_url = matchHD[0]
        if final_url:
            self.play_movie(final_url)

    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.check == 'abc':
            self.loading_ok = False
            self.index_nr = self['menulist'].getSelectedIndex()
            self.genre_name = self['menulist'].getCurrent()[0][0]
            genre_link = self['menulist'].getCurrent()[0][1]
            self.letter_movielist = []
            self.start(genre_link, -1)
        elif self.check == 'letter_movie':
            self.filmname = self['menulist'].getCurrent()[0][0]
            link = self['menulist'].getCurrent()[0][1]
            self.dnfile = 'False'
            print link
            self.get_play_link(self.filmname, link)

    def exit(self):
        os.system('rm -rf /tmp/dramacafe')
        self.close()

    def show_cover(self):
        jpg_link = self['menulist'].getCurrent()[0][2]
        jpg_name = self['menulist'].getCurrent()[0][0]
        jpg_store = '/tmp/dramacafe/%s' % jpg_name
        if not os.path.exists(jpg_store):
            downloadPage(jpg_link, jpg_store).addCallback(self.downloadPic, jpg_store).addErrback(self.errorload)
        else:
            self.poster_resize(jpg_store)

    def downloadPic(self, data, jpg_store):
        if fileExists(jpg_store):
            self.poster_resize(jpg_store)
        else:
            print '[dramacafe] thumb 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 '[dramacafe] no thumb.. error'
        return

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found'), MessageBox.TYPE_INFO, timeout=3)

    def errorload(self, error):
        print ''

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