Example #1
0
def init(channel, list_servers, list_quality):
    '''
    Comprueba la existencia de canal en el archivo de configuracion de Autoplay y si no existe lo añade.
    Es necesario llamar a esta funcion al entrar a cualquier canal que incluya la funcion Autoplay.

    :param channel: (str) id del canal
    :param list_servers: (list) lista inicial de servidores validos para el canal. No es necesario incluirlos todos,
        ya que la lista de servidores validos se ira actualizando dinamicamente.
    :param list_quality: (list) lista inicial de calidades validas para el canal. No es necesario incluirlas todas,
        ya que la lista de calidades validas se ira actualizando dinamicamente.
    :return: (bool) True si la inicializacion ha sido correcta.
    '''
    logger.info()
    change = False
    result = True

    if not config.is_xbmc():
        # platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi')
        result = False
    else:
        autoplay_path = os.path.join(config.get_data_path(),
                                     "settings_channels", 'autoplay_data.json')
        if os.path.exists(autoplay_path):
            autoplay_node = jsontools.get_node_from_file(
                'autoplay', "AUTOPLAY")
        else:
            change = True
            autoplay_node = {"AUTOPLAY": {}}

        if channel not in autoplay_node:
            change = True

            # Se comprueba que no haya calidades ni servidores duplicados
            if 'default' not in list_quality:
                list_quality.append('default')
            list_servers = list(set(list_servers))
            list_quality = list(set(list_quality))

            # Creamos el nodo del canal y lo añadimos
            channel_node = {
                "servers": list_servers,
                "quality": list_quality,
                "settings": {
                    "active": False,
                    "custom_servers": False,
                    "custom_quality": False,
                    "priority": 0
                }
            }
            for n in range(1, 4):
                s = c = 0
                if len(list_servers) >= n:
                    s = n - 1
                if len(list_quality) >= n:
                    c = n - 1

                channel_node["settings"]["server_%s" % n] = s
                channel_node["settings"]["quality_%s" % n] = c

            autoplay_node[channel] = channel_node

        if change:
            result, json_data = jsontools.update_node(autoplay_node,
                                                      'autoplay', 'AUTOPLAY')

            if not result:
                heading = "Error al iniciar AutoPlay"
                msj = "Consulte su log para obtener mas información."
                icon = 1

                platformtools.dialog_notification(heading,
                                                  msj,
                                                  icon,
                                                  sound=False)

    return result
Example #2
0
from core.item import Item
from core import jsontools
from platformcode import config, logger
from platformcode import launcher
import xbmc, xbmcgui, xbmcplugin, xbmcaddon

media_path = os.path.join(config.get_runtime_path(),
                          "resources/skins/Default/media/side_menu/")
menu_settings_path = os.path.join(config.get_data_path(), "settings_channels",
                                  'menu_settings_data.json')

if os.path.exists(menu_settings_path):
    menu_node = jsontools.get_node_from_file('menu_setting_data.json', 'menu')
else:
    menu_node = {'categoria actual': config.get_setting('category')}
    jsontools.update_node(menu_node, 'menu_settings_data.json', "menu")

info_language = ["de", "en", "es", "fr", "it", "pt"]  # from videolibrary.json
def_lang = info_language[config.get_setting("info_language", "videolibrary")]

ACTION_SHOW_FULLSCREEN = 36
ACTION_GESTURE_SWIPE_LEFT = 511
ACTION_SELECT_ITEM = 7
ACTION_PREVIOUS_MENU = 10
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_DOWN = 4
ACTION_MOVE_UP = 3


def set_menu_settings(item):
Example #3
0
def semiautomatic_config_item(item):
    log()
    # Configurazione Semi Automatica, utile in caso la numerazione automatica fallisca

    tvdb.find_and_set_infoLabels(item)
    item.channel = item.from_channel
    dict_series = jsontools.get_node_from_file(item.channel,
                                               TAG_TVSHOW_RENUMERATE)
    title = item.show

    # Trova l'ID dellla serie
    while not item.infoLabels['tvdb_id']:
        try:
            item.show = platformtools.dialog_input(
                default=item.show, heading=config.get_localized_string(
                    30112))  # <- Enter title to search
            tvdb.find_and_set_infoLabels(item)
        except:
            heading = config.get_localized_string(
                70704)  # <- TMDB ID (0 to cancel)
            info = platformtools.dialog_numeric(0, heading)
            item.infoLabels['tvdb_id'] = '0' if info == '' else info

    if item.infoLabels['tvdb_id']:
        ID = item.infoLabels['tvdb_id']
        dict_renumerate = {TAG_ID: ID}
        dict_series[title] = dict_renumerate
        # Trova la Stagione
        if any(word in title.lower() for word in ['specials', 'speciali']):
            heading = config.get_localized_string(
                70686
            )  # <- Enter the number of the starting season (for specials)
            season = platformtools.dialog_numeric(0, heading, '0')
            dict_renumerate[TAG_SEASON] = season
        elif RepresentsInt(title.split()[-1]):
            heading = config.get_localized_string(
                70686
            )  # <- Enter the number of the starting season (for season > 1)
            season = platformtools.dialog_numeric(0, heading,
                                                  title.split()[-1])
            dict_renumerate[TAG_SEASON] = season
        else:
            heading = config.get_localized_string(
                70686
            )  # <- Enter the number of the starting season (for season 1)
            season = platformtools.dialog_numeric(0, heading, '1')
            dict_renumerate[TAG_SEASON] = season

        ########### PROVVISORIO ###################
        mode = platformtools.dialog_yesno(
            config.get_localized_string(70687),
            config.get_localized_string(70688),
            nolabel=config.get_localized_string(30023),
            yeslabel=config.get_localized_string(30022))
        if mode == 1:
            dict_renumerate[TAG_MODE] = False
            specials = []
            stop = False
            while not stop:
                heading = config.get_localized_string(70718) + str(specials)
                special = platformtools.dialog_numeric(0, heading, '')
                if special:
                    specials.append(int(special))
                    dict_renumerate[TAG_SPECIAL] = specials
                else:
                    stop = True
        dict_renumerate[TAG_MODE] = False
        # Richede se ci sono speciali nella stagione
        # mode = platformtools.dialog_yesno(config.get_localized_string(70687), config.get_localized_string(70688), nolabel=config.get_localized_string(30023), yeslabel=config.get_localized_string(30022))
        # if mode == 0: dict_renumerate[TAG_MODE] = False
        # else:
        #     select = platformtools.dialog_yesno(config.get_localized_string(70687), config.get_localized_string(70717), nolabel=config.get_localized_string(30023), yeslabel=config.get_localized_string(30022))
        #     if select == 0:
        #         dict_renumerate[TAG_MODE] = False
        #         specials = []
        #         stop = False
        #         while not stop:
        #             heading = config.get_localized_string(70718) + str(specials)
        #             special = platformtools.dialog_numeric(0, heading, '')
        #             if special:
        #                 specials.append(int(special))
        #                 dict_renumerate[TAG_SPECIAL] = specials
        #             else: stop = True
        #     else:
        #         dict_renumerate[TAG_MODE] = True
        ########### PROVVISORIO ###################

        # Imposta la voce Episode
        dict_renumerate[TAG_EPISODE] = ''
        # Scrive nel json
        jsontools.update_node(dict_series, item.channel,
                              TAG_TVSHOW_RENUMERATE)[0]

    else:
        message = config.get_localized_string(60444)
        heading = item.show.strip()
        platformtools.dialog_notification(heading, message)
Example #4
0
def make_list(itemlist, item, typography, dict_series, ID, SEASON, EPISODE,
              MODE, TITLE):
    from core import support
    log()
    page = 1
    EpList = []
    EpisodeDict = {}
    exist = True
    item.infoLabels['tvdb_id'] = ID
    tvdb.set_infoLabels_item(item)
    FirstOfSeason = 0
    try:
        SPECIAL = dict_series[TITLE][TAG_SPECIAL]
    except:
        SPECIAL = []

    # Ricava Informazioni da TVDB
    while exist:
        data = tvdb.otvdb_global.get_list_episodes(ID, page)
        if data: page = page + 1
        else: exist = False

        if data:
            for episodes in data['data']:
                EpList.append([
                    episodes['firstAired'], episodes['airedSeason'],
                    episodes['airedEpisodeNumber']
                ])
        EpList.sort()
        log(EpList)

    # Crea Dizionari per la numerazione
    if EpList:
        specials = []
        regular = {}
        complete = {}
        allep = 1
        ep = 0
        specialep = 0
        for episode in EpList:
            complete[allep] = [
                str(episode[1]) + 'x' + str(episode[2]), episode[0]
            ]
            if episode[1] == 0:
                specials.append(allep)
                specialep = specialep + 1
            else:
                regular[ep] = [
                    str(episode[1]) + 'x' + str(episode[2]),
                    str(episode[0]), allep - 1
                ]
                ep = ep + 1
            allep = allep + 1

        # seleziona l'Episodio di partenza
        if int(SEASON) > 1:
            for numbers, data in regular.items():
                if data[0] == SEASON + 'x1':
                    FirstOfSeason = numbers - 1

        if MODE == True: SPECIAL = specials
        log(SPECIAL)
        log(complete)
        log(regular)

        addiction = 0
        for item in itemlist:
            # Otiene Numerazione Episodi
            episode = int(scrapertoolsV2.find_single_match(item.title, r'\d+'))
            log('EPISODE= ', episode)
            number = episode + FirstOfSeason - addiction
            count = number + addiction
            # find = episode + FirstOfSeason
            # log('FIND= ',find, ' ',str(episode) + ' ' + str(FirstOfSeason))
            # Crea Dizionario Episodi

            # log(episode, ' ', number, ' ', count)
            if episode == 0:
                EpisodeDict[str(episode)] = str(
                    complete[regular[FirstOfSeason + 1][2]][0])
            elif addiction < len(SPECIAL):
                if episode in SPECIAL:
                    season = complete[regular[count][2]][0]
                    EpisodeDict[str(episode)] = str(
                        complete[regular[count][2]][0]) if season.startswith(
                            '0') else '0x' + platformtools.dialog_numeric(
                                0, item.title + '?', '')
                    addiction = addiction + 1
                else:
                    EpisodeDict[str(episode)] = str(regular[number][0])
            elif number <= len(regular):
                EpisodeDict[str(episode)] = str(regular[number][0])
            else:
                try:
                    EpisodeDict[str(episode)] = str(complete[regular[number +
                                                                     2][2]][0])
                except:
                    EpisodeDict[str(episode)] = '0x0'

            # Aggiunge numerazione agli Episodi

            item.title = typo(EpisodeDict[str(episode)] + ' - ',
                              typography) + item.title

        # Scrive Dizionario Episodi sul json
        EpisodeDict = base64.b64encode(json.dumps(EpisodeDict))
        dict_series[TITLE][TAG_EPISODE] = EpisodeDict
        jsontools.update_node(dict_series, item.channel,
                              TAG_TVSHOW_RENUMERATE)[0]

    else:
        heading = config.get_localized_string(70704)
        ID = platformtools.dialog_numeric(0, heading)
        dict_series[TITLE][TAG_ID] = ID
        jsontools.update_node(dict_series, item.channel,
                              TAG_TVSHOW_RENUMERATE)[0]
        if ID == '0':
            return itemlist
        else:
            return make_list(itemlist, item, typography, dict_series, ID,
                             SEASON, EPISODE, MODE, TITLE)
Example #5
0
def rename(File):
    jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath'))
    json = jsontools.load(open(filetools.join(jsonPath, File), "r").read())
    filePath = filetools.join(
        xbmc.translatePath(config.get_setting('downloadpath')),
        json['downloadFilename'])

    if json['infoLabels']['mediatype'] == 'movie':
        if filetools.isdir(filePath):
            extension = ''
            files = filetools.listdir(filePath)
            oldName = json['downloadFilename']
            newName = json['backupFilename']
            for f in files:
                ext = os.path.splitext(f)[-1]
                if ext in extensions_list: extension = ext
                filetools.rename(filetools.join(filePath, f),
                                 f.replace(oldName, newName))
            filetools.rename(filePath, newName)
            jsontools.update_node(filetools.join(newName, newName + extension),
                                  File, 'downloadFilename', jsonPath)

        else:
            oldName = json['downloadFilename']
            newName = json['backupFilename'] + os.path.splitext(oldName)[-1]
            filetools.rename(filePath, newName)
            jsontools.update_node(newName, File, 'downloadFilename', jsonPath)
    else:
        sep = '/' if filePath.lower().startswith("smb://") else os.sep
        FolderName = json['backupFilename'].split(sep)[0]
        Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName)
        if filetools.isdir(filePath):
            files = filetools.listdir(filePath)
            file_dict = {}
            for f in files:
                title = process_filename(f, Title, ext=False)
                ext = os.path.splitext(f)[-1]
                name = os.path.splitext(f)[0]
                if title not in file_dict and ext in extensions_list:
                    file_dict[title] = name

            for title, name in file_dict.items():
                for f in files:
                    if name in f:
                        filetools.rename(filetools.join(filePath, f),
                                         f.replace(name, title))

            filetools.rename(filePath, FolderName)
            jsontools.update_node(FolderName, File, 'downloadFilename',
                                  jsonPath)
        else:
            filename = filetools.split(filePath)[-1]
            title = process_filename(filename, Title)
            NewFolder = filetools.join(config.get_setting('downloadpath'),
                                       FolderName)
            if not filetools.isdir(NewFolder):
                filetools.mkdir(NewFolder)
            from_folder = filetools.join(config.get_setting('downloadpath'),
                                         filename)
            to_folder = filetools.join(config.get_setting('downloadpath'),
                                       FolderName, title)
            filetools.move(from_folder, to_folder)
            jsontools.update_node(filetools.join(FolderName, title), File,
                                  'downloadFilename', jsonPath)
Example #6
0
def elementum_monitor():
    # from core.support import dbg;dbg()
    path = xbmc.translatePath(config.get_setting('downloadlistpath'))
    elementum_setting, elementum_host, TorrentPath = setting()
    # active_torrent = filetools.listdir(TorrentPath)
    # logger.debug('ELEMENTUM:', elementum_setting, elementum_host, TorrentPath)

    if elementum_setting:
        # check if command file exist
        if filetools.isfile(monitor):
            json = jsontools.load(open(monitor, "r").read())
            Monitor = json['monitor']
        # else create it
        else:
            Monitor = jsontools.load('{"monitor":{},"settings":{}}')
            json = jsontools.dump(Monitor)
            filetools.write(monitor, json, silent=True)

        if len(Monitor) > 0:
            try:
                data = requests.get(elementum_host + '/list', timeout=2).json()
            except:
                data = ''
            if data:
                # from core.support import dbg;dbg()
                for it in data:
                    progress = round(it['progress'], 2)
                    status = it['status']
                    name = it['id']
                    if name in Monitor:
                        jsontools.update_node(progress,
                                              Monitor[name]['file'],
                                              'downloadProgress',
                                              path,
                                              silent=True)
                        jsontools.update_node(4,
                                              Monitor[name]['file'],
                                              'downloadStatus',
                                              path,
                                              silent=True)
                        if status in ['Paused']:
                            jsontools.update_node(0,
                                                  Monitor[name]['file'],
                                                  'downloadStatus',
                                                  path,
                                                  silent=True)
                        if status in [
                                'Seeding', 'Finished'
                        ] and not config.get_setting('elementum_on_seed'):
                            monitor_update(TorrentPath, name, remove=True)
                            dlJson = jsontools.load(
                                open(
                                    filetools.join(path,
                                                   Monitor[name]['file']),
                                    "r").read())
                            jsontools.update_node(dlJson['downloadSize'],
                                                  Monitor[name]['file'],
                                                  'downloadCompleted',
                                                  path,
                                                  silent=True)
                            jsontools.update_node(2,
                                                  Monitor[name]['file'],
                                                  'downloadStatus',
                                                  path,
                                                  silent=True)
                            requests.get(elementum_host + 'pause/' + name)
                            filetools.remove(
                                filetools.join(TorrentPath, name + '.torrent'))
                            filetools.remove(
                                filetools.join(TorrentPath,
                                               name + '.fastresume'))