Exemplo n.º 1
0
    def __login():
        # logger.debug()
        global TOKEN

        apikey = "106B699FDC04301C"

        url = HOST + "/login"
        params = {"apikey": apikey}
        if PY3: params = jsontools.dump(params).encode()
        else: params = jsontools.dump(params)

        try:
            dict_html = requests.post(url,
                                      data=params,
                                      headers=DEFAULT_HEADERS).json()

        except Exception as ex:
            message = "An exception of type %s occured. Arguments:\n%s" % (
                type(ex).__name__, repr(ex.args))
            logger.error("error: %s" % message)

        else:
            if "token" in dict_html:
                token = dict_html["token"]
                DEFAULT_HEADERS["Authorization"] = "Bearer " + token

                TOKEN = config.set_setting("tvdb_token", token)
Exemplo n.º 2
0
def monitor_update(TorrentPath, value, remove=False):
    elementum_setting, elementum_host, TorrentPath = setting()
    json = jsontools.load(open(monitor, "r").read())
    Monitor = json['monitor']
    info = Torrent.from_file(filetools.join(TorrentPath, value + '.torrent'))
    path = xbmc.translatePath(config.get_setting('downloadlistpath'))

    if not value in Monitor:
        Monitor[value]={}
        Monitor[value]['name'] = info.name
        Monitor[value]['size'] = info.total_size
        File = find_file(value)
        Monitor[value]['file'] = File
        json = jsontools.dump(json)
        filetools.write(monitor, json, silent=True)

        backupFilename = jsontools.load(open(filetools.join(path, File), "r").read())['downloadFilename']
        jsontools.update_node(value, File, 'TorrentName', path, silent=True)
        jsontools.update_node(info.total_size, File, 'downloadSize', path, silent=True)
        jsontools.update_node(backupFilename, File, 'backupFilename', path, silent=True)
        jsontools.update_node(info.name, File, 'downloadFilename', path, silent=True)

    elif remove:
        Monitor.pop(value)
        jsontools.dump(json)
        filetools.write(monitor, jsontools.dump(json), silent=True)

    if len(Monitor) == 0: set_elementum()
def update_infolabels_show(tmdb_id, with_tvdb=False):
    logger.info()
    if with_tvdb:
        from core import tvdb as scrapper
    else:
        from core import tmdb as scrapper

    tit = 'Actualizando datos desde ' + ('TVDB' if with_tvdb else 'TMDB')
    progreso = platformtools.dialog_progress(tit, 'Serie y temporadas ...')

    db = TrackingData()
    cambios = []

    # Serie
    # -----
    infolabels = db.get_show(tmdb_id)
    it = Item(infoLabels = infolabels)
    # ~ logger.debug(it)
    scrapper.set_infoLabels_item(it)
    # ~ logger.debug(it)
    if base64.b64encode(jsontools.dump(infolabels)) != base64.b64encode(jsontools.dump(it.infoLabels)):
        db.save_show(tmdb_id, it.infoLabels)
        cambios.append('Serie')

    # Temporadas
    # ----------
    rows = db.get_seasons(tmdb_id)
    num_rows = len(rows)
    n = 0
    for season, infolabels in rows:
        it = Item(infoLabels = infolabels)
        # ~ logger.debug(it)
        scrapper.set_infoLabels_item(it)
        # ~ logger.debug(it)
        if base64.b64encode(jsontools.dump(infolabels)) != base64.b64encode(jsontools.dump(it.infoLabels)):
            db.save_season(tmdb_id, season, it.infoLabels)
            cambios.append('T%d' % season)

        n += 1
        perc = int(n / num_rows * 100)
        progreso.update(perc, tit, 'Procesada temporada %d' % season)
        if progreso.iscanceled(): break

    # Para episodios podrían ser demasiadas llamadas a tmdb, mejor hacerlo por una temporada concreta

    progreso.close()

    commit = True if len(cambios) > 0 else False
    db.close(commit=commit)

    msg = 'Sin cambios en la serie ni en las temporadas.' if not commit else 'Actualizados cambios en %s.' % ', '.join(cambios)
    logger.info(msg)
    return commit, msg
Exemplo n.º 4
0
    def tojson(self, path=""):
        """
        Crea un JSON a partir del item, para guardar archivos de favoritos, lista de descargas, etc...
        Si se especifica un path, te lo guarda en la ruta especificada, si no, devuelve la cadena json
        Usos: item.tojson(path="ruta\archivo\json.json")
              file.write(item.tojson())

        @param path: ruta
        @type path: str
        """
        if path:
            open(path, "wb").write(json.dump(self.__dict__))
        else:
            return json.dump(self.__dict__)
Exemplo n.º 5
0
    def tojson(self, path=""):
        from core import filetools
        """
        Create a JSON from the item, to save favorite files, download list, etc....
        If a path is specified, it saves it in the specified path, if not, it returns the string json
        Applications: item.tojson(path="path\archivo\json.json")
                      file.write(item.tojson())

        @param path: path
        @type path: str
        """
        if path:
            #open(path, "wb").write(json.dump(self.__dict__))
            res = filetools.write(path, json.dump(self.__dict__))
        else:
            return json.dump(self.__dict__)
Exemplo n.º 6
0
def programs(item):
    logger.debug()

    itemlist = []
    data = session.get(
        f'{domain}/cms/routes/browse?include=default').json()['included']
    images = {
        key['id']: key['attributes']['src']
        for key in data if key['type'] == 'image'
    }

    channels = {}
    for key in data:
        if key['type'] == 'link' and 'Free' in key['attributes']['packages']:
            logger.debug(jsontools.dump(key))
            _title = key['attributes'].get('title',
                                           key['attributes'].get('name', ''))
            _id = key['relationships']['linkedContent']['data']['id']
            _thumb = images.get(key['relationships'].get('images', {}).get(
                'data', [{}])[0].get('id'))
            channels[_title] = {'id': _id, 'thumb': _thumb}

    itemlist = [
        item.clone(title='Tutti',
                   id=channels['Tutti']['id'],
                   action='peliculas'),
        item.clone(title='Generi', id=channels['Tutti']['id'],
                   action='genres'),
        item.clone(title='Per canale', channels=channels, action='channels')
    ]

    return support.thumb(itemlist)
Exemplo n.º 7
0
def write(item, json):
    logger.debug()
    js = jsontools.load(open(filename(item), "r").read())
    js[RENUMBER] = json
    with open(filename(item), "w") as file:
        file.write(jsontools.dump(js))
        file.close()
Exemplo n.º 8
0
def set_server_setting(name, value, server):
    # We create the folder if it does not exist
    if not filetools.exists(filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers", server + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # We get saved configuration from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR when reading the file: %s" % file_settings)

    dict_settings[name] = value

    # we check if dict_file exists and it is a dictionary, if not we create it
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # We create the file ../settings/channel_data.json
    if not filetools.write(file_settings, jsontools.dump(dict_file)):
        logger.error("ERROR saving file: %s" % file_settings)
        return None

    return value
Exemplo n.º 9
0
def set_server_setting(name, value, server):
    # Creamos la carpeta si no existe
    if not os.path.exists(os.path.join(config.get_data_path(), "settings_servers")):
        os.mkdir(os.path.join(config.get_data_path(), "settings_servers"))

    file_settings = os.path.join(config.get_data_path(), "settings_servers", server + "_data.json")
    dict_settings = {}

    dict_file = None

    if os.path.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(open(file_settings, "r").read())
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % file_settings)

    dict_settings[name] = value

    # comprobamos si existe dict_file y es un diccionario, sino lo creamos
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    try:
        json_data = jsontools.dump(dict_file)
        open(file_settings, "w").write(json_data)
    except EnvironmentError:
        logger.info("ERROR al salvar el archivo: %s" % file_settings)
        return None

    return value
Exemplo n.º 10
0
def auth_trakt():
    item = Item()
    folder = (config.get_platform() == "plex")
    item.folder = folder
    # Autentificación de cuenta Trakt
    headers = {'Content-Type': 'application/json', 'trakt-api-key': client_id, 'trakt-api-version': '2'}
    try:
        post = {'client_id': client_id}
        post = jsontools.dump(post)
        # Se solicita url y código de verificación para conceder permiso a la app
        url = "http://api-v2launch.trakt.tv/oauth/device/code"
        data = httptools.downloadpage(url, post=post, headers=headers, replace_headers=True).data
        data = jsontools.load(data)
        item.verify_url = data["verification_url"]
        item.user_code = data["user_code"]
        item.device_code = data["device_code"]
        item.intervalo = data["interval"]
        if not item.folder:
            token_trakt(item)

        else:
            itemlist = []
            title = "Accede a esta página: %s" % item.verify_url
            itemlist.append(item.clone(title=title, action=""))
            title = "Ingresa este código y acepta: %s" % item.user_code
            itemlist.append(item.clone(title=title, action=""))
            title = "Una vez hecho, pulsa aquí!"
            itemlist.append(item.clone(title=title, action="token_trakt"))
            return itemlist
    except:
        import traceback
        logger.error(traceback.format_exc())
Exemplo n.º 11
0
def get_data(payload):
    """
    obtiene la información de la llamada JSON-RPC con la información pasada en payload
    @type payload: dict
    @param payload: data
    :return:
    """
    logger.info("payload: %s" % payload)
    # Required header for XBMC JSON-RPC calls, otherwise you'll get a 415 HTTP response code - Unsupported media type
    headers = {'content-type': 'application/json'}

    if config.get_setting("db_mode", "videolibrary"):
        try:
            try:
                xbmc_port = config.get_setting("xbmc_puerto", "videolibrary")
            except:
                xbmc_port = 0

            xbmc_json_rpc_url = "http://" + config.get_setting(
                "xbmc_host",
                "videolibrary") + ":" + str(xbmc_port) + "/jsonrpc"
            req = urllib2.Request(xbmc_json_rpc_url,
                                  data=jsontools.dump(payload),
                                  headers=headers)
            f = urllib2.urlopen(req)
            response = f.read()
            f.close()

            logger.info("get_data: response %s" % response)
            data = jsontools.load(response)
        except Exception, ex:
            template = "An exception of type %s occured. Arguments:\n%r"
            message = template % (type(ex).__name__, ex.args)
            logger.error("error en xbmc_json_rpc_url: %s" % message)
            data = ["error"]
Exemplo n.º 12
0
def set_elementum(SET=False):
    elementum_setting, elementum_host, TorrentPath = setting()
    json = jsontools.load(open(monitor, "r").read())
    backup_setting = json['settings']
    write = False
    if SET:
        if elementum_setting.getSetting('logger_silent') == False or not 'logger_silent' in backup_setting:
            elementum_setting.setSetting('logger_silent', 'true')
            backup_setting['logger_silent'] = 'false'

        if elementum_setting.getSetting('download_storage') != 0 or not 'download_storage' in backup_setting:
            backup_setting['download_storage'] = elementum_setting.getSetting('download_storage')           # Backup Setting
            elementum_setting.setSetting('download_storage', '0')                                    # Set Setting

        if elementum_setting.getSetting('download_path') != config.get_setting('downloadpath') or not 'download_path' in backup_setting:
            backup_setting['download_path'] = elementum_setting.getSetting('download_path')              # Backup Setting
            elementum_setting.setSetting('download_path', config.get_setting('downloadpath'))        # Set Setting
        write = True

    elif backup_setting:
        elementum_setting.setSetting('logger_silent', backup_setting['logger_silent'])
        elementum_setting.setSetting('download_storage', backup_setting['download_storage'])
        elementum_setting.setSetting('download_path', backup_setting['download_path'])
        json['settings'] = {}
        write = True
    if write:
        json = jsontools.dump(json)
        filetools.write(monitor, json, silent=True)
        time.sleep(1)
Exemplo n.º 13
0
def lista(item):
    logger.info()
    itemlist = []
    dict_param = dict()
    item.infoLabels = {}
    item.text_color = color2
    params = '{}'
    if item.extra1 != 0:
        dict_param["genero"] = [item.extra1]
        params = jsontools.dump(dict_param)
    data = httptools.downloadpage(item.url, post=params).data
    data = data.replace("<mark>","").replace("<\/mark>","")
    dict_data = jsontools.load(data)
    for it in dict_data["items"]:
        year = it["year"]
        url = host + "pelicula/" + it["slug"]
        title = it["title"] + " (%s)" %year
        thumb = host + it["image"]
        item.infoLabels['year'] = year
        itemlist.append(item.clone(action="findvideos", title=title, url=url, thumbnail=thumb,
                                   context=["buscar_trailer"], contentTitle=it["title"], contentType="movie"))
    tmdb.set_infoLabels(itemlist, __modo_grafico__)
    pagina = scrapertools.find_single_match(item.url, 'page=([0-9]+)')
    item.url = item.url.replace(pagina, "")
    if pagina == "":
        pagina = "0"
    pagina = int(pagina) + 1
    item.url = item.url + "%s" %pagina
    if item.extra != "busqueda":
        itemlist.append(Item(channel = item.channel, action="lista", title="Pagina %s" %pagina, url=item.url, extra1 = item.extra1
                             ))
    return itemlist
Exemplo n.º 14
0
    def stop(self, erase=False):
        if self._state == self.states.downloading:
            # We stop downloading
            self._state = self.states.stopped
            for t in self._threads:
                if t.is_alive(): t.join()

            if self._save_thread.is_alive(): self._save_thread.join()

            if self._seekable:
                # Guardamos la info al final del archivo
                self.file.seek(0, 2)
                try:
                    offset = self.file.tell()
                except:
                    offset = self.file.seek(0, 1)
                if not PY3:
                    self.file.write(str(self._download_info))
                    self.file.write("%0.16d" % offset)
                else:
                    download_info_dump = jsontools.dump(
                        self._download_info).encode('utf-8')
                    self.file.write(download_info_dump)
                    self.file.write(b"%0.16d" % offset)

        self.file.close()

        if erase: os.remove(filetools.join(self._path, self._filename))
Exemplo n.º 15
0
def verify_copy_folders(custom_code_dir, custom_code_json_path):
    logger.info()

    #verificamos si es una nueva versión de Alfa instalada o era la existente.  Si es la existente, nos vamos sin hacer nada
    json_data_file = filetools.join(custom_code_json_path, json_data_file_name)
    json_data = jsontools.load(filetools.read(json_data_file))
    current_version = config.get_addon_version(with_fix=False)
    if not json_data or not 'addon_version' in json_data:
        create_json(custom_code_json_path)
        json_data = jsontools.load(filetools.read(json_data_file))
    try:
        if current_version == json_data['addon_version']:
            return
    except:
        logger.error(traceback.format_exc(1))

    #Ahora copiamos los archivos desde el área de Userdata, Custom_code, sobre las carpetas del add-on
    for root, folders, files in filetools.walk(custom_code_dir):
        for file in files:
            input_file = filetools.join(root, file)
            output_file = input_file.replace(custom_code_dir,
                                             custom_code_json_path)
            if not filetools.copy(input_file, output_file, silent=True):
                return

    #Guardamaos el json con la versión actual de Alfa, para no volver a hacer la copia hasta la nueva versión
    json_data['addon_version'] = current_version
    filetools.write(json_data_file, jsontools.dump(json_data))

    return
Exemplo n.º 16
0
def get_data(url_orig, req_post=""):
    try:
        if not excption:
            response = httptools.downloadpage(url_orig, post=req_post)
            if not response.data or "urlopen error [Errno 1]" in str(response.code):
                global excption
                excption = True
                raise Exception
            return response.data
        else:
            raise Exception
    except:
        post = {"address": url_orig.replace(".me", ".org")}
        if req_post:
            post["options"] = [{"man": "--data", "attribute": req_post}]
        else:
            post["options"] = []
        from core import jsontools
        global token
        if not token:
            data = httptools.downloadpage("http://onlinecurl.com/").data
            token = scrapertools.find_single_match(data, '<meta name="csrf-token" content="([^"]+)"')

        headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': token, 'Referer': 'http://onlinecurl.com/'}
        post = "curl_request=" + urllib.quote(jsontools.dump(post)) + "&email="
        response = httptools.downloadpage("http://onlinecurl.com/onlinecurl", post=post, headers=headers).data
        data = jsontools.load(response).get("body", "")

        return data
Exemplo n.º 17
0
    def __login():
        # logger.info()
        global TOKEN

        apikey = "106B699FDC04301C"

        url = HOST + "/login"
        params = {"apikey": apikey}

        try:
            req = urllib.request.Request(url,
                                         data=jsontools.dump(params),
                                         headers=DEFAULT_HEADERS)
            response = urllib.request.urlopen(req)
            html = response.read()
            response.close()

        except Exception as ex:
            message = "An exception of type %s occured. Arguments:\n%s" % (
                type(ex).__name__, repr(ex.args))
            logger.error("error: %s" % message)

        else:
            dict_html = jsontools.load(html)
            # logger.debug("dict_html %s" % dict_html)

            if "token" in dict_html:
                token = dict_html["token"]
                DEFAULT_HEADERS["Authorization"] = "Bearer " + token

                TOKEN = config.set_setting("tvdb_token", token)
Exemplo n.º 18
0
def extract_safe(item):
    logger.info()
    if item.infoLabels["tmdb_id"] and not item.infoLabels["plot"]:
        tmdb.set_infoLabels_item(item, True, idioma_busqueda="en")
    itemlist = list()
    hash = item.url.rsplit("/", 1)[1]
    headers = [['Content-Type', 'application/json;charset=utf-8']]
    post = jsontools.dump({"hash": hash})
    data = httptools.downloadpage("http://safelinking.net/v1/protected",
                                  post=post,
                                  headers=headers).json
    for link in data.get("links"):
        enlace = link["url"]
        domain = link["domain"]
        title = "Ver por %s" % domain
        action = "play"
        if "mega" in domain:
            server = "mega"
            if "/#F!" in enlace:
                action = "carpeta"
        elif "1fichier" in domain:
            server = "onefichier"
            if "/dir/" in enlace:
                action = "carpeta"
        itemlist.append(
            item.clone(title=title, action=action, url=enlace, server=server))
    return itemlist
Exemplo n.º 19
0
def check_blacklist(domain):
    res = True
    if not filetools.exists(PATH_BL):
        return res
    
    try:
        bl_data = jsontools.load(filetools.read(PATH_BL))
        bl_data_clean = bl_data.copy()
        expiration = config.get_setting('cf_assistant_bl_expiration', default=30) * 60
        if not expiration:
            config.set_setting('cf_assistant_bl_expiration', 30)
            expiration = 30 * 60
        time_today = time.time()
        
        if bl_data:
            for domain_reg, time_rec in list(bl_data_clean.items()):
                if time_today > time_rec + expiration:
                    del bl_data[domain_reg]
            filetools.write(PATH_BL, jsontools.dump(bl_data))
            for domain_reg, time_rec in list(bl_data.items()):
                if domain in domain_reg:
                    res = False
                    break
            else:
                res = True
    except:
        logger.error(traceback.format_exc())
        filetools.remove(PATH_BL)
        res = True

    return res
Exemplo n.º 20
0
def save_server_stats(stats, type="find_videos"):
    if not config.get_setting("server_stats"):
        return

    stats_file = os.path.join(config.get_data_path(), "server_stats.json")
    today = datetime.datetime.now().strftime("%Y%m%d")

    # Leemos el archivo
    try:
        server_stats = jsontools.load(open(stats_file, "rb").read())
    except:
        server_stats = {"created": time.time(), "data": {}}

    # Actualizamos los datos
    for server in stats:
        if not server in server_stats["data"]:
            server_stats["data"][server] = {}

        if not today in server_stats["data"][server]:
            server_stats["data"][server][today] = {
                "find_videos": {
                    "found": 0
                },
                "resolve": {
                    "sucess": 0,
                    "error": 0
                }
            }

        server_stats["data"][server][today][type][stats[server]] += 1

    # Guardamos el archivo
    open(stats_file, "wb").write(jsontools.dump(server_stats))

    # Enviamos al servidor
    return
    if time.time() - server_stats["created"] > 86400:  # 86400: #1 Dia
        from core import httptools
        if httptools.downloadpage("url servidor",
                                  headers={
                                      'Content-Type': 'application/json'
                                  },
                                  post=jsontools.dump(server_stats)).sucess:
            os.remove(stats_file)
            logger.info("Datos enviados correctamente")
        else:
            logger.info("No se han podido enviar los datos")
Exemplo n.º 21
0
def search_for_unrar_in_error(download_paths, init=False):
    logger.info(str(init) + ' / ' + str(download_paths))

    rar_processed = []

    for torrent_client, path in download_paths:
        list_dir = filetools.listdir(path)
        for folder_w in list_dir:
            folder = filetools.join(path, folder_w)
            if filetools.isdir(folder):
                if not filetools.exists(
                        filetools.join(folder, '_rar_control.json')):
                    continue
            else:
                if not '_rar_control.json' in folder:
                    continue

            if folder in rar_processed:
                continue
            rar_processed += [folder]

            rar_control = jsontools.load(
                filetools.read(filetools.join(folder, '_rar_control.json')))
            rar_control['status'] += ': Recovery'
            if ('UnRARing' in rar_control['status']
                    or 'RECOVERY' in rar_control['status']) and not init:
                continue
            if 'UnRARing' in rar_control['status'] or 'ERROR' in rar_control[
                    'status']:
                rar_control['status'] = 'RECOVERY: ' + rar_control['status']
            rar_control['download_path'] = folder
            rar_control['torr_client'] = torrent_client
            if 'ERROR' in rar_control['status'] or 'UnRARing' in rar_control['status'] \
                        or 'RECOVERY' in rar_control['status']:
                rar_control['error'] += 1
            ret = filetools.write(
                filetools.join(rar_control['download_path'],
                               '_rar_control.json'),
                jsontools.dump(rar_control))
            logger.debug('%s, %s, %s, %s, %s, %s' % (rar_control['download_path'], \
                        rar_control['rar_names'][0], rar_control['password'], \
                        str(rar_control['error']), rar_control['error_msg'], rar_control['status']))
            if ('ERROR' in rar_control['status'] and rar_control['error'] > 2) \
                        or ('UnRARing' in rar_control['status'] and rar_control['error'] > 3) \
                        or ('RECOVERY' in rar_control['status'] and rar_control['error'] > 3)  \
                        or 'DONE' in rar_control['status']:
                continue

            if ret:
                try:
                    threading.Thread(target=call_unrar, args=(
                        rar_control,
                    )).start()  # Creamos un Thread independiente por UnRAR
                    time.sleep(1)  # Dejamos terminar la inicialización...
                except:  # Si hay problemas de threading, pasamos al siguiente
                    logger.error(traceback.format_exc())

    if not init:
        sys.exit(0)
Exemplo n.º 22
0
def get_server_setting(name, server, default=None):
    """
        Returns the configuration value of the requested parameter.

        Returns the value of the parameter 'name' in the own configuration of the server 'server'.

        Look in the path \addon_data\plugin.video.addon\settings_servers for the file server_data.json and read
        the value of the parameter 'name'. If the server_data.json file does not exist look in the servers folder for the file
        server.json and create a server_data.json file before returning the requested value. If the parameter 'name'
        also does not exist in the server.json file the default parameter is returned.


        @param name: parameter name
        @type name: str
        @param server: server name
        @type server: str
        @param default: return value in case the name parameter does not exist
        @type default: any

        @return: The parameter value 'name'
        @rtype: any

        """
    # We create the folder if it does not exist
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}
    dict_file = {}
    if filetools.exists(file_settings):
        # We get saved configuration from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.info("ERROR when reading the file: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # We get controls from the file ../servers/server.json
        try:
            list_controls, default_settings = get_server_controls_settings(
                server)
        except:
            default_settings = {}
        if name in default_settings:  # If the parameter exists in the server.json we create the server_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # We create the file ../settings/channel_data.json
            if not filetools.write(file_settings, jsontools.dump(dict_file)):
                logger.info("ERROR saving file: %s" % file_settings)

    # We return the value of the local parameter 'name' if it exists, if default is not returned
    return dict_settings.get(name, default)
Exemplo n.º 23
0
def get_channel_setting(name, channel, default=None):
    from core import filetools
    """
    Returns the configuration value of the requested parameter.

    Returns the value of the parameter 'name' in the own configuration of the channel 'channel'.

    Look in the path \addon_data\plugin.video.kod\settings_channels for the file channel_data.json and read
    the value of the parameter 'name'. If the file channel_data.json does not exist look in the channels folder for the file
    channel.json and create a channel_data.json file before returning the requested value. If the parameter 'name'
    also does not exist in the channel.json file the default parameter is returned.


    @param name: parameter name
    @type name: str
    @param channel: channel name
    @type channel: str
    @param default: return value in case the name parameter does not exist
    @type default: any

    @return: The value of the parameter 'name'
    @rtype: any

    """
    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}
    dict_file = {}
    if channel not in ['trakt', 'autoplay']:
        def_settings = get_default_settings(channel)

    if filetools.exists(file_settings):
        # We get saved configuration from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.error("ERROR when reading the file: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # We get controls from the file ../channels/channel.json
        try:
            list_controls, default_settings = get_channel_controls_settings(
                channel)
        except:
            default_settings = {}

        if name in default_settings:  #If the parameter exists in the channel.json we create the channel_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # We create the file ../settings/channel_data.json
            json_data = jsontools.dump(dict_file)
            if not filetools.write(file_settings, json_data, silent=True):
                logger.error("ERROR saving file: %s" % file_settings)

    # We return the value of the local parameter 'name' if it exists, if default is not returned
    return dict_settings.get(name, default)
Exemplo n.º 24
0
def get_server_setting(name, server, default=None):
    """
        Retorna el valor de configuracion del parametro solicitado.

        Devuelve el valor del parametro 'name' en la configuracion propia del servidor 'server'.

        Busca en la ruta \addon_data\plugin.video.addon\settings_servers el archivo server_data.json y lee
        el valor del parametro 'name'. Si el archivo server_data.json no existe busca en la carpeta servers el archivo 
        server.json y crea un archivo server_data.json antes de retornar el valor solicitado. Si el parametro 'name'
        tampoco existe en el el archivo server.json se devuelve el parametro default.


        @param name: nombre del parametro
        @type name: str
        @param server: nombre del servidor
        @type server: str
        @param default: valor devuelto en caso de que no exista el parametro name
        @type default: any

        @return: El valor del parametro 'name'
        @rtype: any

        """
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}
    dict_file = {}
    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # Obtenemos controles del archivo ../servers/server.json
        try:
            list_controls, default_settings = get_server_controls_settings(
                server)
        except:
            default_settings = {}
        if name in default_settings:  # Si el parametro existe en el server.json creamos el server_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # Creamos el archivo ../settings/channel_data.json
            if not filetools.write(file_settings, jsontools.dump(dict_file)):
                logger.info("ERROR al salvar el archivo: %s" % file_settings)

    # Devolvemos el valor del parametro local 'name' si existe, si no se devuelve default
    return dict_settings.get(name, default)
Exemplo n.º 25
0
def write(item, json):
    logger.debug()
    json_file = open(filename(item), "r").read()
    js = jsontools.load(json_file)
    js[TVSHOW_RENUMERATE] = json
    with open(filename(item), "w") as file:
        file.write(jsontools.dump(js))
        file.close()
Exemplo n.º 26
0
def set_channel_setting(name, value, channel):
    from core import filetools
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion propia del canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.kod\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.

    @param name: nombre del parametro
    @type name: str
    @param value: valor del parametro
    @type value: str
    @param channel: nombre del canal
    @type channel: str

    @return: 'value' en caso de que se haya podido fijar el valor y None en caso contrario
    @rtype: str, None

    """
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_channels")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_channels"))

    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR al leer el archivo: %s" % file_settings)

    dict_settings[name] = value

    # comprobamos si existe dict_file y es un diccionario, sino lo creamos
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    json_data = jsontools.dump(dict_file)
    if not filetools.write(file_settings, json_data, silent=True):
        logger.error("ERROR al salvar el archivo: %s" % file_settings)
        return None

    return value
Exemplo n.º 27
0
def get_channel_setting(name, channel, default=None):
    from core import filetools
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion propia del canal 'channel'.

    Busca en la ruta \addon_data\plugin.video.kod\settings_channels el archivo channel_data.json y lee
    el valor del parametro 'name'. Si el archivo channel_data.json no existe busca en la carpeta channels el archivo
    channel.json y crea un archivo channel_data.json antes de retornar el valor solicitado. Si el parametro 'name'
    tampoco existe en el el archivo channel.json se devuelve el parametro default.


    @param name: nombre del parametro
    @type name: str
    @param channel: nombre del canal
    @type channel: str
    @param default: valor devuelto en caso de que no exista el parametro name
    @type default: any

    @return: El valor del parametro 'name'
    @rtype: any

    """
    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}
    dict_file = {}
    if channel not in ['trakt']: def_settings = get_default_settings(channel)

    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.error("ERROR al leer el archivo: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # Obtenemos controles del archivo ../channels/channel.json
        try:
            list_controls, default_settings = get_channel_controls_settings(
                channel)
        except:
            default_settings = {}

        if name in default_settings:  # Si el parametro existe en el channel.json creamos el channel_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # Creamos el archivo ../settings/channel_data.json
            json_data = jsontools.dump(dict_file)
            if not filetools.write(file_settings, json_data, silent=True):
                logger.error("ERROR al salvar el archivo: %s" % file_settings)

    # Devolvemos el valor del parametro local 'name' si existe, si no se devuelve default
    return dict_settings.get(name, default)
Exemplo n.º 28
0
def set_channel_setting(name, value, channel):
    from core import filetools
    """
    Sets the configuration value of the indicated parameter.

    Set 'value' as the value of the parameter 'name' in the own configuration of the channel 'channel'.
    Returns the changed value or None if the assignment could not be completed.

    If the name of the channel is specified, search in the path \addon_data\plugin.video.kod\settings_channels the
    channel_data.json file and set the parameter 'name' to the value indicated by 'value'.
    If the parameter 'name' does not exist, it adds it, with its value, to the corresponding file.

    @param name: parameter name
    @type name: str
    @param value: parameter value
    @type value: str
    @param channel: channel name
    @type channel: str

    @return: 'value' if the value could be set and None otherwise
    @rtype: str, None

    """
    # We create the folder if it does not exist
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_channels")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_channels"))

    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # We get saved settings from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR when reading the file: %s" % file_settings)

    dict_settings[name] = value

    # we check if dict_file exists and it is a dictionary, if not we create it
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    json_data = jsontools.dump(dict_file)
    if not filetools.write(file_settings, json_data, silent=True):
        logger.error("ERROR saving file: %s" % file_settings)
        return None

    return value
Exemplo n.º 29
0
def now_available():

    itemlist = list()
    channel_list = list()
    if not platformtools.is_playing():
        channel_list.extend(news.get_channels("peliculas"))
        first_pass = check_db()
        #platformtools.dialog_notification("Alfa", "Buscando estrenos...")
        with futures.ThreadPoolExecutor() as executor:
            c_results = [executor.submit(news.get_channel_news, ch, "peliculas") for ch in channel_list]

            for index, res in enumerate(futures.as_completed(c_results)):
                try:
                    itemlist.extend(res.result()[1])
                except:
                    continue

        tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)

        conn = sqlite3.connect(db_path)
        conn.text_factory = str
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM availables")


        #if first_pass:
        #    set_new = 0
        #else:
        #    set_new = 1

        now = datetime.datetime.today()

        for elem in itemlist:
            if not elem.infoLabels["tmdb_id"] or not elem.infoLabels["release_date"]:
                continue
            release = datetime.datetime.strptime(elem.infoLabels["release_date"], "%d/%m/%Y")
            status = elem.infoLabels["status"]
            if status != "Released" or release < (now - datetime.timedelta(weeks=26.0715)):
                continue
            cursor.execute("SELECT * FROM availables WHERE tmdb_id=?", (elem.infoLabels["tmdb_id"],))
            results = cursor.fetchone()
            id = elem.infoLabels["tmdb_id"]
            release = datetime.datetime.strftime(release, "%Y/%m/%d")

            #if set_new:
            info = jsontools.dump(elem.infoLabels)
            #else:
            #    info = ""
            if results:
                continue
            else:
                cursor.execute("INSERT INTO availables (tmdb_id, info, new, release, wish)VALUES (?, ?, ?, ?, ?)",
                               (id, info, 1, release, 0))
                conn.commit()

        item = Item(channel="info_popup", current=0)
        show_popup(item, first_pass=first_pass)
Exemplo n.º 30
0
def set_watched(id):

    watched_file = dict()

    if filetools.exists(data_path) and filetools.getsize(data_path) > 0:
        watched_file = jsontools.load(filetools.read(data_path))

    watched_file[id] = "true"
    filetools.write(data_path, jsontools.dump(watched_file))