Example #1
0
def op_rearrange_dir(mdb, args, mf, dry_run):
    def get_auto_create_dir_day(name):
        try:
            return datetime.datetime.strptime(name, '%Y%m%d')
        except ValueError:
            return None

    path = mdb.abspath(mf.relative_path)
    old_dir = os.path.dirname(path)
    old_day_dir = os.path.basename(os.path.dirname(old_dir))
    # If it's a directory created by user, then don't change it
    if get_auto_create_dir_day(old_day_dir) is None:
        return False

    correct_dir = get_file_dir(args.media_dir, path, mf.create_time)
    # If the current directory is correct, then don't do anything
    if correct_dir == os.path.dirname(path):
        return False

    if mf.create_time:
        logging.info("Rearrange file %s to %s" % (path, correct_dir))
    else:
        logging.info("File %s has no creation time, move it to %s" % (path, correct_dir))

    if dry_run:
        return

    if not os.path.isdir(correct_dir):
        os.makedirs(correct_dir)
    dst = os.path.join(correct_dir, mf.filename)

    # Move the file to the correct_dir
    ok, msg = copy_file(path, dst)
    if not ok:
        logging.error( 'Move file %s to %s failed: %s' % (path, correct_dir, msg))
        return False
    else:
        os.unlink(path)
        mdb.update(
                mf.id,
                path=dst,
                relative_path=mdb.relpath(dst))
        mdb.commit()

        if not os.listdir(old_dir):
            # old dir is empty, delete it
            logging.info("Directory %s is empty, so delete it." % old_dir)
            os.rmdir(old_dir)
        return True
Example #2
0
            def _copy():
                if args.dry_run:
                    return False
                ok, msg = copy_file(src, dst)
                if not ok:
                    logging.error( 'Copy %s to %s failed: %s' % (src, dst, msg))
                    return False

                dst_mf = MediaFile(path=dst, relative_path=right_mdb.relpath(dst))
                # copied file's middle_md5 should be same as the src_mf's middle_md5
                if dst_mf.middle_md5 == src_mf.middle_md5:
                    # copy success
                    right_mdb.add_mf(dst_mf)
                    return True
                else:
                    # copy failed
                    logging.error("Copied file's middle_md5 dose not match, copy failed: %s." % src)
                    os.unlink(dst)
                    return False