# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/aldarmedia.py
from Components.ActionMap import *
from Components.Button import Button
from Components.Label import Label
from Components.MenuList import MenuList
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmap, MultiContentEntryPixmapAlphaTest
from Components.Pixmap import Pixmap
from enigma import ePicLoad
from Tools.LoadPixmap import LoadPixmap
from Components.AVSwitch import AVSwitch
from Components.Sources.StaticText import StaticText
from Plugins.Plugin import PluginDescriptor
from Screens.InfoBarGenerics import *
from Components.ServiceEventTracker import ServiceEventTracker, InfoBarBase
from Screens.InfoBar import MoviePlayer, InfoBar
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from string import find
from Tools.Directories import fileExists, pathExists
from Components.config import *
from Components.ConfigList import ConfigList, ConfigListScreen
from Components.config import config, ConfigSubsection, ConfigText, getConfigListEntry, ConfigSelection, ConfigPIN
from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, RT_WRAP
from enigma import getDesktop, eServiceReference, iServiceInformation, iPlayableService
from enigma import loadJPG, loadPNG
from twisted.web import client
from twisted.web.client import downloadPage, getPage
from Screens.MessageBox import MessageBox
from Components.PluginComponent import plugins
import re, urllib, urllib2, os, cookielib, time
from urllib2 import urlopen, Request
from urllib import urlencode
import sha
from shahid import *

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


def show_aldarmedia(name, link, image):
    res = [(name, link, image)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(590, 24), font=4, text=name, flags=RT_HALIGN_LEFT, color=16777215, color_sel=16451625))
    return res


def cat_aldarmedia(letter, link):
    res = [(letter, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(200, 24), font=4, text=letter, flags=RT_HALIGN_LEFT, color=16777215, color_sel=16451625))
    return res


class aldarmedia(Screen):
    skin = '\n\t<screen position="35,55" size="1210,640" title=" ">\n\t<widget name="logo" position="450,1" size="200,50" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/dubaitv_logo.png" zPosition="1" alphatest="on" />\n\t<widget name="logo2" position="0,0" size="1200,630" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/logo2.png" zPosition="0" alphatest="on" />\n\t\t<widget source="session.VideoPicture" render="Pig"  position="750,120" size="340,228" zPosition="3" backgroundColor="transparent"/>\t\n\t<widget name="text" position="10,2" size="550,40" zPosition="0" font="Regular;24" halign="left" valign="center" transparent="1" foregroundColor="#ffffff" backgroundColor="#000000" />\n\t<widget name="poster" position="15,100" size="100,100" zPosition="4" alphatest="on" />\n\t<widget name="menulist" position="200,120" size="500,450" transparent="1" scrollbarMode="showOnDemand" />\n\t<widget name="ButtonRed" position="28,596" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/red.png" zPosition="10" size="150,30" transparent="1" alphatest="on" />\n\t<widget name="TextRed" position="28,600" size="140,24" valign="center" halign="center" zPosition="11" font="Regular;18" transparent="1" />\n\t<widget name="ButtonGreen" position="196,596" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/green.png" zPosition="10" size="150,30" transparent="1" alphatest="on" />\n\t<widget name="TextGreen" position="196,600" size="140,24" valign="center" halign="center" zPosition="11" font="Regular;18" transparent="1" />\t\t\t\n\t<widget name="ButtonBlue" position="532,596" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/blue.png" zPosition="10" size="150,30" transparent="1" alphatest="on" />\n\t<widget name="TextBlue" position="532,600" size="140,24" valign="center" halign="center" zPosition="11" font="Regular;18" transparent="1" />\n\t<widget name="ButtonYellow" position="364,596" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/yellow.png" zPosition="10" size="150,30" transparent="1" alphatest="on" />\n\t<widget name="TextYellow" position="364,600" size="140,24" valign="center" halign="center" zPosition="11" font="Regular;18" transparent="1" />\n\t<widget name="plugin_logo" position="750,330" size="390,260" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/ArabicEntertainment/images/logo_dubaitv.png" zPosition="1" alphatest="on" />\n\t</screen>'

    def __init__(self, session):
        self.skin = aldarmedia.skin
        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,
         'yellow': self.about,
         'blue': self.dnitnow}, -1)
        self['menulist'] = m2list([])
        self['plugin_logo'] = Pixmap()
        self['ButtonBlue'] = Pixmap()
        self['ButtonRed'] = Pixmap()
        self['ButtonGreen'] = Pixmap()
        self['ButtonYellow'] = Pixmap()
        self['TextBlue'] = Label('Download')
        self['TextRed'] = Label('Exit')
        self['TextGreen'] = Label('Search')
        self['TextYellow'] = Label('About')
        self['TextGreen'].hide()
        self['TextBlue'].hide()
        self['logo'] = Pixmap()
        self['logo2'] = Pixmap()
        self['text'] = Label('')
        self['poster'] = Pixmap()
        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(ShahidAboutScreen)

    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()
        if self.info == 'list_episodes':
            self.load_poster_dubaitv()

    def down(self):
        self[self.currentList].down()
        if self.info == 'list_episodes':
            self.load_poster_dubaitv()

    def left(self):
        self[self.currentList].pageUp()
        if self.info == 'list_episodes':
            self.load_poster_dubaitv()

    def right(self):
        self[self.currentList].pageDown()
        if self.info == 'list_episodes':
            self.load_poster_dubaitv()

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('Series-Archive', 'http://www.aldarmedia.ae/archive-series'), ('Series', 'http://www.aldarmedia.ae/series'), ('Our Shows', 'http://www.aldarmedia.ae/our-shows')]
        for each in cat:
            title, url = each
            self.cat_list.append(cat_aldarmedia(title, url))

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

    def list_shows(self, url):
        self.info = 'list_shows'
        self.show_list = []
        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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        shows = re.findall('class="ubermenu-target ubermenu-item-layout-default ubermenu-item-layout-text_only" href="(.*?)"><span.*?class="ubermenu-target-title ubermenu-target-text">(.*?)</span></a></li>', response, re.DOTALL)
        print shows
        for each in shows:
            url, title = each
            self.show_list.append(cat_aldarmedia(title, url))

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

    def list_episodes(self, url):
        self.info = 'list_episodes'
        self.episodes_list = []
        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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        episodes = re.findall('src="(.*?)" class="attachment-video-thumb4 wp-post-image" alt=".*?" /></noscript><div.*?class="hover-image"></div></div></a><h2><a.*?href="(.*?)" rel="bookmark">(.*?)</a></h2><div', response, re.DOTALL)
        print episodes
        for each in episodes:
            img, url, title = each
            self.episodes_list.append(show_aldarmedia(title, url, img))

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

    def list_streams(self, url):
        self.info = 'list_streams'
        req = urllib2.Request(url)
        print 'STREAMURL: %s' % 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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        streams = re.findall('"file":"(.*?.mp4)",', response)
        if streams:
            self.play_aldarmedia_vod(streams[0])
        else:
            self.info1 = 'fuck'
            self.list_episodes(url)

    def list_streams1(self, url):
        self.info = 'list_streams'
        req = urllib2.Request(url)
        print 'STREAMURL: %s' % 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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        streams = re.findall('src="(.*?)" frameborder="0" allowfullscreen="1"> </iframe>', response)
        if streams:
            self.play_aldarmedia_vod(streams[0])
        else:
            streams = re.findall('"file":"(.*?.mp4)",', response)
            self.play_aldarmedia_vod(streams[0])

    def play_aldarmedia_vod(self, link):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, link)
        sref.setName(selectedName)
        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
            selectedEntry = str(selectedEntry).replace('\\', '')
            url = str(selectedEntry)
            print 'url parsed to episodes_list = %s' % url
            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
            selectedEntry = str(selectedEntry).replace('\\', '')
            url = str(selectedEntry)
            print url
            self.list_streams(url)
        elif self.info1 == 'fuck':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_streams1(url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/aldarmedia_poster.jpg'):
                os.system('rm -r /tmp/aldarmedia_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_shows':
            self.info = 'list_cat'
            self['TextBlue'].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['TextBlue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)

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

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


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


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