Exemplo n.º 1
0
def create_new_trash_path(config=Config(), path='.trash'):
    """Specify the path to the trash."""
    log_config(config=config)
    logging.info('function: ' + inspect.stack()[0][3])
    logging.info('result: ')
    code = Codes.GOOD

    if not confirmation(config):
        code = Codes.NOT_CONFIRMATION
        return code

    try:
        if os.path.basename(path)[0] == '.':
            hidden_trash = os.path.abspath(path)
        else:
            hidden_trash = os.path.abspath(path)[:-os.path.basename(path).__len__()] + '.' + os.path.basename(path)

        if not config.dry:
            os.makedirs(hidden_trash)
            config.path_to_trash = hidden_trash
            write_config(config)

        message(config, 'New trash path: {path}'.format(path=hidden_trash))
        logging.info('New trash path: {path}'.format(path=hidden_trash))
    except OSError:
        message(config, 'Such folder already exists')
        message(config, 'Remains the trash path: {path}'.format(path=config.path_to_trash))
        logging.error('Such folder already exists')
        logging.error('Remains the trash path: {path}'.format(path=config.path_to_trash))
        code = Codes.CONFLICT
    return code
Exemplo n.º 2
0
def clearing_trash(config=Config()):
    """Clear the contents of the trash."""
    log_config(config=config)
    logging.info('function: ' + inspect.stack()[0][3])
    logging.info('result: ')
    code = Codes.GOOD

    if not confirmation(config):
        code = Codes.NOT_CONFIRMATION
        return code

    try:
        if not config.dry:
            shutil.rmtree(config.path_to_trash)

        message(config, "Trash cleared")
        logging.info("Trash cleared")
    except OSError:
        message(config, "Trash already cleared")
        logging.info("Trash already cleared")
        code = Codes.BAD
    finally:
        if not config.dry:
            last_cleaning_date = datetime.datetime.now()
            config.last_cleaning_date['year'] = last_cleaning_date.year
            config.last_cleaning_date['month'] = last_cleaning_date.month
            config.last_cleaning_date['day'] = last_cleaning_date.day
            config.last_cleaning_date['hour'] = last_cleaning_date.hour
            config.last_cleaning_date['minute'] = last_cleaning_date.minute
            config.last_cleaning_date['second'] = last_cleaning_date.second
            config.last_cleaning_date['microsecond'] = last_cleaning_date.microsecond
            write_config(config)
            os.makedirs(config.path_to_trash)
    return code
Exemplo n.º 3
0
def create_new_log_path(config=Config(), path='.log_myrm'):
    """Specify the path to the log."""
    log_config(config=config)
    logging.info('function: ' + inspect.stack()[0][3])
    logging.info('result: ')
    code = Codes.GOOD
    marker = '_itislogfilemyrm_'
    if not confirmation(config):
        code = Codes.NOT_CONFIRMATION
        return code

    try:
        if (os.path.basename(path)[0] == '.'
            and os.path.basename(path)[os.path.basename(path).__len__() - marker.__len__():] != marker):
            hidden_log = os.path.abspath(path) + marker
        elif (os.path.basename(path)[0] == '.'
              and os.path.basename(path)[os.path.basename(path).__len__() - marker.__len__():] == marker):
            hidden_log = os.path.abspath(path)
        elif (os.path.basename(path)[0] != '.'
              and os.path.basename(path)[os.path.basename(path).__len__() - marker.__len__():] != marker):
            hidden_log = (os.path.abspath(path)[:-os.path.basename(path).__len__()] + '.'
                          + os.path.basename(path) + marker)
        else:
            hidden_log = (os.path.abspath(path)[:-os.path.basename(path).__len__()] + '.'
                          + os.path.basename(path))

        if not config.dry:
            with open(hidden_log, 'w'):
                pass
            config.path_to_log = hidden_log
            write_config(config)

        message(config, 'New log path: {path}'.format(path=hidden_log))
        logging.info('New log path: {path}'.format(path=hidden_log))
    except IOError:
        message(config, 'incorrect path')
        message(config, 'Remains the log path: {path}'.format(path=config.path_to_log))
        logging.error('incorrect path')
        logging.error('Remains the log path: {path}'.format(path=config.path_to_log))
        code = Codes.BAD
    except OSError:
        code = Codes.BAD
    return code
Exemplo n.º 4
0
def main():

    # set path for relativistic imports if not launched as package
    try:
        sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
        import file_add
        import auth
        import edit_config
        import file_ops
        import cron_handle

    # using relativistic imports directly if launched as package
    except ImportError:
        from . import file_add
        from . import auth
        from . import edit_config
        from . import file_ops
        from . import cron_handle

    GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = file_add.client_secrets
    gauth = auth.drive_auth(0)  # parameter to reset GAccount permissions
    drive = GoogleDrive(gauth)

    arguments = sys.argv[1:]

    # if function called without any arguments print version info
    if len(arguments) == 0:
        p_info("ver")

    arg_index = 0

    while True:

        if arg_index >= len(arguments):
            break

        elif arguments[arg_index] == "-v" or arguments[
                arg_index] == "-version" or arguments[arg_index] == "version":
            p_info("ver")

        elif arguments[arg_index] == "-h" or arguments[
                arg_index] == "-help" or arguments[arg_index] == "help":
            p_info("help")

        elif arguments[arg_index] == "-re" or arguments[
                arg_index] == "-reset" or arguments[arg_index] == "reset":
            auth.reset_account()

        elif arguments[arg_index] == "-st" or arguments[
                arg_index] == "-start" or arguments[arg_index] == "start":
            cron_handle.cron_process(drive, "start")

        elif arguments[arg_index] == "-x" or arguments[
                arg_index] == "-stop" or arguments[arg_index] == "stop":
            cron_handle.cron_process(drive, "stop")

        elif arguments[arg_index] == "-y" or arguments[
                arg_index] == "-status" or arguments[arg_index] == "status":
            cron_handle.cron_process(drive, "status")

        elif arguments[arg_index] == "-c" or arguments[
                arg_index] == "-config" or arguments[arg_index] == "config":
            edit_config.write_config()

        elif arguments[arg_index] == "-d" or arguments[
                arg_index] == "-download" or arguments[arg_index] == "download":
            arg_index += 1
            if is_matching(arg_index, len(arguments)):
                # download entire drive folder
                if arguments[arg_index] == "all":
                    file_list = drive.ListFile({
                        'q':
                        "'root' in parents and trashed=false"
                    }).GetList()
                    for argument in file_list:
                        file_ops.f_down(drive, argument,
                                        edit_config.down_addr())
                # download only specified folder
                else:
                    for argument in arguments[arg_index:len(arguments)]:
                        file_ops.f_down(drive, argument,
                                        edit_config.down_addr())
                arg_index = len(arguments)  # all arguments used up by download

        elif arguments[arg_index] == "-u" or arguments[
                arg_index] == "-upload" or arguments[arg_index] == "upload":
            arg_index += 1
            if is_matching(arg_index, len(arguments)):
                # adding to root folder hence None
                file_ops.f_create(
                    drive, arguments[arg_index], None,
                    str(file_add.get_f_name(arguments[arg_index])), True)

        elif arguments[arg_index] == "-s" or arguments[
                arg_index] == "-share" or arguments[arg_index] == "share":
            arg_index += 1
            if is_matching(arg_index, len(arguments)):
                file_ops.share_link(drive, arguments[arg_index], True)

        elif arguments[arg_index] == "-r" or arguments[
                arg_index] == "-remove" or arguments[arg_index] == "remove":
            arg_index += 2
            # in case of less arguments than required
            if is_matching(arg_index, len(arguments)):
                file_ops.f_remove(drive, arguments[arg_index - 1],
                                  arguments[arg_index:len(arguments)])
                arg_index = len(arguments)

        elif arguments[arg_index] == "-o" or arguments[
                arg_index] == "-open" or arguments[arg_index] == "open":
            arg_index += 1
            if is_matching(arg_index, len(arguments)):
                file_ops.f_open(arguments[arg_index])

        elif arguments[arg_index] == "-ls_files" or arguments[arg_index] == "-laf" or \
                arguments[arg_index] == "ls_files":
            arg_index += 1
            if is_matching(arg_index, len(arguments)):
                file_ops.f_list(drive, arguments[arg_index], 1)

        elif arguments[arg_index] == "-ls" or arguments[
                arg_index] == "-l" or arguments[arg_index] == "ls":
            if (arg_index + 1) < len(arguments):
                if arguments[arg_index + 1] == "remote":
                    arg_index += 1
                    file_ops.f_list(drive, "all", 0)
                # list of files in downloads directory
                elif arguments[arg_index + 1] == "local":
                    arg_index += 1
                    file_ops.f_list_local()
                # no argument matching -ls
                else:
                    file_ops.f_list(drive, "all", 0)

            # no argument after -ls
            else:
                file_ops.f_list(drive, "all", 0)

        elif arguments[arg_index] == "-ls_trash" or arguments[
                arg_index] == "-lt" or arguments[arg_index] == "ls_trash":
            file_ops.f_list(drive, "trash", 0)

        elif arguments[arg_index] == "-ls_folder" or arguments[arg_index] == "-lf" or \
                arguments[arg_index] == "ls_folder":
            arg_index += 1  # increase arg_index to read the query argument
            if is_matching(arg_index, len(arguments)):
                file_ops.f_list(drive, arguments[arg_index], 0)

        else:
            print(
                str(arguments[arg_index]) +
                " is an unrecognised argument. Please report if you know this is an error"
                ".\n\n")
            p_info("arg")

        arg_index += 1
Exemplo n.º 5
0
def auto_clear_trash(config=Config()):
    """Clear automatically the contents of the trash."""
    def sort_by_count_slash(string):
        count_slash = 0
        for char in string:
            if char == '/':
                count_slash = count_slash + 1
        return count_slash

    code = Codes.GOOD
    log_config(config=config)
    logging.info('function: ' + inspect.stack()[0][3])
    logging.info('result: ')

    if not confirmation(config):
        code = Codes.NOT_CONFIRMATION
        return code

    if not config.dry:
        list_of_files = []
        list_of_dirs = []

        for dirpath, dirs, files in os.walk(config.path_to_trash):
            iteration_files = 0
            iteration_dirs = 0
            total_files = len(files)
            total_dirs = len(dirs)

            for file in files:
                if config.show_bar_status:
                    iteration_files += 1
                    print_progress_bar(iteration_files,
                                       total_files,
                                       config=config,
                                       prefix='Progress counting files:',
                                       suffix='Complete',
                                       length=50)
                list_of_files.append(
                    os.path.abspath(os.path.join(dirpath, file)))
            for dir in dirs:
                if config.show_bar_status:
                    iteration_dirs += 1
                    print_progress_bar(iteration_dirs,
                                       total_dirs,
                                       config=config,
                                       prefix='Progress counting dirs:',
                                       suffix='Complete',
                                       length=50)
                list_of_dirs.append(os.path.abspath(os.path.join(dirpath,
                                                                 dir)))

        list_of_dirs.sort(key=sort_by_count_slash, reverse=True)
        iteration_files = 0
        iteration_dirs = 0
        total_files = len(list_of_files)
        total_dirs = len(list_of_dirs)

        for file in list_of_files:
            if config.show_bar_status:
                iteration_files += 1
                print_progress_bar(iteration_files,
                                   total_files,
                                   config=config,
                                   prefix='Progress remove files:',
                                   suffix='Complete',
                                   length=50)
            os.remove(file)

        for dir in list_of_dirs:
            if config.show_bar_status:
                iteration_dirs += 1
                print_progress_bar(iteration_dirs,
                                   total_dirs,
                                   config=config,
                                   prefix='Progress remove dirs:',
                                   suffix='Complete',
                                   length=50)
            os.rmdir(dir)

    message(config, 'Automatic cleaning of the trash occurred')
    logging.info('Automatic cleaning of the trash occurred')

    if not config.dry:
        last_cleaning_date = datetime.datetime.now()
        config.last_cleaning_date['year'] = last_cleaning_date.year
        config.last_cleaning_date['month'] = last_cleaning_date.month
        config.last_cleaning_date['day'] = last_cleaning_date.day
        config.last_cleaning_date['hour'] = last_cleaning_date.hour
        config.last_cleaning_date['minute'] = last_cleaning_date.minute
        config.last_cleaning_date['second'] = last_cleaning_date.second
        config.last_cleaning_date[
            'microsecond'] = last_cleaning_date.microsecond
        write_config(config)
    return code
Exemplo n.º 6
0
def edit_settings(dry=False, silent=False, with_confirmation=False, policy=0,
                  auto_cleaning=False, show_bar_status=False, time=None, size=None,
                  resolve_conflict=False, level_log=sys.maxint, config=Config()):
    """Editing program settings."""
    log_config(config=config)
    logging.info('function: ' + inspect.stack()[0][3])
    logging.info('result: ')
    code = Codes.GOOD

    if not confirmation(config):
        code = Codes.NOT_CONFIRMATION
        return code

    config.dry = dry
    config.silent = silent
    config.with_confirmation = with_confirmation
    config.policy = policy
    config.call_auto_cleaning_if_memory_error = auto_cleaning
    config.show_bar_status = show_bar_status
    config.resolve_conflict = resolve_conflict

    if level_log is sys.maxint or level_log is None:
        config.level_log = sys.maxint
        message(config, 'Logging is disabled')
        logging.info('Logging is disabled')
    else:
        config.level_log = level_log
        message(config, 'The following level of logging is set: {}'.format(level_log))
        logging.info('The following level of logging is set: {}'.format(level_log))

    if time is not None:
        config.min_day_for_start_cleaning = time
        message(config, 'The minimum number of days for auto cleaning is set to {}'.format(time))
        logging.info('The minimum number of days for auto cleaning is set to {}'.format(time))

    if size is not None:
        config.max_size_for_start_cleaning = size
        message(config, 'The maximum basket size for cleaning is set to {}'.format(size))
        logging.info('The maximum basket size for cleaning is set to {}'.format(size))

    write_config(config)

    if config.dry:
        message(config, 'Now imitation of the program is on')
        logging.info('Now imitation of the program is on')
    else:
        message(config, 'Now imitation of the program is off')
        logging.info('Now imitation of the program is off')

    if config.silent:
        message(config, 'Now program operation without reports')
        logging.info('Now program operation without reports')
    else:
        message(config, 'Now program operation with reports')
        logging.info('Now program operation with reports')

    if config.resolve_conflict:
        message(config, 'Now the program will replace files')
        logging.info('Now the program will replace files')
    else:
        message(config, 'Now the program will not replace files')
        logging.info('Now the program will not replace files')

    if config.with_confirmation:
        message(config, 'Now all actions require confirmation')
        logging.info('Now all actions require confirmation')
    else:
        message(config, 'Now all actions don\'t require confirmation')
        logging.info('Now all actions don\'t require confirmation')

    if config.policy > 0:
        message(config, 'The size policy has been activated')
        logging.info('The size policy has been activated')
    elif config.policy == 0:
        message(config, 'The time and size policy has been activated')
        logging.info('The time and size policy has been activated')
    else:
        message(config, 'The time policy has been activated')
        logging.info('The time policy has been activated')

    if config.call_auto_cleaning_if_memory_error:
        message(config, 'The auto cleaning if memory error has been activated')
        logging.info('The auto cleaning if memory error has been activated')
    else:
        message(config, 'The auto cleaning if memory error has been deactivated')
        logging.info('The auto cleaning if memory error has been deactivated')

    if config.show_bar_status:
        message(config, 'The bar status has been activated')
        logging.info('The bar status has been activated')
    else:
        message(config, 'The bar status has been deactivated')
        logging.info('The bar status has been deactivated')
    return code