Beispiel #1
0
def logout(tg_client):
    """
        This function logs the user out.
    """

    file_log = get_logger()

    if not confirm("Are you sure you want to Logout?"):
        return

    task = tg_client.call_method("logOut", {})
    task.wait()

    if task.error_info:
        print("Oops something went wrong")
        file_log.error(task.error_info)
        return

    try:
        rmtree(GRAMUP_DIR)
    except FileNotFoundError:
        file_log.warning("Cache already cleared")

    file_log.info("Logged out")
    input("Logged out. Press enter to continue.")
    sys.exit(0)
Beispiel #2
0
def fix_failed_screenshot(cursor):
    print("Fix Base64 Decode Error due to failed screenshot")
    print()
    
    rows = cursor.execute("SELECT ID, Discriminator, FileName, length(FileContents) FROM Events WHERE Discriminator='ScreenshotEvent' AND FileContents like 'System.ComponentModel.Win32Exception: The handle is invalid%' ").fetchall()
    if len(rows):
        print("ID: Discriminator: FileName: Character Lengh of FileContents")
        options=[]

        terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split()
        for row in rows:
            row_filename=f"{str(row[2])}"
            max_filename_length = (50 * int(terminal_columns)) // 100
            if len(row_filename) < max_filename_length:
                string_row = f"{str(row[0])}: {str(row[1])}: {row_filename}: ({str(row[3])}) Chars"
            else:
                shortened_filename="..." + row_filename[-max_filename_length:]
                string_row = f"{str(row[0])}: {str(row[1])}: {shortened_filename}: ({str(row[3])}) Chars" 

            options.append(string_row)

        choices = enquiries.choose("Select a record to truncate...", options, multi=True)

        for choice in choices:
            truncation_record = re.split(r':\s', choice)
            if enquiries.confirm('Do you want to resolve {} ({})?'.format(str(truncation_record[0]),str(truncation_record[2]))):  
                print("Attempt to fix record: " + str(truncation_record[0]) )
                update_screenshots_in_events_table(cursor, truncation_record[0])
    else:
        print("Could not find any matching records showing evidence of stack trace where a SreenShot should be.")

    print("")
    fix_bad_things_menu(cursor)
Beispiel #3
0
def truncate_downloaded_files_events_table(cursor):
    print("Which Downloaded file do you wish to truncate?")
    print("")

    rows = cursor.execute("SELECT ID, Discriminator, FileName, length(FileContents) FROM Events WHERE Discriminator='DownloadEvent' ").fetchall()
    if len(rows):
        print("ID: Discriminator: FileName: Character Lengh of FileContents")
        options=[]

        terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split()
        for row in rows:
            row_filename=f"{str(row[2])}"
            max_filename_length = (50 * int(terminal_columns)) // 100
            if len(row_filename) < max_filename_length:
                string_row = f"{str(row[0])}: {str(row[1])}: {row_filename}: ({str(row[3])}) Chars"
            else:
                shortened_filename="..." + row_filename[-max_filename_length:]
                string_row = f"{str(row[0])}: {str(row[1])}: {shortened_filename}: ({str(row[3])}) Chars" 

            options.append(string_row)

        choices = enquiries.choose("Select a record to truncate...", options, multi=True)

        for choice in choices:
            truncation_record = re.split(r':\s', choice)
            if enquiries.confirm('Do you want to truncate {} ({})?'.format(str(truncation_record[0]),str(truncation_record[2]))):  
                print("Truncated record: " + str(truncation_record[0]) )
                update_downloads_in_events_table(cursor, truncation_record[0])

    else:
        print("Currently no downloads in the database.")
        print("")
    
    fix_bad_things_menu(cursor)
Beispiel #4
0
def change_folder(_):
    """
        This function allows user to change backup folder.
    """

    file_log = get_logger()

    try:
        with open(DATA_FILE, "rb") as db_file:
            db_dict = pickle.load(db_file)

    except FileNotFoundError:
        file_log.warning("No backup folders to change")
        db_dict = {}

    if not confirm(f"Currently {','.join(db_dict['back_up_folders'])} are backed-up. Do you want to change this?"):
        return

    db_dict["back_up_folders"] = get_folders()

    with open(DATA_FILE, "wb") as db_file:
        pickle.dump(db_dict, db_file)

    file_log.info("Backup Folders changed.")
    input("Backup Folders changed. Press any enter to continue.")
Beispiel #5
0
def get_folders(c_dir=None, selected_dirs=None):
    """
        This function shows a file chooser to select
        multiple directories.
    """

    if c_dir is None:
        c_dir = getcwd()

    selected_dirs = selected_dirs if selected_dirs else set([])

    dirs = {item for item in listdir(c_dir) if isdir(join(c_dir, item))}
    dirs = {item for item in dirs if join(c_dir, item) not in selected_dirs and item[0] != "."}

    options = ["Select This directory"]
    options.extend(dirs)
    options.append("⬅")

    info = f"You have selected : \n {','.join(selected_dirs)} \n" if len(selected_dirs) > 0 else "\n"
    choice = choose(f"{info}You are in {c_dir}", options)

    if choice == options[0]:
        selected_dirs.add(c_dir)

        if confirm("Do you want to select more folders?"):
            return get_folders(str(Path(c_dir).parent), selected_dirs)

        return selected_dirs

    if choice == options[-1]:
        return get_folders(str(Path(c_dir).parent), selected_dirs)

    return get_folders(join(c_dir, choice), selected_dirs)
Beispiel #6
0
def clear_cache(_):
    """
        This function clears all local caches.
    """

    if not confirm("Are you sure you want to clear all cache?"):
        return

    file_log = get_logger()

    try:
        rmtree(CACHE_DIR)
    except FileNotFoundError:
        file_log.warning("Cache already cleared")

    file_log.info("Cache cleared")
    input("Cache cleared. Press any enter to continue.")
Beispiel #7
0
    def handle(self) -> None:
        email = ""
        password = ""

        while not email:
            email = input("Email: ")

        while not password:
            password = getpass("Password: "******"Password stored for {email}")

        if enquiries.confirm(f"Use {email} as your default account?"):
            self.config["default_account"] = email
            save_config(self.config)
Beispiel #8
0
def change_chat(tg_client):
    """
        This function allows user to change backup folder.
    """

    file_log = get_logger()

    try:
        with open(DATA_FILE, "rb") as db_file:
            db_dict = pickle.load(db_file)

    except FileNotFoundError:
        file_log.warning("No backup folders to change")
        db_dict = {}
    if not confirm("If you change chat you will not be able to access previously backed-up files without changing back."
                   "Are you sure you want to change?"):
        return

    get_chat_id(tg_client, db_dict["phone_number"], db_dict["back_up_folders"])

    input("backup chat changed. Press any enter to continue.")
Beispiel #9
0
def truncate_downloaded_files_commandoutputs_table(cursor):
    print("Which Downloaded file do you wish to truncate?")
    print("")

    sql = ''' SELECT CommandOutputs.Id, GruntTaskings.Parameters , length(CommandOutputs.Output) FROM CommandOutputs 
                INNER JOIN GruntCommands ON GruntCommands.CommandOutputId = CommandOutputs.Id 
                INNER JOIN GruntTaskings ON GruntTaskings.GruntCommandId = GruntCommands.Id 
                INNER JOIN GruntTasks ON GruntTaskings.GruntTaskId = GruntTasks.Id 
                WHERE GruntTasks.Name = 'Download'
              '''
    rows = cursor.execute(sql).fetchall()
    if len(rows):
        print("ID: Discriminator: FileName: Character Lengh of FileContents")
        options=[]

        terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split()
        for row in rows:
            row_filename=f"{str(row[1])}"
            max_filename_length = (50 * int(terminal_columns)) // 100
            if len(row_filename) < max_filename_length:
                string_row = f"{str(row[0])}: {row_filename}: ({str(row[2])}) Chars"
            else:
                shortened_filename="..." + row_filename[-max_filename_length:]
                string_row = f"{str(row[0])}: {shortened_filename}: ({str(row[2])}) Chars" 

            options.append(string_row)

        choices = enquiries.choose("Select a record to truncate...", options, multi=True)

        for choice in choices:
            truncation_record = re.split(r':\s', choice)
            if enquiries.confirm('Do you want to truncate {} ({})?'.format(str(truncation_record[0]),str(truncation_record[1]))):  
                print("Truncated record: " + str(truncation_record[0]) )
                update_downloads_in_commandoutputs_table(cursor, truncation_record[0])

    else:
        print("Currently no downloads in the database.")
        print("")
    
    fix_bad_things_menu(cursor)
Beispiel #10
0
def login():
    """
        This function creates and authenticates Telegram client
        and calls the call_back with Telegram client, phone no
        and chat id as arguments.
    """

    (ph_no, chat_id, bup_folders) = load_data()

    tg_client = Telegram(api_id=API_ID,
                         api_hash=API_HASH,
                         files_directory=FILES_DIR,
                         database_encryption_key=DATABASE_ENCRYPTION_KEY,
                         tdlib_verbosity=0,
                         phone=ph_no)

    tg_client.call_method(
        "setTdlibParameters",
        {
            "use_file_database": True,
            "use_chat_info_database": True,
            "use_message_database": True,
            "application_version": VERSION
        },
    )

    if chat_id is None:
        print("A code has been sent to you via telegram.")

    try_login_with_code(tg_client)

    if chat_id is None:
        chat_id = get_chat_id(tg_client, ph_no, bup_folders)

        if confirm("Do you want to load previously backed-up file list?"):
            print("Getting file list, this might take some time...")
            tg_client.get_chats().wait()

    return tg_client, chat_id, bup_folders
Beispiel #11
0
        print("your password is: ", passman.get_password())
    elif choice == options[1]:
        print("adding a new password...")
        passman.add_password()
        #passman.save_new_passwords(pass_dict)
    elif choice == options[2]:
        print("getting password...")
        print("your password is: ", passman.get_password_menu(pass_dict))
    elif choice == options[3]:
        print("entering setting menu...")
        settings_choice = enquiries.choose('Choose one of these options: ',
                                           settings_options)
        if settings_choice == settings_options[0]:
            print("setting machine_id...")
            #passman.set_machine_id()
        elif settings_choice == settings_options[1]:
            print("creating master password...")
            passman.create_master_password()
            #passman.generate_key()
        elif settings_choice == settings_options[2]:
            print("exiting...")
            quit()
    elif choice == options[4]:
        print("exiting...")
        quit()

    if enquiries.confirm('yes to continue using passman, no to exit'):
        os.system('clear')
    else:
        quit()