コード例 #1
0
ファイル: main.py プロジェクト: snemetz/tvnamer
def doMoveFile(cnamer, destDir=None, destFilepath=None, getPathPreview=False):
    """Moves file to destDir, or to destFilepath
    """

    if (destDir is None
            and destFilepath is None) or (destDir is not None
                                          and destFilepath is not None):
        raise ValueError("Specify only destDir or destFilepath")

    if not Config['move_files_enable']:
        raise ValueError(
            "move_files feature is disabled but doMoveFile was called")

    if Config['move_files_destination'] is None:
        raise ValueError(
            "Config value for move_files_destination cannot be None if move_files_enabled is True"
        )

    try:
        return cnamer.newPath(new_path=destDir,
                              new_fullpath=destFilepath,
                              always_move=Config['always_move'],
                              leave_symlink=Config['leave_symlink'],
                              getPathPreview=getPathPreview,
                              force=Config['overwrite_destination_on_move'])

    except OSError as e:
        if Config['skip_behaviour'] == 'exit':
            warn("Exiting due to error: %s" % e)
            raise SkipBehaviourAbort()
        warn("Skipping file due to error: %s" % e)
コード例 #2
0
ファイル: main.py プロジェクト: lanky/tvnamer
def doRenameFile(cnamer, newName):
    """Renames the file. cnamer should be Renamer instance,
    newName should be string containing new filename.
    """
    try:
        cnamer.newPath(new_fullpath = newName, force = Config['overwrite_destination_on_rename'], leave_symlink = Config['leave_symlink'])
    except OSError as e:
        if Config['skip_behaviour'] == 'exit':
            warn("Exiting due to error: %s" % e)
            raise SkipBehaviourAbort()
        warn("Skipping file due to error: %s" % e)
コード例 #3
0
def do_rename_file(cnamer, new_name):
    # type: (Renamer, str) -> None
    """Renames the file. cnamer should be Renamer instance,
    new_name should be string containing new filename.
    """
    try:
        cnamer.new_path(
            new_fullpath=new_name,
            force=Config["overwrite_destination_on_rename"],
            leave_symlink=Config["leave_symlink"],
        )
    except OSError as e:
        if Config["skip_behaviour"] == "exit":
            warn("Exiting due to error: %s" % e)
            raise SkipBehaviourAbort()
        warn("Skipping file due to error: %s" % e)
コード例 #4
0
def do_move_file(cnamer,
                 dest_dir=None,
                 dest_filepath=None,
                 get_path_preview=False):
    # type: (Renamer, Optional[str], Optional[str], bool) -> Optional[str]
    """Moves file to dest_dir, or to dest_filepath
    """

    if (dest_dir, dest_filepath).count(None) != 1:
        raise ValueError("Specify only dest_dir or dest_filepath")

    if not Config["move_files_enable"]:
        raise ValueError(
            "move_files feature is disabled but do_move_file was called")

    if Config["move_files_destination"] is None:
        raise ValueError(
            "Config value for move_files_destination cannot be None if move_files_enabled is True"
        )

    try:
        return cnamer.new_path(
            new_path=dest_dir,
            new_fullpath=dest_filepath,
            always_move=Config["always_move"],
            leave_symlink=Config["leave_symlink"],
            get_path_preview=get_path_preview,
            force=Config["overwrite_destination_on_move"],
        )

    except OSError as e:
        if Config["skip_behaviour"] == "exit":
            warn("Exiting due to error: %s" % e)
            raise SkipBehaviourAbort()
        warn("Skipping file due to error: %s" % e)
        return None
コード例 #5
0
ファイル: main.py プロジェクト: snemetz/tvnamer
def processFile(tvdb_instance, episode):
    """Gets episode name, prompts user for input
    """
    p("#" * 20)
    p("# Processing file: %s" % episode.fullfilename)

    if len(Config['input_filename_replacements']) > 0:
        replaced = applyCustomInputReplacements(episode.fullfilename)
        p("# With custom replacements: %s" % (replaced))

    # Use force_name option. Done after input_filename_replacements so
    # it can be used to skip the replacements easily
    if Config['force_name'] is not None:
        episode.seriesname = Config['force_name']

    p("# Detected series: %s (%s)" %
      (episode.seriesname, episode.number_string()))

    try:
        episode.populateFromTvdb(tvdb_instance,
                                 force_name=Config['force_name'],
                                 series_id=Config['series_id'])
    except (DataRetrievalError, ShowNotFound) as errormsg:
        if Config['always_rename'] and Config['skip_file_on_error'] is True:
            if Config['skip_behaviour'] == 'exit':
                warn("Exiting due to error: %s" % errormsg)
                raise SkipBehaviourAbort()
            warn("Skipping file due to error: %s" % errormsg)
            return
        else:
            warn(errormsg)
    except (SeasonNotFound, EpisodeNotFound, EpisodeNameNotFound) as errormsg:
        # Show was found, so use corrected series name
        if Config['always_rename'] and Config['skip_file_on_error']:
            if Config['skip_behaviour'] == 'exit':
                warn("Exiting due to error: %s" % errormsg)
                raise SkipBehaviourAbort()
            warn("Skipping file due to error: %s" % errormsg)
            return

        warn(errormsg)

    cnamer = Renamer(episode.fullpath)

    shouldRename = False

    if Config["move_files_only"]:

        newName = episode.fullfilename
        shouldRename = True

    else:
        newName = episode.generateFilename()
        if newName == episode.fullfilename:
            p("#" * 20)
            p("Existing filename is correct: %s" % episode.fullfilename)
            p("#" * 20)

            shouldRename = True

        else:
            p("#" * 20)
            p("Old filename: %s" % episode.fullfilename)

            if len(Config['output_filename_replacements']) > 0:
                # Show filename without replacements
                p("Before custom output replacements: %s" %
                  (episode.generateFilename(preview_orig_filename=False)))

            p("New filename: %s" % newName)

            if Config['always_rename']:
                doRenameFile(cnamer, newName)
                if Config['move_files_enable']:
                    if Config['move_files_destination_is_filepath']:
                        doMoveFile(cnamer=cnamer,
                                   destFilepath=getMoveDestination(episode))
                    else:
                        doMoveFile(cnamer=cnamer,
                                   destDir=getMoveDestination(episode))
                return

            elif Config['dry_run']:
                p("%s will be renamed to %s" % (episode.fullfilename, newName))
                if Config['move_files_enable']:
                    p("%s will be moved to %s" %
                      (newName, getMoveDestination(episode)))
                return

            ans = confirm("Rename?", options=['y', 'n', 'a', 'q'], default='y')

            if ans == "a":
                p("Always renaming")
                Config['always_rename'] = True
                shouldRename = True
            elif ans == "q":
                p("Quitting")
                raise UserAbort("User exited with q")
            elif ans == "y":
                p("Renaming")
                shouldRename = True
            elif ans == "n":
                p("Skipping")
            else:
                p("Invalid input, skipping")

            if shouldRename:
                doRenameFile(cnamer, newName)

    if shouldRename and Config['move_files_enable']:
        newPath = getMoveDestination(episode)
        if Config['dry_run']:
            p("%s will be moved to %s" %
              (newName, getMoveDestination(episode)))
            return

        if Config['move_files_destination_is_filepath']:
            doMoveFile(cnamer=cnamer,
                       destFilepath=newPath,
                       getPathPreview=True)
        else:
            doMoveFile(cnamer=cnamer, destDir=newPath, getPathPreview=True)

        if not Config['batch'] and Config['move_files_confirmation']:
            ans = confirm("Move file?", options=['y', 'n', 'q'], default='y')
        else:
            ans = 'y'

        if ans == 'y':
            p("Moving file")
            doMoveFile(cnamer, newPath)
        elif ans == 'q':
            p("Quitting")
            raise UserAbort("user exited with q")
コード例 #6
0
def process_file(tvdb_instance, episode):
    # type: (tvdb_api.Tvdb, BaseInfo) -> None
    """Gets episode name, prompts user for input
    """
    print("#" * 20)
    print("# Processing file: %s" % episode.fullfilename)

    if len(Config["input_filename_replacements"]) > 0:
        replaced = _apply_replacements_input(episode.fullfilename)
        print("# With custom replacements: %s" % (replaced))

    # Use force_name option. Done after input_filename_replacements so
    # it can be used to skip the replacements easily
    if Config["force_name"] is not None:
        episode.seriesname = Config["force_name"]

    print("# Detected series: %s (%s)" %
          (episode.seriesname, episode.number_string()))

    try:
        episode.populate_from_tvdb(
            tvdb_instance,
            force_name=Config["force_name"],
            series_id=Config["series_id"],
        )
    except (DataRetrievalError, ShowNotFound) as errormsg:
        if Config["always_rename"] and Config["skip_file_on_error"] is True:
            if Config["skip_behaviour"] == "exit":
                warn("Exiting due to error: %s" % errormsg)
                raise SkipBehaviourAbort()
            warn("Skipping file due to error: %s" % errormsg)
            return
        else:
            warn("%s" % (errormsg))
    except (SeasonNotFound, EpisodeNotFound, EpisodeNameNotFound) as errormsg:
        # Show was found, so use corrected series name
        if Config["always_rename"] and Config["skip_file_on_error"]:
            if Config["skip_behaviour"] == "exit":
                warn("Exiting due to error: %s" % errormsg)
                raise SkipBehaviourAbort()
            warn("Skipping file due to error: %s" % errormsg)
            return

        warn("%s" % (errormsg))

    cnamer = Renamer(episode.fullpath)

    should_rename = False

    if Config["move_files_only"]:

        new_name = episode.fullfilename
        should_rename = True

    else:
        new_name = episode.generate_filename()
        if new_name == episode.fullfilename:
            print("#" * 20)
            print("Existing filename is correct: %s" % episode.fullfilename)
            print("#" * 20)

            should_rename = True

        else:
            print("#" * 20)
            print("Old filename: %s" % episode.fullfilename)

            if len(Config["output_filename_replacements"]) > 0:
                # Show filename without replacements
                print("Before custom output replacements: %s" %
                      (episode.generate_filename(preview_orig_filename=False)))

            print("New filename: %s" % new_name)

            if Config["dry_run"]:
                print("%s will be renamed to %s" %
                      (episode.fullfilename, new_name))
                if Config["move_files_enable"]:
                    print("%s will be moved to %s" %
                          (new_name, get_move_destination(episode)))
                return
            elif Config["always_rename"]:
                do_rename_file(cnamer, new_name)
                if Config["move_files_enable"]:
                    if Config["move_files_destination_is_filepath"]:
                        do_move_file(
                            cnamer=cnamer,
                            dest_filepath=get_move_destination(episode))
                    else:
                        do_move_file(cnamer=cnamer,
                                     dest_dir=get_move_destination(episode))
                return

            ans = confirm("Rename?", options=["y", "n", "a", "q"], default="y")

            if ans == "a":
                print("Always renaming")
                Config["always_rename"] = True
                should_rename = True
            elif ans == "q":
                print("Quitting")
                raise UserAbort("User exited with q")
            elif ans == "y":
                print("Renaming")
                should_rename = True
            elif ans == "n":
                print("Skipping")
            else:
                print("Invalid input, skipping")

            if should_rename:
                do_rename_file(cnamer, new_name)

    if should_rename and Config["move_files_enable"]:
        new_path = get_move_destination(episode)
        if Config["dry_run"]:
            print("%s will be moved to %s" %
                  (new_name, get_move_destination(episode)))
            return

        if Config["move_files_destination_is_filepath"]:
            do_move_file(cnamer=cnamer,
                         dest_filepath=new_path,
                         get_path_preview=True)
        else:
            do_move_file(cnamer=cnamer,
                         dest_dir=new_path,
                         get_path_preview=True)

        if not Config["batch"] and Config["move_files_confirmation"]:
            ans = confirm("Move file?", options=["y", "n", "q"], default="y")
        else:
            ans = "y"

        if ans == "y":
            print("Moving file")
            do_move_file(cnamer, new_path)
        elif ans == "q":
            print("Quitting")
            raise UserAbort("user exited with q")