Beispiel #1
0
def write_batch_id_files(tv_ids, movie_ids, misc_ids):
    if len(tv_ids) > 0:
        shows_import_file_path = "special://profile/addon_data/plugin.video.metalliq/shows_to_add.txt"
        if xbmcvfs.exists(shows_import_file_path): os.remove(xbmc.translatePath(shows_import_file_path))
        tv_id_list = ""
        for id in tv_ids:
            tv_id_list = tv_id_list + str(id) + '\n'
        if not xbmcvfs.exists(shows_import_file_path):
            batch_add_file = xbmcvfs.File(shows_import_file_path, 'w')
            batch_add_file.write(tv_id_list)
            batch_add_file.close()
        dialogs.notify(msg='Converting tvshows, seasons & episodes', title='to id-list for batch-adding', delay=3000, image=get_icon_path("tvshows"))
    if len(movie_ids) > 0:
        movies_import_file_path = "special://profile/addon_data/plugin.video.metalliq/movies_to_add.txt"
        if xbmcvfs.exists(movies_import_file_path): os.remove(xbmc.translatePath(movies_import_file_path))
        movie_id_list = ""
        for id in movie_ids:
            movie_id_list = movie_id_list + str(id) + '\n'
        if not xbmcvfs.exists(movies_import_file_path):
            batch_add_file = xbmcvfs.File(movies_import_file_path, 'w')
            batch_add_file.write(movie_id_list)
            batch_add_file.close()
        dialogs.notify(msg='Converting movies', title='to id-list for batch-adding', delay=3000, image=get_icon_path("movies"))
    if len(misc_ids) > 0:
        misc_import_file_path = "special://profile/addon_data/plugin.video.metalliq/misc_to_add.txt"
        if xbmcvfs.exists(misc_import_file_path): os.remove(xbmc.translatePath(misc_import_file_path))
        misc_id_list = ""
        for id in misc_ids:
            misc_id_list = misc_id_list + str(id) + '\n'
        if not xbmcvfs.exists(misc_import_file_path):
            batch_add_file = xbmcvfs.File(misc_import_file_path, 'w')
            batch_add_file.write(misc_id_list)
            batch_add_file.close()
        dialogs.notify(msg='Converting miscellaneous', title='to id-list for batch-adding', delay=3000, image=get_icon_path("tvshows"))
Beispiel #2
0
def batch_add_movies_to_library(library_folder, id):
    if id == None:
        return
    changed = False
    movie_folder = os.path.join(library_folder, str(id)+'/')
    if not xbmcvfs.exists(movie_folder):
        try: xbmcvfs.mkdir(movie_folder)
        except: pass
        player_filepath = os.path.join(movie_folder, 'player.info')
        player_file = xbmcvfs.File(player_filepath, 'w')
        content = "{0}".format(plugin.get_setting(SETTING_MOVIES_DEFAULT_PLAYER_FROM_LIBRARY, unicode))
        player_file.write(content)
        player_file.close()
    # create nfo file
    nfo_filepath = os.path.join(movie_folder, str(id)+ "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) + ".nfo")
    if not xbmcvfs.exists(nfo_filepath):
        changed = True
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        content = "http://www.imdb.com/title/%s/" % str(id)
        nfo_file.write(content)
        nfo_file.close()
    strm_filepath = os.path.join(movie_folder, str(id) + "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) + ".strm")
    src = "imdb"
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        try:
            content = plugin.url_for("movies_play", src=src, id=id, mode='library')
            strm_file.write(content)
            strm_file.close()
        except:
            pass
#    if xbmc.getCondVisibility("system.hasaddon(script.qlickplay)"): xbmc.executebuiltin("RunScript(script.qlickplay,info=afteradd)")
#    elif xbmc.getCondVisibility("system.hasaddon(script.extendedinfo)"): xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
    return changed
Beispiel #3
0
def add_channel_to_library(library_folder, channel, play_plugin = None):
    changed = False
    # create channel folder
    channel_folder = os.path.join(library_folder, str(channel)+'/')
    if not xbmcvfs.exists(channel_folder):
        try: 
            xbmcvfs.mkdir(channel_folder)
        except:
            pass
    # create nfo file
    nfo_filepath = os.path.join(channel_folder, str(channel)+".nfo")
    if not xbmcvfs.exists(nfo_filepath):
        changed = True
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        content = "%s" % str(channel)
        nfo_file.write(content)
        nfo_file.close()
    # Create play with file
    if play_plugin is not None:
        player_filepath = os.path.join(channel_folder, 'player.info')
        player_file = xbmcvfs.File(player_filepath, 'w')
        content = "{0}".format(play_plugin)
        player_file.write(content)
        player_file.close()
    # create strm file
    strm_filepath = os.path.join(channel_folder, str(channel)+".strm")
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        content = plugin.url_for("live_play", channel=channel, program="None", language="en", mode="library")
        strm_file.write(content)
        strm_file.close()
    return changed
Beispiel #4
0
def batch_add_tvshows_to_library(library_folder, show):
    id = show['id']
    showname = to_utf8(show['seriesname'])
    playlist_folder = plugin.get_setting(SETTING_TV_PLAYLIST_FOLDER, unicode)
    if not xbmcvfs.exists(playlist_folder):
        try: xbmcvfs.mkdir(playlist_folder)
        except: dialogs.notify(msg=_('Creation of [COLOR ff0084ff]M[/COLOR]etalli[COLOR ff0084ff]Q[/COLOR] Playlist Folder'), title=_('Failed'), delay=5000, image=get_icon_path("lists"))
    playlist_file = os.path.join(playlist_folder, id+".xsp")
    if not xbmcvfs.exists(playlist_file):
        playlist_file = xbmcvfs.File(playlist_file, 'w')
        content = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><smartplaylist type="tvshows"><name>%s</name><match>all</match><rule field="path" operator="contains"><value>%s%s</value></rule><rule field="playcount" operator="is"><value>0</value></rule><order direction="ascending">numepisodes</order></smartplaylist>' % (showname, plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode).replace('special://profile',''), str(id))
        playlist_file.write(str(content))
        playlist_file.close()
    show_folder = os.path.join(library_folder, str(id)+'/')
    if not xbmcvfs.exists(show_folder):
        try: xbmcvfs.mkdir(show_folder)
        except: pass
    player_filepath = os.path.join(show_folder, 'player.info')
    player_file = xbmcvfs.File(player_filepath, 'w')
    content = "default"
    player_file.write(content)
    player_file.close()
    nfo_filepath = os.path.join(show_folder, 'tvshow.nfo')
    if not xbmcvfs.exists(nfo_filepath):
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        content = "http://thetvdb.com/index.php?tab=series&id=%s" % str(id)
        nfo_file.write(content)
        nfo_file.close()
    clean_needed = True
    return clean_needed
Beispiel #5
0
def write_list_id_files(misc_ids, tv_ids, movie_ids, slug, user):
    if len(misc_ids) > 0:
        misc_list_file_path = "special://home/userdata/addon_data/plugin.video.chappaai/misc_from_" + slug + "_by_" + user + ".txt"
        if xbmcvfs.exists(misc_list_file_path):
            os.remove(xbmc.translatePath(misc_list_file_path))
        misc_id_list = ""
        for id in misc_ids:
            misc_id_list = misc_id_list + str(id) + '\n'
        if not xbmcvfs.exists(misc_list_file_path):
            batch_add_file = xbmcvfs.File(misc_list_file_path, 'w')
            batch_add_file.write(misc_id_list)
            batch_add_file.close()
    if len(tv_ids) > 0:
        shows_list_file_path = "special://home/userdata/addon_data/plugin.video.chappaai/shows_from_" + slug + "_by_" + user + ".txt"
        if xbmcvfs.exists(shows_list_file_path):
            os.remove(xbmc.translatePath(shows_list_file_path))
        tv_id_list = ""
        for id in tv_ids:
            tv_id_list = tv_id_list + str(id) + '\n'
        if not xbmcvfs.exists(shows_list_file_path):
            batch_add_file = xbmcvfs.File(shows_list_file_path, 'w')
            batch_add_file.write(tv_id_list)
            batch_add_file.close()
    if len(movie_ids) > 0:
        movies_list_file_path = "special://home/userdata/addon_data/plugin.video.chappaai/movies_from_" + slug + "_by_" + user + ".txt"
        if xbmcvfs.exists(movies_list_file_path):
            os.remove(xbmc.translatePath(movies_list_file_path))
        movie_id_list = ""
        for id in movie_ids:
            movie_id_list = movie_id_list + str(id) + '\n'
        if not xbmcvfs.exists(movies_list_file_path):
            batch_add_file = xbmcvfs.File(movies_list_file_path, 'w')
            batch_add_file.write(movie_id_list)
            batch_add_file.close()
Beispiel #6
0
def add_movie_to_library(library_folder, src, id, date):
    changed = False

    # create nfo file
    nfo_filepath = os.path.join(library_folder, str(id) + ".nfo")
    if not xbmcvfs.exists(nfo_filepath):
        changed = True
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        if src == "imdb":
            content = "http://www.imdb.com/title/%s/" % str(id)
        else:
            content = "http://www.themoviedb.org/movie/%s" % str(id)
        nfo_file.write(content)
        nfo_file.close()
        if date and plugin.get_setting(SETTING_LIBRARY_SET_DATE,
                                       converter=bool):
            os.utime(nfo_filepath, (date, date))

    # create strm file
    strm_filepath = os.path.join(library_folder, str(id) + ".strm")
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        content = plugin.url_for("movies_play", src=src, id=id, mode='library')
        strm_file.write(content)
        strm_file.close()
        if date and plugin.get_setting(SETTING_LIBRARY_SET_DATE,
                                       converter=bool):
            os.utime(strm_filepath, (date, date))

    return changed
def list_library():
    while not xbmc.abortRequested and \
     (xbmc.getCondVisibility('Library.IsScanning') or \
     xbmc.getCondVisibility('Window.IsActive(progressdialog)') or \
     xbmc.getCondVisibility('Window.IsActive(extendedprogressdialog)')):
        xbmc.sleep(100)
    xbmc.sleep(5000)
    library = {}
    medias = ["movies", "tvshows"]
    #    medias = ["movies", "tvshows", "musicvideos", "music", "live"]
    for m in medias:
        if m == "movies":
            lib = plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode)
            prite = RPC.videolibrary.get_movies(properties=[
                "title", "year", "playcount", "fanart", "originaltitle",
                "imdbnumber", "thumbnail", "file"
            ])
            if "movies" in prite: ite = prite["movies"]
            else: ite = []
        elif m == "tvshows":
            lib = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
            prite = RPC.videolibrary.get_tvshows(properties=[
                "title", "year", "playcount", "fanart", "originaltitle",
                "imdbnumber", "thumbnail", "file"
            ])
            if "tvshows" in prite: ite = prite["tvshows"]
            else: ite = []
#        elif m == "musicvideos":
#            lib = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
#            ite = RPC.videolibrary.get_tvshows(properties=["title","year","playcount","fanart","originaltitle","imdbnumber","thumbnail","file"])["tvshows"]
        else:
            continue
        liq = xbmcvfs.listdir(lib)[0]
        for i in ite:
            try:
                f = xbmcvfs.File(
                    os.path.join(lib, i["imdbnumber"], "player.info"))
                i["player"] = f.read()
                f.close()
            except:
                i["player"] = "na"
        f = xbmcvfs.File("{0}library.nfo".format(lib), 'w')
        f.write(str(ite))
        f.close()
        if len(ite) > 0:
            players = dict(zip(ite[0],
                               zip(*[d.values() for d in ite])))["player"]
        else:
            players = "()"
        f = xbmcvfs.File("{0}players.nfo".format(lib), 'w')
        f.write(str(players))
        f.close()
Beispiel #8
0
def get_current_movie_players_from_library():
    library_folder = plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode)
    if not xbmcvfs.exists(library_folder): return
    folders = xbmcvfs.listdir(library_folder)[0]
    players_info = ""
    for folder in folders:
        player_file = xbmcvfs.File(os.path.join(library_folder, str(folder), "player.info"))
        content = player_file.read()
        players_info = players_info + "{0}|{1}".format(folder, content) + '\n'
        player_file.close()
    lib_players_file = xbmcvfs.File(library_folder + "players.info", 'w')
    lib_players_file.write(players_info)
    lib_players_file.close()
Beispiel #9
0
def export_movies_library():
    folder_path = plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode)
    if not xbmcvfs.exists(folder_path):
        return dialogs.notify(msg='Movies folder',
                              title='Absent',
                              delay=5000,
                              image=get_icon_path("movies"))
    ids = ""
    movies = xbmcvfs.listdir(folder_path)[0]
    if len(movies) < 1:
        return dialogs.notify(msg='Movies folder',
                              title='Empty',
                              delay=5000,
                              image=get_icon_path("movies"))
    else:
        for movie in movies:
            ids = ids + str(movie) + '\n'
    movies_backup_file_path = "special://profile/addon_data/plugin.video.metalliq/movies_to_add.bak"
    if xbmcvfs.exists(movies_backup_file_path):
        os.remove(xbmc.translatePath(movies_backup_file_path))
    if not xbmcvfs.exists(movies_backup_file_path):
        batch_add_file = xbmcvfs.File(movies_backup_file_path, 'w')
        batch_add_file.write(ids)
        batch_add_file.close()
    dialogs.notify(msg="Movies",
                   title="Backed up",
                   delay=5000,
                   image=get_icon_path("movies"))
Beispiel #10
0
def export_tv_library():
    folder_path = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
    if not xbmcvfs.exists(folder_path):
        return dialogs.notify(msg='TVShows folder',
                              title='Absent',
                              delay=5000,
                              image=get_icon_path("tv"))
    ids = ""
    shows = xbmcvfs.listdir(folder_path)[0]
    if len(shows) < 1:
        return dialogs.notify(msg='TVShows folder',
                              title='Empty',
                              delay=5000,
                              image=get_icon_path("tv"))
    else:
        for show in shows:
            ids = ids + str(show) + '\n'
    shows_backup_file_path = "special://profile/addon_data/plugin.video.metalliq/shows_to_add.bak"
    if xbmcvfs.exists(shows_backup_file_path):
        os.remove(xbmc.translatePath(shows_backup_file_path))
    if not xbmcvfs.exists(shows_backup_file_path):
        batch_add_file = xbmcvfs.File(shows_backup_file_path, 'w')
        batch_add_file.write(ids)
        batch_add_file.close()
    dialogs.notify(msg="TVShows",
                   title="Backed up",
                   delay=5000,
                   image=get_icon_path("tv"))
Beispiel #11
0
def get_players(media, filters={}):
    assert media in ("tvshows", "movies", "musicvideos", "music", "live")
    players = []
    players_path = "special://home/userdata/addon_data/{0}/players/".format(
        plugin.id)
    files = [
        x for x in xbmcvfs.listdir(players_path)[1] if x.endswith(EXTENSION)
    ]
    for file in files:
        path = players_path + file
        try:
            f = xbmcvfs.File(path)
            try:
                content = f.read()
                meta = json.loads(content)
            finally:
                f.close()
            player = AddonPlayer(file, media, meta)
            if not player.is_empty():
                players.append(player)
        except Exception, e:
            plugin.log.error(repr(e))
            msg = "player %s is invalid" % file
            xbmcgui.Dialog().ok('Invalid player', msg)
            raise
Beispiel #12
0
def library_tv_strm(show, folder, id, season, episode):
    # Create season folder
    enc_season = ('Season %s' % season).translate(None, '\/:*?"<>|').strip('.')
    folder = os.path.join(folder, enc_season)
    try:
        xbmcvfs.mkdir(folder)
    except:
        pass
    # Create episode strm
    enc_name = 'S%02dE%02d' % (season, episode)
    stream = os.path.join(
        folder, enc_name +
        "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) + ".strm")
    if not xbmcvfs.exists(stream):
        file = xbmcvfs.File(stream, 'w')
        content = plugin.url_for("tv_play",
                                 id=id,
                                 season=season,
                                 episode=episode,
                                 mode='library')
        file.write(str(content))
        file.close()
        if plugin.get_setting(SETTING_LIBRARY_SET_DATE, bool):
            try:
                firstaired = show[season][episode]['firstaired']
                t = date_to_timestamp(firstaired)
                os.utime(stream, (t, t))
            except:
                pass
def add_movie_to_library(library_folder, src, id, play_plugin=None):
    changed = False
    # create movie folder
    movie_folder = os.path.join(library_folder, str(id) + '/')
    if not xbmcvfs.exists(movie_folder):
        try:
            xbmcvfs.mkdir(movie_folder)
        except:
            pass
        # Create play with file
        if play_plugin is not None:
            player_filepath = os.path.join(movie_folder, 'player.info')
            player_file = xbmcvfs.File(player_filepath, 'w')
            content = "{0}".format(play_plugin)
            player_file.write(content)
            player_file.close()
    # create nfo file
    nfo_filepath = os.path.join(
        movie_folder,
        str(id) + "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) +
        ".nfo")
    if not xbmcvfs.exists(nfo_filepath):
        changed = True
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        if src == "imdb":
            content = "http://www.imdb.com/title/%s/" % str(id)
        else:
            content = "http://www.themoviedb.org/movie/%s" % str(id)
        nfo_file.write(content)
        nfo_file.close()
    # create strm file
    strm_filepath = os.path.join(
        movie_folder,
        str(id) + "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) +
        ".strm")
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        content = plugin.url_for("movies_play", src=src, id=id, mode='library')
        strm_file.write(content)
        strm_file.close()


#    if xbmc.getCondVisibility("system.hasaddon(script.qlickplay)"): xbmc.executebuiltin("RunScript(script.qlickplay,info=afteradd)")
#    elif xbmc.getCondVisibility("system.hasaddon(script.extendedinfo)"): xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
#    xbmc.executebuiltin("RunScript(script.artworkdownloader,mediatype=movie,dbid=%s)" % xbmc.getInfoLabel('ListItem.DBID'))
    return changed
Beispiel #14
0
def get_tv_player_plugin_from_library(id):
    # Specified by user
    try:
        library_folder = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
        player_file = xbmcvfs.File(os.path.join(library_folder, str(id), "player.info"))
        content = player_file.read()
        player_file.close()
        if content: return content
    except: pass
    return None
Beispiel #15
0
def get_player_plugin_from_library(library_channel):
    # Specified by user
    try:
        library_folder = plugin.get_setting(SETTING_LIVE_LIBRARY_FOLDER)
        player_file = xbmcvfs.File(os.path.join(library_folder, str(channel), "player.info"))
        content = player_file.read()
        player_file.close()
        if content:
            return content
    except:
        pass
Beispiel #16
0
def batch_add_movies_to_library(library_folder, id):
    if id == None:
        return
    changed = False
    movie_folder = os.path.join(library_folder, str(id) + '/')
    if not xbmcvfs.exists(movie_folder):
        try:
            xbmcvfs.mkdir(movie_folder)
        except:
            pass
    nfo_filepath = os.path.join(movie_folder, str(id) + ".nfo")
    if not xbmcvfs.exists(nfo_filepath):
        changed = True
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        content = "http://www.imdb.com/title/%s/" % str(id)
        nfo_file.write(content)
        nfo_file.close()
    strm_filepath = os.path.join(movie_folder, str(id) + ".strm")
    src = "imdb"
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        try:
            content = plugin.url_for("movies_play",
                                     src=src,
                                     id=id,
                                     mode='library')
            strm_file.write(content)
            strm_file.close()
        except:
            pass
    if xbmc.getCondVisibility("system.hasaddon(script.qlickplay)"):
        xbmc.executebuiltin("RunScript(script.qlickplay,info=afteradd)")
    if xbmc.getCondVisibility("system.hasaddon(script.extendedinfo)"):
        xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
    return changed
Beispiel #17
0
def set_movie_library_player(path):
    # get active players
    players = active_players("movies")
    players.insert(0, ADDON_SELECTOR)
    players.insert(0, ADDON_DEFAULT)
    # let the user select one player
    selection = dialogs.select("{0}".format(_("Select %s") % "{0} {1}".format(_("Default").lower(), _("Player").lower())), [p.title for p in players])
    if selection == -1:
        return
    # get selected player
    player = players[selection]
    # Create play with file
    player_filepath = os.path.join(path, 'player.info')
    player_file = xbmcvfs.File(player_filepath, 'w')
    content = "{0}".format(player.id)
    player_file.write(content)
    player_file.close()
Beispiel #18
0
def get_movie_player_plugin_from_library(id):
    # Specified by user
    try:
        if not str(id).startswith("tt"):
            import_tmdb()
            movie = tmdb.Movies(id).info()
            imdb_id = movie.get('imdb_id')
        else: imdb_id = id
        if imdb_id:
            src = "imdb"
            id = imdb_id
            library_folder = plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode)
            player_file = xbmcvfs.File(os.path.join(library_folder, str(id), "player.info"))
            content = player_file.read()
            player_file.close()
        if content: return content
    except: pass
    return None
Beispiel #19
0
def set_library_player(path):
    # get active players
    players = active_players("tvshows")
    players.insert(0, ADDON_SELECTOR)
    players.insert(0, ADDON_DEFAULT)
    # let the user select one player
    selection = dialogs.select(_("Select default player"),
                               [p.title for p in players])
    if selection == -1:
        return
    # get selected player
    player = players[selection]

    # Create Choose Your Channel...le
    player_filepath = os.path.join(path, 'player.info')
    player_file = xbmcvfs.File(player_filepath, 'w')
    content = "{0}".format(player.id)
    player_file.write(content)
    player_file.close()
Beispiel #20
0
def add_tvshow_to_library(library_folder, show, play_plugin = None):
    clean_needed = False
    
    id = show['id']
    showname = to_utf8(show['seriesname'])

    ## Create show folder
    enc_show = showname.translate(None, '\/:*?"<>|').strip('.')
    show_folder = os.path.join(library_folder, str(id)+'/')
    if not xbmcvfs.exists(show_folder):
        try: 
            xbmcvfs.mkdir(show_folder)
        except:
            pass

        # Create play with file
        if play_plugin is not None:
            player_filepath = os.path.join(show_folder, 'player.info')
            player_file = xbmcvfs.File(player_filepath, 'w')
            content = "{0}".format(play_plugin)
            player_file.write(content)
            player_file.close()
            
        # Create nfo file
        nfo_filepath = os.path.join(show_folder, 'tvshow.nfo')
        if not xbmcvfs.exists(nfo_filepath):
            nfo_file = xbmcvfs.File(nfo_filepath, 'w')
            content = "http://thetvdb.com/index.php?tab=series&id=%s" % str(id)
            nfo_file.write(content)
            nfo_file.close()

    ## Get existing items in library
    
    # get all ids of the show
    ids = [id, show.get('imdb_id', None)]   # TODO: add tmdb!
    ids = [x for x in ids if x]

    # get show episodes in library
    try:
#        if not plugin.get_setting(SETTING_CHECK_LIBRARY_DUPS, converter=bool):
#            raise Exception()

        # get tvshow from library
        libshows = RPC.VideoLibrary.GetTVShows(properties=["imdbnumber", "title", "year"])['tvshows']
        libshows = [i for i in libshows if str(i['imdbnumber']) in ids or (str(i['year']) == str(show.get('year', 0)) and equals(show['seriesname'], i['title']))]
        libshow = libshows[0]
        
        # get existing (non strm) episodes in library
        libepisodes = RPC.VideoLibrary.GetEpisodes(filter={"and": [ {"field": "tvshow", "operator": "is", "value": to_utf8(libshow['title'])}]}, properties=["season", "episode", "file"])['episodes']
        libepisodes = [(int(i['season']), int(i['episode'])) for i in libepisodes if not i['file'].endswith(".strm")]
    except:
        libepisodes = []
    
    ## Create content strm files
    for (season_num,season) in show.items():
        if season_num == 0: # or not season.has_aired():
            continue
            
        for (episode_num, episode) in season.items():
            if episode_num == 0:
                continue
            
            delete = False
            if not episode.has_aired(flexible=True):
                delete = True
                #break
            
            if delete or (season_num, episode_num) in libepisodes:
                if library_tv_remove_strm(show, show_folder, id, season_num, episode_num):
                    clean_needed = True
            else:
                library_tv_strm(show, show_folder, id, season_num, episode_num)

    files, dirs = xbmcvfs.listdir(show_folder)
    if not dirs:
        shutil.rmtree(show_folder)
        clean_needed = True
                
    return clean_needed
Beispiel #21
0
def lists_trakt_add_all_to_library(user, slug):
    items = lists_trakt_show_list(user, slug)
    tv_ids = []
    movie_ids = []
    for item in items:
        if not isinstance(item, type):
            if "/tv/" in str(item):
                if "/tv/play/" in str(item):
                    pre_tvdb = str(item).split(" (plugin://plugin.video.metalliq/tv/play/")
                    pro_tvdb = str(pre_tvdb[1]).split("/")
                    tvdb = str(pro_tvdb[0])
                    if not tvdb in tv_ids: tv_ids.append(tvdb)
                elif "/tv/tvdb/" in str(item):
                    pre_tvdb = str(item).split(" (plugin://plugin.video.metalliq/tv/tvdb/")
                    if "/" in str(pre_tvdb[1]): pro_tvdb = str(pre_tvdb[1]).split("/")
                    else: pro_tvdb = str(pre_tvdb[1]).split(")")
                    tvdb = str(pro_tvdb[0])
                    if not tvdb in tv_ids: tv_ids.append(tvdb)
            elif "/movies/" in str(item):
                if "/tmdb/" in str(item):
                    pre_tmdb = str(item).split(" (plugin://plugin.video.metalliq/movies/play/tmdb/")
                    pro_tmdb = str(pre_tmdb[1]).split("/")
                    tmdb = str(pro_tmdb[0])
                    if not tmdb in movie_ids: movie_ids.append(tmdb)
                elif "/imdb/" in str(item):
                    pre_imdb = str(item).split(" (plugin://plugin.video.metalliq/movies/play/imdb/")
                    pro_imdb = str(pre_imdb[1]).split("/")
                    imdb = str(pro_imdb[0])
                    if not imdb in movie_ids: movie_ids.append(imdb)
        else:
            if "tvshowtitle" in str(item["info"]):
                if item["info"]["tvdb_id"] != None and item["info"]["tvdb_id"] != "" and str(item["info"]["tvdb_id"]) not in tv_ids: tv_ids.append(str(item["info"]["tvdb_id"]))
                elif item["info"]["imdb_id"] != None and item["info"]["imdb_id"] != "" and str(item["info"]["imdb_id"]) not in tv_ids: tv_ids.append(str(item["info"]["imdb_id"]))
            else:
                if item["info"]["tmdb"] != None and item["info"]["tmdb"] != "" and str(item["info"]["tmdb"]) not in movie_ids: movie_ids.append(str(item["info"]["tmdb"]))
                elif item["info"]["imdb_id"] != None and item["info"]["imdb_id"] != "" and str(item["info"]["imdb_id"]) not in movie_ids: movie_ids.append(str(item["info"]["imdb_id"]))
    if len(tv_ids) > 0:
        shows_list_file_path = "special://profile/addon_data/plugin.video.metalliq/shows_from_" + slug + "_by_" + user + ".txt"
        shows_import_file_path = "special://profile/addon_data/plugin.video.metalliq/shows_to_add.txt"
        if xbmcvfs.exists(shows_list_file_path): os.remove(xbmc.translatePath(shows_import_file_path))
        if xbmcvfs.exists(shows_import_file_path): os.remove(xbmc.translatePath(shows_import_file_path))
        tv_id_list = ""
        for id in tv_ids:
            tv_id_list = tv_id_list + str(id) + '\n'
        if not xbmcvfs.exists(shows_list_file_path):
            batch_add_file = xbmcvfs.File(shows_list_file_path, 'w')
            batch_add_file.write(tv_id_list)
            batch_add_file.close()
        if not xbmcvfs.exists(shows_import_file_path):
            batch_add_file = xbmcvfs.File(shows_import_file_path, 'w')
            batch_add_file.write(tv_id_list)
            batch_add_file.close()
        plugin.notify(msg='TVShows, seasons & episodes', title='Converted to list.txt', delay=3000, image=get_icon_path("tvshows"))
    if len(movie_ids) > 0:
        movies_list_file_path = "special://profile/addon_data/plugin.video.metalliq/movies_from_" + slug + "_by_" + user + ".txt"
        movies_import_file_path = "special://profile/addon_data/plugin.video.metalliq/movies_to_add.txt"
        if xbmcvfs.exists(movies_list_file_path): os.remove(xbmc.translatePath(movies_import_file_path))
        if xbmcvfs.exists(movies_import_file_path): os.remove(xbmc.translatePath(movies_import_file_path))
        movie_id_list = ""
        for id in movie_ids:
            movie_id_list = movie_id_list + str(id) + '\n'
        if not xbmcvfs.exists(movies_list_file_path):
            batch_add_file = xbmcvfs.File(movies_list_file_path, 'w')
            batch_add_file.write(movie_id_list)
            batch_add_file.close()
        if not xbmcvfs.exists(movies_import_file_path):
            batch_add_file = xbmcvfs.File(movies_import_file_path, 'w')
            batch_add_file.write(movie_id_list)
            batch_add_file.close()
        plugin.notify(msg='Movies', title='Converted to list.txt', delay=3000, image=get_icon_path("movies"))
    plugin.notify(msg='Generating', title='.strm-files', delay=3000, image=get_icon_path("metalliq"))
    xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq/movies/batch_add_to_library)")
Beispiel #22
0
def add_tvshow_to_library(library_folder, show, play_plugin=None):
    clean_needed = False
    id = show['id']
    showname = to_utf8(show['seriesname'])
    if showname == "None" or showname == None:
        show_folder = os.path.join(library_folder, str(id) + '/')
        if os.path.isdir(show_folder): return shutil.rmtree(show_folder)
    playlist_folder = plugin.get_setting(SETTING_TV_PLAYLIST_FOLDER, unicode)
    if not xbmcvfs.exists(playlist_folder):
        try:
            xbmcvfs.mkdir(playlist_folder)
        except:
            dialogs.notify(msg=_(
                'Creation of [COLOR limegreen]M[/COLOR]etalli[COLOR limegreen]Q[/COLOR] 4[COLOR limegreen]Q[/COLOR]ed Playlist Folder'
            ),
                           title=_('Failed'),
                           delay=5000,
                           image=get_icon_path("lists"))
    playlist_file = os.path.join(playlist_folder, id + ".xsp")
    if not xbmcvfs.exists(playlist_file):
        playlist_file = xbmcvfs.File(playlist_file, 'w')
        content = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><smartplaylist type="tvshows"><name>%s</name><match>all</match><rule field="path" operator="contains"><value>%s%s</value></rule><rule field="playcount" operator="is"><value>0</value></rule><order direction="ascending">numepisodes</order></smartplaylist>' % (
            showname, plugin.get_setting(
                SETTING_TV_LIBRARY_FOLDER, str).replace(
                    'special://profile', ''), str(id))
        playlist_file.write(str(content))
        playlist_file.close()
    ## Create show folder
    enc_show = showname.translate(None, '\/:*?"<>|').strip('.')
    show_folder = os.path.join(library_folder, str(id) + '/')
    if not xbmcvfs.exists(show_folder):
        try:
            xbmcvfs.mkdir(show_folder)
        except:
            pass
        # Create play with file
        if play_plugin is not None:
            player_filepath = os.path.join(show_folder, 'player.info')
            player_file = xbmcvfs.File(player_filepath, 'w')
            content = "{0}".format(play_plugin)
            player_file.write(content)
            player_file.close()
        # Create nfo file
        nfo_filepath = os.path.join(show_folder, 'tvshow.nfo')
        if not xbmcvfs.exists(nfo_filepath):
            nfo_file = xbmcvfs.File(nfo_filepath, 'w')
            content = "http://thetvdb.com/index.php?tab=series&id=%s" % str(id)
            nfo_file.write(content)
            nfo_file.close()
    ## Get existing items in library
    # get all ids of the show
    ids = [id, show.get('imdb_id', None)]  # TODO: add tmdb!
    ids = [x for x in ids if x]
    # get show episodes in library
    try:
        # get tvshow from library
        libshows = RPC.VideoLibrary.GetTVShows(
            properties=["imdbnumber", "title", "year"])['tvshows']
        libshows = [
            i for i in libshows if str(i['imdbnumber']) in ids or (
                str(i['year']) == str(show.get('year', 0))
                and equals(show['seriesname'], i['title']))
        ]
        libshow = libshows[0]
        # get existing (non strm) episodes in library
        libepisodes = RPC.VideoLibrary.GetEpisodes(
            filter={
                "and": [{
                    "field": "tvshow",
                    "operator": "is",
                    "value": to_utf8(libshow['title'])
                }]
            },
            properties=["season", "episode", "file"])['episodes']
        libepisodes = [(int(i['season']), int(i['episode']))
                       for i in libepisodes if not i['file'].endswith(".strm")]
    except:
        libepisodes = []
    ## Create content strm files
    for (season_num, season) in show.items():
        if season_num == 0:  # or not season.has_aired():
            continue
        for (episode_num, episode) in season.items():
            if episode_num == 0:
                continue
            delete = False
            if plugin.get_setting(SETTING_AIRED_UNKNOWN, bool) == True:
                aired_unknown = True
            else:
                aired_unknown = False
            if not episode.has_aired(flexible=aired_unknown):
                delete = True
                #break
            if delete or (season_num, episode_num) in libepisodes:
                if library_tv_remove_strm(show, show_folder, id, season_num,
                                          episode_num):
                    clean_needed = True
            else:
                library_tv_strm(show, show_folder, id, season_num, episode_num)
    files, dirs = xbmcvfs.listdir(show_folder)
    if not dirs:
        shutil.rmtree(show_folder)
        clean_needed = True


#    if xbmc.getCondVisibility("system.hasaddon(script.qlickplay)"): xbmc.executebuiltin("RunScript(script.qlickplay,info=afteradd)")
#    elif xbmc.getCondVisibility("system.hasaddon(script.extendedinfo)"): xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
    return clean_needed
Beispiel #23
0
def add_music_to_library(library_folder, artist_name, album_name, track_name):
    # replace non valid path characters with _
    safe_artist_name = to_utf8(re.sub('[^\w\-_\. ]', '_', artist_name))
    safe_album_name = to_utf8(re.sub('[^\w\-_\. ]', '_', album_name))
    safe_track_name = to_utf8(re.sub('[^\w\-_\. ]', '_', track_name))

    changed = False
    artist_info = lastfm.get_artist_info(artist_name)
    album_info = lastfm.get_album_info(artist_name, album_name)
    # create nfo file
    artist_folder = os.path.join(library_folder, safe_artist_name)
    album_folder = os.path.join(artist_folder, safe_album_name)
    if not xbmcvfs.exists(artist_folder):
        xbmcvfs.mkdir(artist_folder)
    if not xbmcvfs.exists(album_folder):
        xbmcvfs.mkdir(album_folder)
    nfo_artist_path = os.path.join(artist_folder, "artist.nfo")
    nfo_album_path = os.path.join(album_folder, "album.nfo")
    track_info = lastfm.get_track_info(artist_name, track_name)
    track_number = ""
    if "album" in track_info:
        track_number = track_info["album"]["@attr"]["position"]
        if track_number != "" and track_number != None:
            full_track_name = track_number + ". " + safe_track_name
        else:
            full_track_name = safe_track_name
    else:
        full_track_name = safe_track_name
    nfo_track_path = os.path.join(album_folder, full_track_name + ".nfo")
    if not xbmcvfs.exists(nfo_artist_path):
        changed = True
        image = artist_info["image"][-1]["#text"]
        nfo_file = xbmcvfs.File(nfo_artist_path, 'w')
        content = "<artist>\n" \
                  "  <name>{0}</name>\n" \
                  "  <thumb>{1}</thumb>\n" \
                  "</artist>".format(artist_name, image)
        nfo_file.write(content)
        nfo_file.close()

    if not xbmcvfs.exists(nfo_album_path):
        changed = True
        image = album_info["image"][-1]["#text"]
        nfo_file = xbmcvfs.File(nfo_album_path, 'w')
        content = "<album>\n" \
                  "  <title>{0}</title>\n" \
                  "  <artist>{1}</artist>\n" \
                  "  <thumb>{2}</thumb>\n" \
                  "</album>".format(album_name, artist_name, image)
        nfo_file.write(content)
        nfo_file.close()

    if not xbmcvfs.exists(nfo_track_path):
        changed = True
        track_info = lastfm.get_track_info(artist_name, track_name)
        track_number = ""
        if "album" in track_info:
            track_number = track_info["album"]["@attr"]["position"]
        nfo_file = xbmcvfs.File(nfo_track_path, 'w')
        content = "<musicvideo>\n" \
                  "  <title>{0}</title>\n" \
                  "  <artist>{1}</artist>\n" \
                  "  <album>{2}</album>\n" \
                  "  <track>{3}</track>\n" \
                  "</musicvideo>".format(to_utf8(track_name),
                                         artist_name,
                                         album_name,
                                         track_number)
        nfo_file.write(content)
        nfo_file.close()

    # create strm file
    strm_filepath = os.path.join(album_folder, full_track_name + ".strm")
    if not xbmcvfs.exists(strm_filepath):
        changed = True
        track_info = lastfm.get_track_info(artist_name, track_name)
        track_number = ""
        if "album" in track_info:
            track_number = track_info["album"]["@attr"]["position"]
            strm_filepath = os.path.join(
                album_folder, track_number + ". " + safe_track_name + ".strm")
        strm_file = xbmcvfs.File(strm_filepath, 'w')
        content = plugin.url_for("music_play",
                                 artist_name=artist_name,
                                 track_name=track_name,
                                 album_name=album_name,
                                 mode='library')
        strm_file.write(content)
        strm_file.close()
    # create thumbnails
    thumb_album_path = os.path.join(artist_folder, "folder.jpg")
    if not xbmcvfs.exists(thumb_album_path):
        changed = True
        r = requests.get(artist_info["image"][-1]["#text"], stream=True)
        if r.status_code == 200:
            try:
                with open(thumb_album_path, 'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw, f)
            except:
                pass
    thumb_album_path = os.path.join(album_folder, "folder.jpg")
    if not xbmcvfs.exists(thumb_album_path):
        changed = True
        try:
            r = requests.get(album_info["image"][-1]["#text"], stream=True)
            if r.status_code == 200:
                with open(thumb_album_path, 'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw, f)
        except:
            pass
    return changed
Beispiel #24
0
def patch(mode):
    import xbmcaddon
    adir = "special://home/addons/"
    AUTOS = eval(plugin.get_setting(SETTING_AUTOPATCHES, unicode))
    #    try: AUTOS = plugin.get_setting(SETTING_AUTOPATCHES, unicode)
    #    except: AUTOS = [[], [], [], []]
    #    return [p for p in get_players() if p.id in AUTOS]
    #    xbmc.log("QQQQQ AUTOS = {0}".format(str(AUTOS)), xbmc.LOGNOTICE)
    INSTALLED = [i for i in xbmcvfs.listdir(adir)[0]]
    PATCHES = [
        [], ["resources/lib/modules/control.py", "pass", "sys.exit()"],
        [
            "default.py", "",
            "\n    cool_down_active = kodi.get_setting('cool_down') == 'true'\n    if not salts_utils.is_salts() or cool_down_active:\n        kodi.notify(msg=i18n('playback_limited'))\n        return False"
        ],
        [
            "lib/dudehere/routines/scrapers/__init__.py", "",
            "\n\t\tif self._caller not in ALLOWED_CALLERS and self._caller: \n\t\t\tplugin.log('Caller not allowed')\n\t\t\tplugin.raise_error('Violation', 'This addon is not allowed.', 'Please do not use %s with %s' % (self._caller, ADDON_NAME))\n\t\t\tif return_sources:\n\t\t\t\treturn [], [], []\n\t\t\telse:\n\t\t\t\treturn []"
        ]
    ]
    if mode == "auto":
        if AUTOS != [[], [], [], []]:
            ADDONS = AUTOS
        else:
            if dialogs.yesno(
                    '{0}: Patch'.format(plugin.name),
                    '{0}.[CR]{1} & {2}'.format(
                        _("%s not found") % 'Auto-patches', _("Enable"),
                        _("Continue?"))):
                return patch("all")
            else:
                plugin.set_setting(SETTING_AUTOPATCH, "false")
                return
    else:
        ADDONS = [
            [],
            [
                i for i in INSTALLED if i.startswith("plugin.video.")
                and xbmcvfs.exists("{0}{1}/{2}".format(adir, i, PATCHES[1][0]))
            ],
            [
                i for i in INSTALLED if i.startswith("plugin.video.")
                and xbmcvfs.exists("{0}{1}/{2}".format(adir, i, PATCHES[2][0]))
            ],
            [
                i for i in INSTALLED if i.startswith("script.module.")
                and xbmcvfs.exists("{0}{1}/{2}".format(adir, i, PATCHES[3][0]))
            ]
        ]
    count = 0
    for i in range(1, len(ADDONS)):
        for a in ADDONS[i]:
            count = count + 1
            b = "{0}{1}/{2}".format(adir, a, PATCHES[i][0])
            c = xbmcvfs.File(b)
            d = c.read()
            c.close()
            if PATCHES[i][2] in d:
                ADDON = xbmcaddon.Addon(a)
                if mode == "auto" or dialogs.yesno(
                        '{0}: Patch "{1}"?'.format(plugin.name,
                                                   ADDON.getAddonInfo("name")),
                        '"{0}" {1} block-code.[CR]{2}'.format(
                            ADDON.getAddonInfo("name"), _("contains"),
                            _("Would you like to remove it from the library?").
                            replace(_("Library").lower(),
                                    _("Add-on").lower()))):
                    h = xbmcvfs.File(b, 'w')
                    d = d.replace(PATCHES[i][2], PATCHES[i][1])
                    result = h.write(d)
                    h.close()
                    if mode != "auto" and dialogs.yesno(
                            "{0}: {1} Patch?".format(plugin.name, _("Auto")),
                            '"{0}"[CR]{1} {2} re-patching?'.format(
                                ADDON.getAddonInfo("name"), _("Enable"),
                                _("Auto").lower())):
                        if ADDON.getAddonInfo("id") not in AUTOS[i]:
                            AUTOS[i].append(ADDON.getAddonInfo("id"))
    if AUTOS != [[], [], [], []] and AUTOS != ADDONS:
        plugin.set_setting(SETTING_AUTOPATCHES, AUTOS)