예제 #1
0
def progress(title, line1='', line2='', line3=''):
    dp = xbmcgui.DialogProgress()
    dp.create(title, line1, line2, line3)
    dp.update(0)
    return dp
예제 #2
0
from sqlite3 import dbapi2 as database

addon_id = 'script.ivueguide'
addon_name = xbmcaddon.Addon(addon_id)
pageNum = addon_name.getAddonInfo('Path')
HOME = addon_name.getAddonInfo('path')
ICON = os.path.join(HOME, 'icon.png')
PACKAGES       = xbmc.translatePath(os.path.join('special://home', 'addons', 'packages'))
TEMP =	  addon_name.getSetting('tempskin')
USER_AGENT     = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'

#Karls changes

ivue = utils.folder()
d = xbmcgui.Dialog()
dp = xbmcgui.DialogProgress()
skin = addon_name.getSetting('skin')
path = xbmc.translatePath(os.path.join('special://profile', 'addon_data', 'script.ivueguide', 'resources', 'skins'))
Skinxml = xbmc.translatePath(os.path.join(path, skin, '720p', 'script-tvguide-main.xml'))
xmlData = xbmc.translatePath('special://profile/addon_data/script.ivueguide/resources/config/Data.txt')
logoData = xbmc.translatePath('special://profile/addon_data/script.ivueguide/resources/config/Logo.txt')
catData = xbmc.translatePath('special://profile/addon_data/script.ivueguide/resources/categories/')	
databasePath = xbmc.translatePath('special://profile/Database')
addons27 = os.path.join(databasePath, 'Addons27.db')
ivue = utils.folder()
players = base64.b64decode('aHR0cHM6Ly9wYXN0ZWJpbi5jb20vcmF3L041ZGJuMTVI')
FOAlist = ''
proglist = []
try:
    FOAlist = urllib2.urlopen(players).read().splitlines()
except:
예제 #3
0
    def get_list(self, input_list=None, skip_meta=False, skip_dialog=False):
        """
        returns the list of items in a format suitable for kodiswift
        Returns:
        list of jen items
        """
        items = []
        meta = ADDON.getSetting("metadata") == "true"
        try:
            is_widget = __builtin__.JEN_WIDGET
        except:
            is_widget = False
        if is_widget:
            skip_dialog = True
        if input_list is None:
            input_list = self.list

        xbmc.log("input_list: " + repr(input_list))

        dialog = None
        dialog2 = None

        if not skip_dialog:
            if ADDON.getSetting("disable_metadata_dialog") == "false":
                dialog = xbmcgui.DialogProgress()
                addon_name = ADDON.getAddonInfo("name")
                dialog.create(addon_name, _("Loading items"))

        if meta and not skip_meta:
            info_thread = threadWithReturn(target=get_info,
                                           args=(input_list, dialog))
            info_thread.start()
        else:
            info_thread = None

        num_items = len(input_list)
        for index, item_xml in enumerate(input_list):
            if dialog2:
                percent = ((index + 1) * 100) / num_items
                dialog2.update(percent, _("processing item"),
                               "%s of %s" % (index + 1, num_items))
            result_item = self.process_item(item_xml)
            if result_item:
                items.append(result_item)
        if dialog2:
            dialog2.close()

        if info_thread:
            info = info_thread.join()  # wait till for thread to finish
            if info:
                skip = 0
                for index, item in enumerate(items):
                    if not item.get("summary", None) and not item.get(
                            "imdb", None):
                        continue
                    if index <= len(info) - 1:
                        for info_item in info[index + skip:]:
                            if not info_item:
                                break
                            if info_item.get("manual", ""):
                                item["info"]["plot"] = info_item["plot"]
                                break
                            if "imdb_id" in info_item:
                                if info_item["imdb_id"] == item["imdb"]:
                                    item["info"].update(info_item)
                                    break
                                else:
                                    skip = skip + 1
                            else:
                                break
                    else:
                        break

        for item in items:
            if not item.get("imdb", ""):
                continue
            match = koding.Get_From_Table(
                "watched", {
                    "identifier": item["imdb"],
                    "season": item["season"],
                    "episode": item["episode"]
                })
            if match:
                match = match[0]
                if match["watched"] and match["watched"] == "1":
                    item["info"]["playcount"] = 1
                    item["info"]["watched"] = 1

        if ADDON.getSetting("trailer_context") == "true":
            for item in items:
                if "trailer" in item["info"]:
                    try:
                        item["context"].append(
                            (_("Trailer"),
                             "PlayMedia({0})".format(item["info"]["trailer"])))
                    except:
                        pass
        return items
예제 #4
0
def downloadfile(url,nombrefichero,headers=[],silent=False,continuar=False):
    logger.info("[downloadtools.py] downloadfile: url="+url+" nombrefichero="+nombrefichero+" continuar="+repr(continuar))

    try:
        # Si no es XBMC, siempre a "Silent"
        try:
            import xbmcgui
        except:
            silent=True
        
        # antes
        #f=open(nombrefichero,"wb")
        try:
            import xbmc
            nombrefichero = xbmc.makeLegalFilename(nombrefichero)
        except:
            pass

        logger.info("[downloadtools.py] downloadfile: nombrefichero="+nombrefichero)
    
        # El fichero existe y se quiere continuar
        if os.path.exists(nombrefichero) and continuar:
            #try:
            #    import xbmcvfs
            #    f = xbmcvfs.File(nombrefichero)
            #    existSize = f.size(nombrefichero)
            #except:
            f = open(nombrefichero, 'r+b')
            existSize = os.path.getsize(nombrefichero)
            
            logger.info("[downloadtools.py] downloadfile: el fichero existe, size=%d" % existSize)
            grabado = existSize
            f.seek(existSize)

        # el fichero ya existe y no se quiere continuar, se aborta
        elif os.path.exists(nombrefichero) and not continuar:
            logger.info("[downloadtools.py] downloadfile: el fichero existe, no se descarga de nuevo")
            return

        # el fichero no existe
        else:
            existSize = 0
            logger.info("[downloadtools.py] downloadfile: el fichero no existe")
            
            #try:
            #    import xbmcvfs
            #    f = xbmcvfs.File(nombrefichero,"w")
            #except:
            f = open(nombrefichero, 'wb')
            grabado = 0
    
        # Crea el diálogo de progreso
        if not silent:            
            #progreso.create( "plugin" , "Descargando..." , os.path.basename(nombrefichero)+" desde "+urlparse.urlparse(url).hostname )

            try:
                progreso = xbmcgui.DialogProgressBG()
                progreso.create("Descargas tvalacarta", "Descargando "+os.path.basename(nombrefichero))
            except:
                progreso = xbmcgui.DialogProgress()
                progreso.create( "plugin" , "Descargando..." , url , os.path.basename(nombrefichero) )

        else:
            progreso = ""
            try:
                xbmc.executebuiltin( 'XBMC.Notification("Descargas tvalacarta", "'+os.path.basename(nombrefichero)+'", 2000)' )
            except:
                import traceback
                logger.error( traceback.format_exc() )
                pass

        # Login y password Filenium
        # http://abcd%40gmail.com:[email protected]/get/Oi8vd3d3/LmZpbGVz/ZXJ2ZS5j/b20vZmls/ZS9kTnBL/dm11/b0/?.zip
        if "filenium" in url:
            from servers import filenium
            url , authorization_header = filenium.extract_authorization_header(url)
            headers.append( [ "Authorization", authorization_header ] )
    
        if "|" in url:
            additional_headers = url.split("|")[1]
            if "&" in additional_headers:
                additional_headers = additional_headers.split("&")
            else:
                additional_headers = [ additional_headers ]
    
            for additional_header in additional_headers:
                logger.info("[downloadtools.py] additional_header: "+additional_header)
                name = re.findall( "(.*?)=.*?" , additional_header )[0]
                value = urllib.unquote_plus(re.findall( ".*?=(.*?)$" , additional_header )[0])
                headers.append( [ name,value ] )
    
            url = url.split("|")[0]
            logger.info("[downloadtools.py] downloadfile: url="+url)
    
        # Timeout del socket a 60 segundos
        socket.setdefaulttimeout(60)
    
        h=urllib2.HTTPHandler(debuglevel=0)
        request = urllib2.Request(url)
        for header in headers:
            logger.info("[downloadtools.py] Header="+header[0]+": "+header[1])
            request.add_header(header[0],header[1])
    
        if existSize > 0:
            request.add_header('Range', 'bytes=%d-' % (existSize, ))
    
        opener = urllib2.build_opener(h)
        urllib2.install_opener(opener)
        try:
            connexion = opener.open(request)
        except urllib2.HTTPError,e:
            logger.info("[downloadtools.py] downloadfile: error %d (%s) al abrir la url %s" % (e.code,e.msg,url))
            #print e.code
            #print e.msg
            #print e.hdrs
            #print e.fp
            f.close()
            if not silent:
                progreso.close()
            # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo
            if e.code==416:
                return 0
            else:
                return -2
    
        try:
            totalfichero = int(connexion.headers["Content-Length"])
        except:
            totalfichero = 1
                
        if existSize > 0:
            totalfichero = totalfichero + existSize
    
        logger.info("Content-Length=%s" % totalfichero)
    
        blocksize = 100*1024
    
        bloqueleido = connexion.read(blocksize)
        logger.info("Iniciando descarga del fichero, bloqueleido=%s" % len(bloqueleido))
    
        maxreintentos = 10
        
        while len(bloqueleido)>0:
            try:
                # Escribe el bloque leido
                #try:
                #    import xbmcvfs
                #    f.write( bloqueleido )
                #except:
                f.write(bloqueleido)
                grabado = grabado + len(bloqueleido)
                percent = int(float(grabado)*100/float(totalfichero))
                totalmb = float(float(totalfichero)/(1024*1024))
                descargadosmb = float(float(grabado)/(1024*1024))
    
                # Lee el siguiente bloque, reintentando para no parar todo al primer timeout
                reintentos = 0
                while reintentos <= maxreintentos:
                    try:
                        before = time.time()
                        bloqueleido = connexion.read(blocksize)
                        after = time.time()
                        if (after - before) > 0:
                            velocidad=len(bloqueleido)/((after - before))
                            falta=totalfichero-grabado
                            if velocidad>0:
                                tiempofalta=falta/velocidad
                            else:
                                tiempofalta=0
                            #logger.info(sec_to_hms(tiempofalta))
                            if not silent:
                                #progreso.update( percent , "Descargando %.2fMB de %.2fMB (%d%%)" % ( descargadosmb , totalmb , percent),"Falta %s - Velocidad %.2f Kb/s" % ( sec_to_hms(tiempofalta) , velocidad/1024 ), os.path.basename(nombrefichero) )
                                progreso.update( percent , "%.2fMB/%.2fMB (%d%%) %.2f Kb/s %s falta " % ( descargadosmb , totalmb , percent , velocidad/1024 , sec_to_hms(tiempofalta)))
                        break

                        try:
                            if xbmc.abortRequested:
                                logger.error( "XBMC Abort requested 1" )
                                return -1
                        except:
                            pass

                    except:
                        try:
                            if xbmc.abortRequested:
                                logger.error( "XBMC Abort requested 2" )
                                return -1
                        except:
                            pass

                        reintentos = reintentos + 1
                        logger.info("ERROR en la descarga del bloque, reintento %d" % reintentos)
                        import traceback
                        logger.error( traceback.format_exc() )
                
                # El usuario cancelo la descarga
                try:
                    if progreso.iscanceled():
                        logger.info("Descarga del fichero cancelada")
                        f.close()
                        progreso.close()
                        return -1
                except:
                    pass
    
                # Ha habido un error en la descarga
                if reintentos > maxreintentos:
                    logger.info("ERROR en la descarga del fichero")
                    f.close()
                    if not silent:
                        progreso.close()
    
                    return -2
    
            except:
                import traceback
                logger.error( traceback.format_exc() )

                f.close()
                if not silent:
                    progreso.close()
                
                #advertencia = xbmcgui.Dialog()
                #resultado = advertencia.ok('Error al descargar' , 'Se ha producido un error' , 'al descargar el archivo')
                
                return -2
    os.path.join('special://home/addons/' + o0OO00, 'fanart.jpg'))
O0O = xbmc.translatePath(
    os.path.join('special://home/addons/' + o0OO00, 'fanart.jpg'))
Oo = xbmc.translatePath(
    os.path.join('special://home/addons/' + o0OO00, 'icon.png'))
I1ii11iIi11i = 'https://img3.picload.org/image/dlgcaigw/nextpage.png'
I1IiI = xbmc.translatePath(
    os.path.join('special://home/userdata/addon_data/' + oi1000, 'favs.xml'))
o0OOO = xbmc.translatePath(
    os.path.join('special://home/userdata/addon_data/' + oi1000,
                 'settings.xml'))
iIiiiI = xbmc.translatePath(
    os.path.join(
        'special://home/userdata/addon_data/plugin.video.pandamovies.pw/downloads/'
    ))
Iii1ii1II11i = xbmcgui.DialogProgress()
iI111iI = xbmcgui.Dialog()
if 34 - 34: iii1I1I / O00oOoOoO0o0O.O0oo0OO0 + Oo0ooO0oo0oO.I1i1iI1i - II


def OoI1Ii11I1Ii1i():
    if 67 - 67: iiI1iIiI.ooo0Oo0 * i1 - Oooo0000 * i1IIi11111i / o000o0o00o0Oo
    if not os.path.exists(os.path.dirname(iIiiiI)):
        try:
            os.makedirs(os.path.dirname(iIiiiI))
            with open(o0OOO, "w") as ooIiII1I1i1i1ii:
                ooIiII1I1i1i1ii.write("<date>000</date>")
        except OSError as IIIII:
            if IIIII.errno != errno.EEXIST:
                raise
    I1()
예제 #6
0
    def onFocus(self, controlID):
        pass


if (__name__ == '__main__'):
    logging = ""
    #####	Start markings for the log file.
    log('|==============================================================================='
        )
    log('| Scripts\XBMC4Gamers Extras\Synopsis\default.py loaded.')
    log('|-------------------------------------------------------------------------------'
        )
    log('|  Initializing')
    log('|-------------------------------------------------------------------------------'
        )
    check_fonts()
    clear_properties()
    colours()
    labels()
    xbmc.executebuiltin('dialog.close(all,true)')
    #####	UI.
    if not fonts_installed:
        ui = GUI('_Script_Synopsis.xml', os.getcwd())
        ui.doModal()
        del ui

    #####	Used to focus the games list when using the script in dialog mode
    if UseDialog == 'dialog': xbmc.executebuiltin('SetFocus(50)')
    xbmcgui.DialogProgress().update(0, "")
예제 #7
0
 def DialogProgress_Create(self, *args, **kwargs):
     dialog = xbmcgui.DialogProgress()
     self._objects[id(dialog)] = dialog
     dialog.create(*args, **kwargs)
     return id(dialog)
예제 #8
0
import xbmc
import xbmcgui

from . import scraper

DIALOG_PROGRESS = xbmcgui.DialogProgress()

try:
    DIALOG_PROGRESS.create("TouTV", "Refresh all emissions...")
    xbmc.sleep(1000)
    #while xbmc.( 'Dialog.Close(10101)' )
    scraper.refreshAllEmissions(DIALOG_PROGRESS)
except:
    pass

xbmc.executebuiltin('Dialog.Close(10101)')
#try: DIALOG_PROGRESS.close()
#except: pass

xbmc.executebuiltin('Container.Refresh')
def auto_install_repo():
    if not os.path.exists(os.path.join(CONFIG.ADDONS, CONFIG.REPOID)):
        response = tools.open_url(CONFIG.REPOADDONXML)

        if response:
            from xml.etree import ElementTree

            root = ElementTree.fromstring(response.text)
            repoaddon = root.findall('addon')
            repoversion = [
                tag.get('version') for tag in repoaddon
                if tag.get('id') == CONFIG.REPOID
            ]

            if repoversion:
                installzip = '{0}-{1}.zip'.format(CONFIG.REPOID,
                                                  repoversion[0])
                url = CONFIG.REPOZIPURL + installzip
                repo_response = tools.open_url(url, check=True)

                if repo_response:
                    progress_dialog = xbmcgui.DialogProgress()

                    progress_dialog.create(CONFIG.ADDONTITLE,
                                           'Downloading Repo...', '',
                                           'Please Wait')
                    tools.ensure_folders(CONFIG.PACKAGES)
                    lib = os.path.join(CONFIG.PACKAGES, installzip)

                    # Remove the old zip if there is one
                    tools.remove_file(lib)

                    from resources.libs.downloader import Downloader
                    from resources.libs import extract
                    Downloader().download(url, lib)
                    extract.all(lib, CONFIG.ADDONS)

                    try:
                        repoxml = os.path.join(CONFIG.ADDONS, CONFIG.REPOID,
                                               'addon.xml')
                        root = ElementTree.parse(repoxml).getroot()
                        reponame = root.get('name')

                        logging.log_notify(
                            "{1}".format(CONFIG.COLOR1, reponame),
                            "[COLOR {0}]Add-on updated[/COLOR]".format(
                                CONFIG.COLOR2),
                            icon=os.path.join(CONFIG.ADDONS, CONFIG.REPOID,
                                              'icon.png'))

                    except Exception as e:
                        logging.log(str(e), level=xbmc.LOGERROR)

                    # Add wizard to add-on database
                    db.addon_database(CONFIG.REPOID, 1)

                    progress_dialog.close()
                    xbmc.sleep(500)

                    logging.log("[Auto Install Repo] Successfully Installed",
                                level=xbmc.LOGNOTICE)
                else:
                    logging.log_notify(
                        "[COLOR {0}]Repo Install Error[/COLOR]".format(
                            CONFIG.COLOR1),
                        "[COLOR {0}]Invalid URL for zip![/COLOR]".format(
                            CONFIG.COLOR2))
                    logging.log(
                        "[Auto Install Repo] Was unable to create a working URL for repository. {0}"
                        .format(url),
                        level=xbmc.LOGERROR)
            else:
                logging.log("Invalid URL for Repo zip", level=xbmc.LOGERROR)
        else:
            logging.log_notify(
                "[COLOR {0}]Repo Install Error[/COLOR]".format(CONFIG.COLOR1),
                "[COLOR {0}]Invalid addon.xml file![/COLOR]".format(
                    CONFIG.COLOR2))
            logging.log(
                "[Auto Install Repo] Unable to read the addon.xml file.",
                level=xbmc.LOGERROR)
    elif not CONFIG.AUTOINSTALL == 'Yes':
        logging.log("[Auto Install Repo] Not Enabled", level=xbmc.LOGNOTICE)
    elif os.path.exists(os.path.join(CONFIG.ADDONS, CONFIG.REPOID)):
        logging.log("[Auto Install Repo] Repository already installed")
예제 #10
0
def HELPWIZARD(name, url, description, filetype):
    path = xbmc.translatePath(
        os.path.join('special://home', 'addons', 'packages'))
    confirm = xbmcgui.Dialog().yesno(
        "Please Confirm",
        "                Please confirm that you wish to automatically                     ",
        "            configure Kodi with all the best addons and tweaks!",
        "              ", "Cancel", "Install")
    filetype = filetype.lower()
    if confirm:
        path = xbmc.translatePath(
            os.path.join('special://home', 'addons', 'packages'))
        dp = xbmcgui.DialogProgress()
        dp.create(AddonTitle, " ", 'Downloading and Configuring ',
                  'Please Wait')
        lib = os.path.join(path, name + '.zip')
        try:
            os.remove(lib)
        except:
            pass
        ### ## ... ##
        # kodi.log(url)
        if str(url).endswith('[error]'):
            print url
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", url)
            return
        if '[error]' in url:
            print url
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", url)
            return
        downloader.download(url, lib, dp)
        if filetype == 'main':
            addonfolder = xbmc.translatePath('special://home')
        elif filetype == 'addon':
            addonfolder = xbmc.translatePath(
                os.path.join('special://home', 'addons'))
        else:
            print {'filetype': filetype}
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", 'filetype: "%s"' % str(filetype))
            return
        xbmc.sleep(4000)
        extract.all(lib, addonfolder, dp)
        xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
        addon_able.setall_enable()
        try:
            os.remove(lib)
        except:
            pass
        if filetype == 'main':
            link = OPEN_URL(cutslink)
            shorts = re.compile('shortcut="(.+?)"').findall(link)
            for shortname in shorts:
                xEB('Skin.SetString(%s)' % shortname)
                enableBG16 = "UseCustomBackground,true"
                enableBG17 = "use_custom_bg,true"
                xEB('Skin.SetBool(%s)' % enableBG16)
                xEB('Skin.SetBool(%s)' % enableBG17)

        xbmc.sleep(4000)
        xbmc.executebuiltin('XBMC_UpdateLocalAddons()')
        addon_able.setall_enable()

        kodi.set_setting("wizardran", 'true')

        dialog = xbmcgui.Dialog()
        dialog.ok(TeamName, "Installation Complete!", "",
                  "Click OK to exit Kodi and then restart to complete .")
        xbmc.executebuiltin('ShutDown')
예제 #11
0
def auto(url, dest, dp=None):
    dp = xbmcgui.DialogProgress()
    start_time = time.time()
    urlretrieve(url, dest,
                lambda nb, bs, fs: _pbhookauto(nb, bs, fs, dp, start_time))
예제 #12
0
def check_server(force=False, change_user=False, notify=False):
    log.debug("checkServer Called")

    settings = xbmcaddon.Addon()
    something_changed = False

    # Initialize api object
    api = API()

    if force is False:
        # if not forcing use server details from settings
        api.server = settings.getSetting('server_address')

    # if the server is not set then try to detect it
    if not api.server:

        # scan for local server
        server_info = get_server_details()

        addon = xbmcaddon.Addon()
        server_icon = addon.getAddonInfo('icon')

        server_list = []
        for server in server_info:
            server_item = xbmcgui.ListItem(
                server.get("Name", translate_string(30063)))
            sub_line = server.get("Address")
            server_item.setLabel2(sub_line)
            server_item.setProperty("address", server.get("Address"))
            art = {"Thumb": server_icon}
            server_item.setArt(art)
            server_list.append(server_item)

        if len(server_list) > 0:
            return_index = xbmcgui.Dialog().select('{} : {}'.format(
                __addon_name__, translate_string(30166)),
                                                   server_list,
                                                   useDetails=True)
            if return_index != -1:
                api.server = server_info[return_index]["Address"]

        if not api.server:
            return_index = xbmcgui.Dialog().yesno(
                __addon_name__, '{}\n{}'.format(translate_string(30282),
                                                translate_string(30370)))
            if not return_index:
                xbmc.executebuiltin("ActivateWindow(Home)")
                return

            while True:
                kb = xbmc.Keyboard()
                kb.setHeading(translate_string(30372))
                if api.server:
                    kb.setDefault(api.server)
                else:
                    kb.setDefault("http://")
                kb.doModal()
                if kb.isConfirmed():
                    api.server = kb.getText()
                else:
                    xbmc.executebuiltin("ActivateWindow(Home)")
                    return

                progress = xbmcgui.DialogProgress()
                progress.create('{} : {}'.format(__addon_name__,
                                                 translate_string(30376)))
                progress.update(0, translate_string(30377))
                result = api.get('/System/Info/Public')
                progress.close()

                if result:
                    xbmcgui.Dialog().ok(
                        '{} : {}'.format(__addon_name__,
                                         translate_string(30167)), api.server)
                    break
                else:
                    return_index = xbmcgui.Dialog().yesno(
                        '{} : {}'.format(__addon_name__,
                                         translate_string(30135)), api.server,
                        translate_string(30371))
                    if not return_index:
                        xbmc.executebuiltin("ActivateWindow(Home)")
                        return

        log.debug("Selected server: {0}".format(api.server))
        settings.setSetting("server_address", api.server)
        something_changed = True

    # do we need to change the user
    current_username = settings.getSetting('username')
    user_details = load_user_details()

    # if asked or we have no current user then show user selection screen
    if something_changed or change_user or len(
            current_username) == 0 or not user_details:

        # stop playback when switching users
        xbmc.Player().stop()

        auth = quick_connect(api)

        if auth:
            users = []
            user_selection = -1
            selected_user_name = auth.get('User', {}).get('Name')
            something_changed = True
        else:
            users, user_selection = user_select(api, current_username)

        if not auth and user_selection > -1:

            something_changed = True
            selected_user = users[user_selection]
            selected_user_name = selected_user.getLabel()
            secured = selected_user.getProperty("secure") == "true"
            manual = selected_user.getProperty("manual") == "true"

            home_window = HomeWindow()

            # If using a manual login, ask for username
            if manual:
                kb = xbmc.Keyboard()
                kb.setHeading(translate_string(30005))
                if current_username:
                    kb.setDefault(current_username)
                kb.doModal()
                if kb.isConfirmed():
                    selected_user_name = kb.getText()
                    log.debug("Manual entered username: {0}".format(
                        selected_user_name))
                else:
                    return

            home_window.set_property('user_name', selected_user_name)
            user_details = load_user_details()

            # Ask for password if user has one
            password = ''
            if secured and not user_details.get('token'):
                kb = xbmc.Keyboard()
                kb.setHeading(translate_string(30006))
                kb.setHiddenInput(True)
                kb.doModal()
                if kb.isConfirmed():
                    password = kb.getText()

            auth_payload = {'username': selected_user_name, 'pw': password}
            auth = api.authenticate(auth_payload)

        if something_changed:
            home_window = HomeWindow()
            home_window.clear_property("jellycon_widget_reload")
            token = auth.get('AccessToken')
            user_id = auth.get('User').get('Id')
            save_user_details(selected_user_name, user_id, token)
            xbmc.executebuiltin("ActivateWindow(Home)")
            if "estuary_jellycon" in xbmc.getSkinDir():
                xbmc.executebuiltin("SetFocus(9000, 0, absolute)")
            xbmc.executebuiltin("ReloadSkin()")
예제 #13
0
def resolve_video_urls_for_playing(server,
                                   url,
                                   video_password="",
                                   muestra_dialogo=False):
    logger.info("[servertools.py] resolve_video_urls_for_playing, server=" +
                server + ", url=" + url)
    video_urls = []
    torrent = False

    server = server.lower()

    # Si el vídeo es "directo", no hay que buscar más
    if server == "directo" or server == "local":
        logger.info("[servertools.py] server=directo, la url es la buena")

        try:
            import urlparse
            parsed_url = urlparse.urlparse(url)
            logger.info("parsed_url=" + str(parsed_url))
            extension = parsed_url.path[-4:]
        except:
            extension = url[-4:]

        video_urls = [["%s [%s]" % (extension, server), url]]
        return video_urls, True, ""

    # Averigua las URL de los vídeos
    else:

        #if server=="torrent":
        #    server="filenium"
        #    torrent = True

        # Carga el conector
        try:
            # Muestra un diálogo de progreso
            if muestra_dialogo:
                import xbmcgui
                progreso = xbmcgui.DialogProgress()
                progreso.create("pelisalacarta", "Conectando con " + server)

            # Sustituye el código por otro "Plex compatible"
            #exec "from servers import "+server+" as server_connector"
            servers_module = __import__("servers." + server)
            server_connector = getattr(servers_module, server)

            logger.info("[servertools.py] servidor de " + server +
                        " importado")
            if muestra_dialogo:
                progreso.update(20, "Conectando con " + server)

            # Si tiene una función para ver si el vídeo existe, lo comprueba ahora
            if hasattr(server_connector, 'test_video_exists'):
                logger.info("[servertools.py] invocando a " + server +
                            ".test_video_exists")
                puedes, motivo = server_connector.test_video_exists(
                    page_url=url)

                # Si la funcion dice que no existe, fin
                if not puedes:
                    logger.info(
                        "[servertools.py] test_video_exists dice que el video no existe"
                    )
                    if muestra_dialogo: progreso.close()
                    return video_urls, puedes, motivo
                else:
                    logger.info(
                        "[servertools.py] test_video_exists dice que el video SI existe"
                    )

            # Obtiene enlaces free
            if server in FREE_SERVERS:
                logger.info("[servertools.py] invocando a " + server +
                            ".get_video_url")
                video_urls = server_connector.get_video_url(
                    page_url=url, video_password=video_password)

                # Si no se encuentran vídeos en modo free, es porque el vídeo no existe
                if len(video_urls) == 0:
                    if muestra_dialogo: progreso.close()
                    return video_urls, False, "No se puede encontrar el vídeo en " + server

            # Obtiene enlaces premium si tienes cuenta en el server
            if server in PREMIUM_SERVERS and config.get_setting(
                    server + "premium") == "true":
                video_urls = server_connector.get_video_url(
                    page_url=url,
                    premium=(config.get_setting(server + "premium") == "true"),
                    user=config.get_setting(server + "user"),
                    password=config.get_setting(server + "password"),
                    video_password=video_password)

                # Si no se encuentran vídeos en modo premium directo, es porque el vídeo no existe
                if len(video_urls) == 0:
                    if muestra_dialogo: progreso.close()
                    return video_urls, False, "No se puede encontrar el vídeo en " + server

            # Obtiene enlaces filenium si tienes cuenta
            if server in FILENIUM_SERVERS and config.get_setting(
                    "fileniumpremium") == "true":

                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update(40, "Conectando con Filenium")

                from servers import filenium as gen_conector

                video_gen = gen_conector.get_video_url(
                    page_url=url,
                    premium=(config.get_setting("fileniumpremium") == "true"),
                    user=config.get_setting("fileniumuser"),
                    password=config.get_setting("fileniumpassword"),
                    video_password=video_password)
                extension = gen_conector.get_file_extension(video_gen)
                logger.info("[xbmctools.py] filenium url=" + video_gen)
                video_urls.append(
                    [extension + " [" + server + "][filenium]", video_gen])

            # Obtiene enlaces realdebrid si tienes cuenta
            if server in REALDEBRID_SERVERS and config.get_setting(
                    "realdebridpremium") == "true":

                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update(60, "Conectando con Real-Debrid")

                from servers import realdebrid as gen_conector
                video_gen = gen_conector.get_video_url(
                    page_url=url,
                    premium=(
                        config.get_setting("realdebridpremium") == "true"),
                    user=config.get_setting("realdebriduser"),
                    password=config.get_setting("realdebridpassword"),
                    video_password=video_password)
                logger.info("[xbmctools.py] realdebrid url=" + video_gen)
                if not "REAL-DEBRID" in video_gen:
                    video_urls.append([
                        "." + video_gen.rsplit('.', 1)[1] + " [realdebrid]",
                        video_gen
                    ])
                else:
                    if muestra_dialogo: progreso.close()
                    # Si RealDebrid da error pero tienes un enlace válido, no te dice nada
                    if len(video_urls) == 0:
                        return video_urls, False, video_gen

            # Obtiene enlaces alldebrid si tienes cuenta
            if server in ALLDEBRID_SERVERS and config.get_setting(
                    "alldebridpremium") == "true":

                # Muestra un diálogo de progreso
                if muestra_dialogo:
                    progreso.update(80, "Conectando con All-Debrid")

                from servers import alldebrid as gen_conector
                video_gen = gen_conector.get_video_url(
                    page_url=url,
                    premium=(config.get_setting("alldebridpremium") == "true"),
                    user=config.get_setting("alldebriduser"),
                    password=config.get_setting("alldebridpassword"),
                    video_password=video_password)
                logger.info("[xbmctools.py] alldebrid url=" + video_gen)
                if video_gen.startswith("http"):
                    video_urls.append([
                        "." + video_gen.rsplit('.', 1)[1] + " [alldebrid]",
                        video_gen
                    ])
                else:
                    # Si Alldebrid da error pero tienes un enlace válido, no te dice nada
                    if len(video_urls) == 0:
                        return [], False, video_gen.strip()

            if muestra_dialogo:
                progreso.update(100, "Proceso finalizado")

            # Cierra el diálogo de progreso
            if muestra_dialogo: progreso.close()

            # Llegas hasta aquí y no tienes ningún enlace para ver, así que no vas a poder ver el vídeo
            if len(video_urls) == 0:
                # ¿Cual es el motivo?

                # 1) No existe -> Ya está controlado
                # 2) No tienes alguna de las cuentas premium compatibles

                # Lista de las cuentas que soportan este servidor
                listapremium = ""
                if server in ALLDEBRID_SERVERS: listapremium += "All-Debrid o "
                if server in FILENIUM_SERVERS: listapremium += "Filenium o "
                if server in REALDEBRID_SERVERS:
                    listapremium += "Real-Debrid o "
                if server in PREMIUM_SERVERS: listapremium += server + " o "
                listapremium = listapremium[:-3]

                return video_urls, False, "Para ver un vídeo en " + server + " necesitas<br/>una cuenta en " + listapremium

        except:
            if muestra_dialogo: progreso.close()
            import traceback
            from pprint import pprint
            exc_type, exc_value, exc_tb = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_tb)
            for line in lines:
                line_splits = line.split("\n")
                for line_split in line_splits:
                    logger.error(line_split)

            return video_urls, False, "Se ha producido un error en<br/>el conector con " + server

    return video_urls, True, ""
예제 #14
0
def download(url, dest, dp=None):
    if not dp:
        dp = xbmcgui.DialogProgress()
    urllib.urlretrieve(
        url, dest, lambda nb, bs, fs, url=url: _pbhook(nb, bs, fs, url, dp))
예제 #15
0
def start_casting(chromecast_name):
    """
    Start casting to the Chromecast with the given friendly name
    :param chromecast_name: friendly name of selected Chromecast
    :type chromecast_name: str
    :return: None
    """
    chromecasts = pychromecast.get_chromecasts()
    progress_dialog = xbmcgui.DialogProgress()
    progress_dialog.create("Connecting to " + chromecast_name + "...")
    cast = next(cc for cc in chromecasts
                if cc.device.friendly_name == chromecast_name)
    if not cast:
        error("Couldn't connect to " + chromecast_name)
        return
    cast.wait()
    player = xbmc.Player()
    url = player.getPlayingFile()
    if '|Referer' in url:
        print(url.split('|Referer')[0])
        url = url.split('|Referer')[0]
    debug("url: " + url)
    url = transform_url(url)
    debug("transformed url: " + str(url))
    if not url:
        return
    content_type, encoding = mimetypes.guess_type(url)
    if not content_type:
        content_type = get_content_type(url)
    debug("content_type: " + str(content_type))
    title = get_playing_title()  #xbmc.getInfoLabel("Player.Title")
    thumb = xbmc.getInfoLabel("Player.Art(thumb)")
    thumb_url = transform_url(thumb, show_warnings=False)
    debug("thumb_url: " + str(thumb_url))
    metadata = {
        'metadataType': 0,
        'title': title,
        'images': [{
            'url': thumb_url
        }]
    }
    livetv = xbmc.getCondVisibility("VideoPlayer.Content(livetv)")
    if not xbmc.getCondVisibility("Player.Paused()"):
        player.pause()
    current_time = parse_time(xbmc.getInfoLabel("Player.Time(hh:mm:ss)"))
    debug("current_time: " + str(current_time))
    cast.media_controller.play_media(url,
                                     content_type,
                                     current_time=current_time,
                                     metadata=metadata)
    progress_dialog.close()
    window_title = "Casting " + title

    debug("livetv: " + str(livetv))
    show_seekbar = not livetv
    total_time = parse_time(xbmc.getInfoLabel("Player.Duration(hh:mm:ss)"))
    debug("total_time: " + str(total_time))
    if total_time:
        percentage = current_time / total_time * 100
    else:
        percentage = 0
    cast_controls_dialog = CastControlsDialog(title=window_title,
                                              cast=cast,
                                              thumb=thumb,
                                              show_seekbar=show_seekbar,
                                              percentage=percentage)
    cast_controls_dialog.doModal()
    try:
        cast.media_controller.stop()
    except Exception, e:
        log_exception("Couldn't stop casting")
        log_exception(str(e))
예제 #16
0
def check_server(force=False, change_user=False, notify=False):
    log.debug("checkServer Called")

    settings = xbmcaddon.Addon()
    server_url = ""
    something_changed = False
    du = DownloadUtils()

    if force is False:
        # if not forcing use server details from settings
        svr = du.get_server()
        if svr is not None:
            server_url = svr

    # if the server is not set then try to detect it
    if server_url == "":

        # scan for local server
        server_info = get_server_details()

        addon = xbmcaddon.Addon()
        server_icon = addon.getAddonInfo('icon')

        server_list = []
        for server in server_info:
            server_item = xbmcgui.ListItem(
                server.get("Name", string_load(30063)))
            sub_line = server.get("Address")
            server_item.setLabel2(sub_line)
            server_item.setProperty("address", server.get("Address"))
            art = {"Thumb": server_icon}
            server_item.setArt(art)
            server_list.append(server_item)

        if len(server_list) > 0:
            return_index = xbmcgui.Dialog().select('{} : {}'.format(
                __addon_name__, string_load(30166)),
                                                   server_list,
                                                   useDetails=True)
            if return_index != -1:
                server_url = server_info[return_index]["Address"]

        if not server_url:
            return_index = xbmcgui.Dialog().yesno(
                __addon_name__, '{}\n{}'.format(string_load(30282),
                                                string_load(30370)))
            if not return_index:
                xbmc.executebuiltin("ActivateWindow(Home)")
                return

            while True:
                kb = xbmc.Keyboard()
                kb.setHeading(string_load(30372))
                if server_url:
                    kb.setDefault(server_url)
                else:
                    kb.setDefault("http://<server address>:8096")
                kb.doModal()
                if kb.isConfirmed():
                    server_url = kb.getText()
                else:
                    xbmc.executebuiltin("ActivateWindow(Home)")
                    return

                public_lookup_url = "%s/System/Info/Public?format=json" % (
                    server_url)

                log.debug("Testing_Url: {0}".format(public_lookup_url))
                progress = xbmcgui.DialogProgress()
                progress.create('{} : {}'.format(__addon_name__,
                                                 string_load(30376)))
                progress.update(0, string_load(30377))
                result = du.download_url(public_lookup_url, authenticate=False)
                progress.close()

                if result:
                    xbmcgui.Dialog().ok(
                        '{} : {}'.format(__addon_name__, string_load(30167)),
                        server_url)
                    break
                else:
                    return_index = xbmcgui.Dialog().yesno(
                        '{} : {}'.format(__addon_name__, string_load(30135)),
                        server_url, string_load(30371))
                    if not return_index:
                        xbmc.executebuiltin("ActivateWindow(Home)")
                        return

        log.debug("Selected server: {0}".format(server_url))
        settings.setSetting("server_address", server_url)
        something_changed = True

    # do we need to change the user
    user_details = load_user_details(settings)
    current_username = user_details.get("username", "")
    current_username = py2_decode(current_username)

    # if asked or we have no current user then show user selection screen
    if something_changed or change_user or len(current_username) == 0:

        # stop playback when switching users
        xbmc.Player().stop()
        du = DownloadUtils()

        # get a list of users
        log.debug("Getting user list")
        result = du.download_url(server_url + "/Users/Public?format=json",
                                 authenticate=False)

        log.debug("jsonData: {0}".format(py2_decode(result)))

        selected_id = -1
        users = []
        for user in result:
            config = user.get("Configuration")
            if config is not None:
                if config.get("IsHidden", False) is False:
                    name = user.get("Name")
                    admin = user.get("Policy", {}).get("IsAdministrator",
                                                       False)

                    time_ago = ""
                    last_active = user.get("LastActivityDate")
                    if last_active:
                        last_active_date = datetime_from_string(last_active)
                        log.debug(
                            "LastActivityDate: {0}".format(last_active_date))
                        ago = datetime.now() - last_active_date
                        log.debug("LastActivityDate: {0}".format(ago))
                        days = divmod(ago.seconds, 86400)
                        hours = divmod(days[1], 3600)
                        minutes = divmod(hours[1], 60)
                        log.debug("LastActivityDate: {0} {1} {2}".format(
                            days[0], hours[0], minutes[0]))
                        if days[0]:
                            time_ago += " %sd" % days[0]
                        if hours[0]:
                            time_ago += " %sh" % hours[0]
                        if minutes[0]:
                            time_ago += " %sm" % minutes[0]
                        time_ago = time_ago.strip()
                        if not time_ago:
                            time_ago = "Active: now"
                        else:
                            time_ago = "Active: %s ago" % time_ago
                        log.debug("LastActivityDate: {0}".format(time_ago))

                    user_item = xbmcgui.ListItem(name)
                    user_image = du.get_user_artwork(user, 'Primary')
                    if not user_image:
                        user_image = "DefaultUser.png"
                    art = {"Thumb": user_image}
                    user_item.setArt(art)
                    user_item.setLabel2("TEST")

                    sub_line = time_ago

                    if user.get("HasPassword", False) is True:
                        sub_line += ", Password"
                        user_item.setProperty("secure", "true")

                        m = hashlib.md5()
                        m.update(ensure_binary(name))
                        hashed_username = m.hexdigest()
                        saved_password = settings.getSetting(
                            "saved_user_password_" + hashed_username)
                        if saved_password:
                            sub_line += ": Saved"

                    else:
                        user_item.setProperty("secure", "false")

                    if admin:
                        sub_line += ", Admin"
                    else:
                        sub_line += ", User"

                    user_item.setProperty("manual", "false")
                    user_item.setLabel2(sub_line)
                    users.append(user_item)

                    if current_username == name:
                        selected_id = len(users) - 1

        if current_username:
            selection_title = string_load(
                30180) + " (" + current_username + ")"
        else:
            selection_title = string_load(30180)

        # add manual login
        user_item = xbmcgui.ListItem(string_load(30365))
        art = {"Thumb": "DefaultUser.png"}
        user_item.setArt(art)
        user_item.setLabel2(string_load(30366))
        user_item.setProperty("secure", "true")
        user_item.setProperty("manual", "true")
        users.append(user_item)

        return_value = xbmcgui.Dialog().select(selection_title,
                                               users,
                                               preselect=selected_id,
                                               autoclose=20000,
                                               useDetails=True)

        if return_value > -1 and return_value != selected_id:

            something_changed = True
            selected_user = users[return_value]
            secured = selected_user.getProperty("secure") == "true"
            manual = selected_user.getProperty("manual") == "true"
            selected_user_name = selected_user.getLabel()

            log.debug("Selected User Name: {0} : {1}".format(
                return_value, selected_user_name))

            if manual:
                kb = xbmc.Keyboard()
                kb.setHeading(string_load(30005))
                if current_username:
                    kb.setDefault(current_username)
                kb.doModal()
                if kb.isConfirmed():
                    selected_user_name = kb.getText()
                    log.debug("Manual entered username: {0}".format(
                        selected_user_name))
                else:
                    return

            if secured:
                # we need a password, check the settings first
                m = hashlib.md5()
                m.update(selected_user_name.encode())
                hashed_username = m.hexdigest()
                saved_password = settings.getSetting("saved_user_password_" +
                                                     hashed_username)
                allow_password_saving = settings.getSetting(
                    "allow_password_saving") == "true"

                # if not saving passwords but have a saved ask to clear it
                if not allow_password_saving and saved_password:
                    clear_password = xbmcgui.Dialog().yesno(
                        string_load(30368), string_load(30369))
                    if clear_password:
                        settings.setSetting(
                            "saved_user_password_" + hashed_username, "")

                if saved_password:
                    log.debug("Saving username and password: {0}".format(
                        selected_user_name))
                    log.debug("Using stored password for user: {0}".format(
                        hashed_username))
                    save_user_details(settings, selected_user_name,
                                      saved_password)

                else:
                    kb = xbmc.Keyboard()
                    kb.setHeading(string_load(30006))
                    kb.setHiddenInput(True)
                    kb.doModal()
                    if kb.isConfirmed():
                        log.debug("Saving username and password: {0}".format(
                            selected_user_name))
                        save_user_details(settings, selected_user_name,
                                          kb.getText())

                        # should we save the password
                        if allow_password_saving:
                            save_password = xbmcgui.Dialog().yesno(
                                string_load(30363), string_load(30364))
                            if save_password:
                                log.debug(
                                    "Saving password for fast user switching: {0}"
                                    .format(hashed_username))
                                settings.setSetting(
                                    "saved_user_password_" + hashed_username,
                                    kb.getText())
            else:
                log.debug("Saving username with no password: {0}".format(
                    selected_user_name))
                save_user_details(settings, selected_user_name, "")

        if something_changed:
            home_window = HomeWindow()
            home_window.clear_property("userid")
            home_window.clear_property("AccessToken")
            home_window.clear_property("userimage")
            home_window.clear_property("embycon_widget_reload")
            du = DownloadUtils()
            du.authenticate()
            du.get_user_id()
            xbmc.executebuiltin("ActivateWindow(Home)")
            if "estuary_embycon" in xbmc.getSkinDir():
                xbmc.executebuiltin("SetFocus(9000, 0, absolute)")
            xbmc.executebuiltin("ReloadSkin()")
예제 #17
0
def extract_file(filename, extract, destination, silent=False):
    try:
        if tarfile.is_tarfile(filename):
            if silent == False:
                extract_dlg = xbmcgui.DialogProgress()
                extract_dlg.create('LibreELEC ',
                                   _(32186).encode('utf-8'), ' ', ' ')
                extract_dlg.update(0)
            compressed = tarfile.open(filename)
            if silent == False:
                xbmc.executebuiltin('ActivateWindow(busydialog)')
            names = compressed.getnames()
            if silent == False:
                xbmc.executebuiltin('Dialog.Close(busydialog)')
            for name in names:
                for search in extract:
                    if search in name:
                        fileinfo = compressed.getmember(name)
                        response = compressed.extractfile(fileinfo)
                        local_file = open(destination + name.rsplit('/', 1)[1],
                                          'wb')
                        total_size = fileinfo.size
                        minutes = 0
                        seconds = 0
                        rest = 1
                        speed = 1
                        start = time.time()
                        size = 1
                        part_size = 1
                        last_percent = 0
                        while 1:
                            part = response.read(32768)
                            part_size += len(part)
                            if silent == False:
                                if extract_dlg.iscanceled():
                                    local_file.close()
                                    response.close()
                                    return None
                            if not part or xbmc.abortRequested:
                                break
                            if time.time() > start + 2:
                                speed = int((part_size - size) /
                                            (time.time() - start) / 1024)
                                start = time.time()
                                size = part_size
                                rest = total_size - part_size
                                minutes = rest / 1024 / speed / 60
                                seconds = rest / 1024 / speed - minutes * 60
                            percent = int(part_size * 100.0 / total_size)
                            if silent == False:
                                extract_dlg.update(
                                    percent,
                                    _(32184) +
                                    ':  %s' % name.rsplit('/', 1)[1],
                                    _(32185) + ':  %d KB/s' % speed,
                                    _(32183) + ':  %d m %d s' %
                                    (minutes, seconds))
                                if extract_dlg.iscanceled():
                                    local_file.close()
                                    response.close()
                                    return None
                            else:
                                if percent > last_percent + 5:
                                    dbg_log(
                                        'oe::extract_file(' + destination +
                                        name.rsplit('/', 1)[1] + ')',
                                        '%d percent with %d KB/s' %
                                        (percent, speed))
                                    last_percent = percent
                            local_file.write(part)
                        local_file.close()
                        response.close()
        return 1
    except Exception, e:
        dbg_log('oe::extract_file', 'ERROR: (' + repr(e) + ')')
예제 #18
0
def check_connection_speed():
    log.debug("check_connection_speed")

    settings = xbmcaddon.Addon()
    verify_cert = settings.getSetting('verify_cert') == 'true'
    http_timeout = int(settings.getSetting("http_timeout"))
    speed_test_data_size = int(settings.getSetting("speed_test_data_size"))
    test_data_size = speed_test_data_size * 1000000

    du = DownloadUtils()
    server = du.get_server()

    url = server + "/playback/bitratetest?size=%s" % test_data_size

    head = du.get_auth_header(True)
    head["User-Agent"] = "embycon-" + ClientInformation().get_version()

    request_details = {"stream": True, "headers": head}

    if not verify_cert:
        request_details["verify"] = False

    progress_dialog = xbmcgui.DialogProgress()
    message = 'Testing with {0} MB of data'.format(speed_test_data_size)
    progress_dialog.create("embycon connection speed test", message)
    start_time = time.time()

    log.debug("Starting Connection Speed Test")

    response = requests.get(url, **request_details)

    last_percentage_done = 0
    total_data_read = 0
    if response.status_code == 200:
        for data in response.iter_content(chunk_size=10240):
            total_data_read += len(data)
            percentage_done = int(
                float(total_data_read) / float(test_data_size) * 100.0)
            if last_percentage_done != percentage_done:
                progress_dialog.update(percentage_done)
                last_percentage_done = percentage_done
    else:
        log.error("HTTP response error: {0} {1}".format(
            response.status_code, response.content))
        error_message = "HTTP response error: %s\n%s" % (response.status_code,
                                                         response.content)
        xbmcgui.Dialog().ok("Speed Test Error", error_message)
        return -1

    total_data_read_kbits = (total_data_read * 8) / 1000
    total_time = time.time() - start_time
    speed = int(total_data_read_kbits / total_time)
    log.debug(
        "Finished Connection Speed Test, speed: {0} total_data: {1}, total_time: {2}"
        .format(speed, total_data_read, total_time))

    progress_dialog.close()
    del progress_dialog

    heading = "Speed Test Result : {0:,} Kbs".format(speed)
    message = "Do you want to set this speed as your max stream bitrate for playback?\n"
    message += "{0:,} MB over {1} sec".format(int((total_data_read / 1000000)),
                                              total_time)

    response = xbmcgui.Dialog().yesno(heading, message)
    if response:
        settings.setSetting("max_stream_bitrate", str(speed))

    return speed
예제 #19
0
 def remove(self, file_):
     dp = xbmcgui.DialogProgress()
     dp.create(translate(40000), translate(40045))
     os.remove(file_)
     dp.update(100)
     dp.close()
예제 #20
0
while idx < len(sys.argv):
    args = sys.argv[idx].split('=')
    parameters[args[0]] = args[1]
    idx += 1

if (parameters['action'] == "none"):
    # No action parameter, so must be run from programs thingy.
    # Lets show presets
    parameters['action'] = "showpresets"


    
if (parameters['action'] == "connect_to_bridge"):
    
    progress = xbmcgui.DialogProgress()
    progress.create(__language__(30007), __language__(30008))
    progress.update(0)
    
    bridges = hue.BridgeLocator(iprange=xbmc.getIPAddress(), logfunc=logDebug).FindBridges(progress=progress.update)
    bridgeidx = -1;
    
    progress.close();
    
    if (len(bridges) == 0):
        xbmcgui.Dialog().ok(__language__(30009), __language__(30010)) 
    elif (len(bridges) == 1):
        # Only one bridge, done
        bridgeidx = 0
        bridge = bridges[bridgeidx]
        xbmccommon.notify(__language__(30011).format(bridge.name)) # Keep output on one line. Name is name + IP e.g. Philips hue (111.112.113.114)
예제 #21
0
def download_media(url, path, file_name):
    try:
        progress = int(kodi.get_setting('down_progress'))
        request = urllib2.Request(url)
        request.add_header('User-Agent', USER_AGENT)
        request.add_unredirected_header('Host', request.get_host())
        response = urllib2.urlopen(request)

        content_length = 0
        if 'Content-Length' in response.info():
            content_length = int(response.info()['Content-Length'])

        file_name = file_name.replace('.strm', get_extension(url, response))
        full_path = os.path.join(path, file_name)
        log_utils.log('Downloading: %s -> %s' % (url, full_path),
                      log_utils.LOGDEBUG)

        path = xbmc.makeLegalFilename(path)
        if not xbmcvfs.exists(path):
            try:
                try:
                    xbmcvfs.mkdirs(path)
                except:
                    os.mkdir(path)
            except Exception as e:
                raise Exception(i18n('failed_create_dir'))

        file_desc = xbmcvfs.File(full_path, 'w')
        total_len = 0
        if progress:
            if progress == PROGRESS.WINDOW:
                dialog = xbmcgui.DialogProgress()
            else:
                dialog = xbmcgui.DialogProgressBG()

            dialog.create('Stream All The Sources',
                          i18n('downloading') % (file_name))
            dialog.update(0)
        while True:
            data = response.read(CHUNK_SIZE)
            if not data:
                break

            if progress == PROGRESS.WINDOW and dialog.iscanceled():
                break

            total_len += len(data)
            if not file_desc.write(data):
                raise Exception('failed_write_file')

            percent_progress = (
                total_len) * 100 / content_length if content_length > 0 else 0
            log_utils.log(
                'Position : %s / %s = %s%%' %
                (total_len, content_length, percent_progress),
                log_utils.LOGDEBUG)
            if progress == PROGRESS.WINDOW:
                dialog.update(percent_progress)
            elif progress == PROGRESS.BACKGROUND:
                dialog.update(percent_progress, 'Stream All The Sources')
        else:
            kodi.notify(msg=i18n('download_complete') % (file_name),
                        duration=5000)
            log_utils.log('Download Complete: %s -> %s' % (url, full_path),
                          log_utils.LOGDEBUG)

        file_desc.close()
        if progress:
            dialog.close()

    except Exception as e:
        log_utils.log(
            'Error (%s) during download: %s -> %s' % (str(e), url, file_name),
            log_utils.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name),
                    duration=5000)
예제 #22
0
def bridgeDiscover(monitor):
    logger.debug("Start bridgeDiscover")
    # Create new config if none exists. Returns success or fail as bool
    ADDON.setSettingString("bridgeIP", "")
    ADDON.setSettingString("bridgeUser", "")
    settings_storage['connected'] = False

    progressBar = xbmcgui.DialogProgress()
    progressBar.create(_('Searching for bridge...'))
    progressBar.update(5, _("Discovery started"))

    complete = False
    while not progressBar.iscanceled() and not complete:

        progressBar.update(10, _("N-UPnP discovery..."))
        bridgeIP = _discoverNupnp()
        if not bridgeIP:
            progressBar.update(20, _("UPnP discovery..."))
            bridgeIP = _discoverSsdp()

        if connectionTest(bridgeIP):
            progressBar.update(100, _("Found bridge: ") + bridgeIP)
            monitor.waitForAbort(1)

            bridgeUser = createUser(monitor, bridgeIP, progressBar)

            if bridgeUser:
                logger.debug("User created: {}".format(bridgeUser))
                progressBar.update(90, _("User Found!"), _("Saving settings"))

                ADDON.setSettingString("bridgeIP", bridgeIP)
                ADDON.setSettingString("bridgeUser", bridgeUser)
                complete = True
                settings_storage['connected'] = True
                progressBar.update(100, _("Complete!"))
                monitor.waitForAbort(5)
                progressBar.close()
                logger.debug("Bridge discovery complete")
                return True
            else:
                logger.debug(
                    "User not created, received: {}".format(bridgeUser))
                progressBar.update(100, _("User not found"),
                                   _("Check your bridge and network"))
                monitor.waitForAbort(5)
                complete = True

                progressBar.close()

        else:
            progressBar.update(100, _("Bridge not found"),
                               _("Check your bridge and network"))
            logger.debug("Bridge not found, check your bridge and network")
            monitor.waitForAbort(5)
            complete = True
            progressBar.close()

    if progressBar.iscanceled():
        logger.debug("Bridge discovery cancelled by user")
        progressBar.update(100, _("Cancelled"))
        complete = True
        progressBar.close()
예제 #23
0
def progressStart(title, status):
    pDialog = xbmcgui.DialogProgress()
    ret = pDialog.create(title, status)
    progressUpdate(pDialog, 1, status)
    return pDialog
    def end(self):
        self.log('end')
        # Prevent the player from setting the sleep timer
        self.Player.stopped = True
        self.background.setVisible(True)
        curtime = time.time()
        xbmc.executebuiltin("PlayerControl(repeatoff)")
        self.isExiting = True
        updateDialog = xbmcgui.DialogProgress()
        updateDialog.create("FurkTrailers", "Exiting")
        updateDialog.update(0, "Exiting", "Removing File Locks")


        if self.playerTimer.isAlive():
            self.playerTimer.cancel()
            self.playerTimer.join()

        if self.Player.isPlaying():
            self.lastPlayTime = self.Player.getTime()
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.Player.stop()

        updateDialog.update(1, "Exiting", "Stopping Threads")

        try:
            if self.channelLabelTimer.isAlive():
                self.channelLabelTimer.cancel()
                self.channelLabelTimer.join()
        except:
            pass

        updateDialog.update(2)

        try:
            if self.notificationTimer.isAlive():
                self.notificationTimer.cancel()
                self.notificationTimer.join()
        except:
            pass

        updateDialog.update(3)

        try:
            if self.infoTimer.isAlive():
                self.infoTimer.cancel()
                self.infoTimer.join()
        except:
            pass

        updateDialog.update(4)

        try:
            if self.sleepTimeValue > 0:
                if self.sleepTimer.isAlive():
                    self.sleepTimer.cancel()
        except:
            pass

        updateDialog.update(5)


        updateDialog.close()
        self.background.setVisible(False)
        self.close()
예제 #25
0
    transPath = xbmcvfs.translatePath
else:
    legalfilename = xbmc.makeLegalFilename
    transPath = xbmc.translatePath

skinPath = transPath('special://skin/')
addonPath = transPath(addonInfo('path'))

try:
    dataPath = transPath(addonInfo('profile')).decode('utf-8')
except AttributeError:
    dataPath = transPath(addonInfo('profile'))

window = xbmcgui.Window(10000)
dialog = xbmcgui.Dialog()
progressDialog = xbmcgui.DialogProgress()
progressDialogGB = xbmcgui.DialogProgressBG()
windowDialog = xbmcgui.WindowDialog()
button = xbmcgui.ControlButton
image = xbmcgui.ControlImage
alphanum_input = xbmcgui.INPUT_ALPHANUM
password_input = xbmcgui.INPUT_PASSWORD
hide_input = xbmcgui.ALPHANUM_HIDE_INPUT
verify = xbmcgui.PASSWORD_VERIFY
item = xbmcgui.ListItem

openFile = xbmcvfs.File
makeFile = xbmcvfs.mkdir
makeFiles = xbmcvfs.mkdirs
deleteFile = xbmcvfs.delete
deleteDir = xbmcvfs.rmdir
예제 #26
0
def xshare_trans(fs, fd):
    def trans(s):
        try:
            s = s.decode('unicode_escape') if '\\' in s else s.decode('utf-8')
        except:
            pass
        return s

    try:
        f = open(fs)
        b = f.read()
        f.close()
    except:
        b = ' '
    s = ''
    S = ''
    u = 'https://translate.googleapis.com/translate_a/single?ie=UTF-8&oe=UTF-8&client=gtx&sl=en&tl=vi&dt=t&q=%s'
    list_1 = b.splitlines()
    list_2 = []
    rows = len(list_1)
    row = 0
    hd = {
        'Referer': 'https://translate.google.com/',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.3) Chrome/49.0.2623.112 Safari/537.36',
        'Cookie': ''
    }
    progress = xbmcgui.DialogProgress()
    progress.create('Xshare Subtitles', 'Goolge translating ...')
    for i in list_1:
        row += 1
        if re.search('[a-zA-Z]', i):
            s = s + ' ' + i + ' xshare'
            list_2.append('xshare')
        else:
            list_2.append(i.strip())
        if len(s) > 1000 or row == rows:
            progress.update(
                row * 100 / rows,
                'Goolde Translate đang dịch từ tiếng Anh sang tiếng Việt')
            s = ' '.join(i for i in s.split())
            tran = urlfetch.get(u % urllib.quote(s), headers=hd)
            if not hd['Cookie']: hd['Cookie'] = tran.cookiestring
            xbmc.sleep(1000)
            try:
                l = eval(tran.body.replace(',,,', ',').replace(',,"en"', ''))
                S = S + ' '.join(i[0] for i in l[0])
            except:
                pass
            s = ''
        if xbmc.abortRequested or progress.iscanceled(): break
    progress.close()
    s = ' '.join(trans(i) for i in S.split())
    list_3 = s.split('xshare')
    d = 0
    f = open(fd, 'w')
    f.write(
        '0\n00:00:00,000 --> 00:02:00,000\nXshare dich tu ban tieng Anh bang Google translate\n\n'
    )
    for i in list_2:
        try:
            if i == 'xshare':
                f.write(list_3[d].strip().encode('utf-8') + '\n')
                d += 1
            else:
                f.write(i + '\n')
        except:
            pass
    f.close()
    xbmc.executebuiltin("Dialog.Close(all, true)")
    return True
예제 #27
0
def dialog_progress(title, Texto):
    progreso = xbmcgui.DialogProgress()
    progreso.create(title, Texto)
    Progreso = DialogoProgreso(progreso, title)
    return Progreso
예제 #28
0
def refresh_db():
    if not os.path.isfile(_database.DBFILE):
        print "Creating db"
        _database.create_db()
    networks = get_networks()
    dialog = xbmcgui.DialogProgress()
    dialog.create(
        smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39016)))
    total_stations = len(networks)
    current = 0
    increment = 100.0 / total_stations
    all_shows = []
    for network in networks:
        network_name = network.NAME
        if _addoncompat.get_setting(network.SITE) == 'true':
            percent = int(increment * current)
            dialog.update(
                percent,
                smart_utf8(
                    xbmcaddon.Addon(id=ADDONID).getLocalizedString(39017)) +
                network.NAME,
                smart_utf8(
                    xbmcaddon.Addon(id=ADDONID).getLocalizedString(39018)))
            showdata = network.masterlist()
            for show in showdata:
                series_title, mode, submode, url = show
                all_shows.append((smart_unicode(series_title.lower().strip()),
                                  smart_unicode(mode), smart_unicode(submode)))
            total_shows = len(showdata)
            current_show = 0
            for show in showdata:
                percent = int((increment * current) +
                              (float(current_show) / total_shows) * increment)
                dialog.update(
                    percent,
                    smart_utf8(
                        xbmcaddon.Addon(id=ADDONID).getLocalizedString(39017))
                    + network.NAME,
                    smart_utf8(
                        xbmcaddon.Addon(id=ADDONID).getLocalizedString(39005))
                    + show[0])
                get_serie(show[0],
                          show[1],
                          show[2],
                          show[3],
                          forceRefresh=False)
                current_show += 1
                if (dialog.iscanceled()):
                    return False
        current += 1
    command = 'select tvdb_series_title , series_title, mode, submode, url from shows order by series_title'
    shows = _database.execute_command(command, fetchall=True)
    for show in shows:
        tvdb_series_title, series_title, mode, submode, url = show
        if ((smart_unicode(series_title.lower().strip()), smart_unicode(mode),
             smart_unicode(submode)) not in all_shows and
            (smart_unicode(tvdb_series_title.lower().strip()),
             smart_unicode(mode), smart_unicode(submode)) not in all_shows):
            command = 'delete from shows where series_title = ? and mode = ? and submode = ? and url = ?;'
            values = (series_title, mode, submode, url)
            print "Deleting - " + series_title + " " + mode + " " + submode + " " + url
            _database.execute_command(command,
                                      values,
                                      fetchone=True,
                                      commit=True)
예제 #29
0
    def DownLoadSpeedTest(self, entry):
        #Get the direct URL to the mediaitem given URL
        urlopener = CURLLoader()
        result = urlopener.urlopen(entry.URL, entry)
        if result["code"] != 0:
            return -1

        URL = urlopener.loc_url

        if URL[:3] == 'ftp':
            dialog = xbmcgui.Dialog()
            dialog.ok("Message",
                      "test vitesse telechargement FTP non supporte.")
            return 0

        dialog = xbmcgui.DialogProgress()
        dialog.create("Test vitesse telechargement", entry.name)
        dialog.update(0, entry.name)

        try:
            bytes = 0
            chunk = 100 * 1024

            #rembember the user agent set the processor
            index = URL.find('|User-Agent=')
            if index != -1:
                useragent = URL[index + 12:]
                URL = URL[:index]
            else:
                useragent = 'Mozilla/4.0 (compatible;MSIE 7.0;Windows NT 6.0)'

            #headers = { 'User-Agent' : 'Mozilla/4.0 (compatible;MSIE 7.0;Windows NT 6.0)'}
            headers = {'User-Agent': useragent}
            req = urllib2.Request(URL, None, headers)
            f = urllib2.urlopen(req)

            size_string = f.headers['Content-Length']
            size = int(size_string)

            file = open(tempCacheDir + "dltest", "wb")
            starttime = time.time()
            deltatime = 0
            updatetime = 0

            while deltatime < 10:  #10 seconds
                if (dialog.iscanceled()):
                    break

                if (bytes >= size):  # got the complete file
                    break

                file.write(f.read(chunk))
                bytes = bytes + chunk

                deltatime = time.time() - starttime
                if (deltatime - updatetime) >= 1.0:
                    dialog.update(deltatime * 10, entry.name)
                    #dialog.update(deltatime*10, str(deltatime-updatetime))
                    updatetime = deltatime

            f.close()
            file.close()
            os.remove(tempCacheDir + "dltest")

        except IOError:
            pass

        dialog.close()

        if deltatime < 3:
            return -1  # failed because we need at least 3 seconds to have an accurate measurement

        if (deltatime < 10) and (bytes < size):
            return 0  #abort

        #calculate the download speed
        dlspeed = (bytes / 1024) / deltatime

        dialog = xbmcgui.Dialog()
        dialog.ok("Message", "Vitesse telechargement: %d kBytes/s." % dlspeed)

        return 0
예제 #30
0
def MovieLib(plugin, do):
	import movielib
	m = movielib.movielib()
	
	if do == 'Cleanup':
		dialog = xbmcgui.Dialog()
		if dialog.yesno(__language__(32000), __language__(32012)):
			m.vdbCleanUp(sys.argv[0])
			__settings__.setSetting('video_last_update', '0000-00-00 00:00:00')
			__settings__.setSetting('in_vod', 'false')
			dialog = xbmcgui.Dialog()
			dialog.ok( __language__(32000), __language__(32001))
	elif do == 'Update':
		__settings__.setSetting('in_vod', 'false')
		progress = xbmcgui.DialogProgress()
		progress.create(__language__(32003))
		progress.update(10, __language__(32004))
		vlist = plugin.getVideoList('last', 1, 'all')
		progress.update(20, __language__(32005))
		toprocess = []
		last_update = __settings__.getSetting('video_last_update') or '0000-00-00 00:00:00'
		for vod in vlist:
			info = sys.argv[0] + '?mode=VideoInfo&vod=%s' % vod['id']
			if m.vdbMovieByPathAndTrailer(sys.argv[0], info):
				xbmc.log('[%s] skipping %s?' % (PLUGIN_NAME, info), level=xbmc.LOGDEBUG)
				continue
			else:
				xbmc.log('[%s] new vod %s?' % (PLUGIN_NAME, info))
			toprocess.append(vod)
		if len(toprocess):
			stepSize = float(60.0 / len(toprocess))
		else:
			stepSize = 1
		xbmc.log('[%s] progress step size set to %s as 60 / %s' % (PLUGIN_NAME, stepSize, len(toprocess)), level=xbmc.LOGDEBUG)
		counter = 0
		for vod in toprocess:
			# [glareff] i keep getting disconnected when indexing, so i added this line to run every 10 items processed
			if(counter % 10 < 1):
				xbmc.log('\nAuthenticating preventively\n')
				plugin._auth(plugin.login,plugin.password)
			info = plugin.getVideoInfo(vod['id'])
			film = movielib.movielibmovie(sys.argv[0])
			film.setTitle(vod['title'])
			film.setDescription(vod['info'])
			film.setImage(vod['icon'])
			for genre in vod['genre'].split(', '):
				film.addGenre(genre)
			for actor in info['actors'].split(', '):
				film.addActor(actor)
			film.setYear(info['year'])
			if info['rate_imdb']:
				rating = info['rate_imdb']
			else:
				rating = info['rate_kinopoisk']
			film.setRating(rating)
			film.setDirector(info['director'])
			film.setWritter(info['scenario'])
			film.setStudio(info['studio'])
			film.setCountry(info['country'])
			film.setTrailer(sys.argv[0] + '?mode=VideoInfo&vod=%s' % vod['id'])
			for part in info['videos']:
				uri = '?mode=WatchVOD&vod=%s&title=%s' % (part['id'], vod['title'])
				film.addFile(uri, part['title'])
			m.addMovie(film)
			progress.update(40 + int(counter * stepSize), __language__(32006) % vod['title'])
			counter += 1
			xbmc.sleep(250)
			if progress.iscanceled():
				break
		progress.update(100, __language__(32001))
		if not progress.iscanceled():
			__settings__.setSetting('video_last_update', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
		progress.close()
		dialog = xbmcgui.Dialog()
		dialog.ok( __language__(32003), __language__(32007) % counter)
	else:
		xbmc.log('[%s] unknown movie lib command: "%s"' % (PLUGIN_NAME, do))