Files
random-file-picker/random_file_picker/cli.py
T

135 lines
4.6 KiB
Python
Executable File

"""
A script to randomly select files from a directory, open them, and allow the user to upload them to a Discord webhook, delete them, or skip to the next file.
You can specify a file size limit, whether to descend into subdirectories, and provide blacklist/whitelist patterns for file selection.
Here's an example usage:
./rand.py -fl 5 -d /path/to/directory --descend --blacklist "*.png" "*.mp4"
"""
import argparse
import os
import pathlib
import random
import sys
import termios
import tty
from random_file_picker.core import collect_files, move_file_to_meme_folder, upload_file
from random_file_picker.openers import open_file_with_geeqie, open_path_in_dolphin, open_path_with_default_app
IMG_EXTENSIONS = [
".jpg",
".jpeg",
".webp",
".png",
".gif",
]
def getch() -> str:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setcbreak(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def main():
parser = argparse.ArgumentParser(description="Random File Sender")
parser.add_argument('-fl', '--file-limit', type=int, default=10, help='Maximum file size in MB')
parser.add_argument('-d', '--directory', type=str, default='.', help='Directory to search for files')
parser.add_argument('--descend', action='store_true', help='Whether to descend into subdirectories')
parser.add_argument('--use-geeqie', action='store_true', help='Whether to use Geeqie as the image viewer')
parser._positionals.title = 'Positional arguments'
parser._optionals.title = 'Optional arguments'
# Globs for blacklisting and whitelisting, --blacklist "*.png" "*.mp4"
parser.add_argument('--blacklist', nargs='*', help='List of glob patterns to blacklist files')
parser.add_argument('--whitelist', nargs='*', help='List of glob patterns to whitelist files')
args = parser.parse_args()
file_limit: int = args.file_limit
directory: str = args.directory
descend: bool = args.descend
blacklist_patterns: list[str] = args.blacklist if args.blacklist else []
whitelist_patterns: list[str] = args.whitelist if args.whitelist else []
use_geeqie: bool = args.use_geeqie
print(f"File size limit set to {file_limit} MB")
search_path = pathlib.Path(directory)
if not search_path.exists() or not search_path.is_dir():
print(f"Directory '{directory}' does not exist or is not a directory.")
return
usable_files = collect_files(
search_path=search_path,
search_subdirectories=descend,
file_size_limit=file_limit,
blacklist_patterns=blacklist_patterns,
whitelist_patterns=whitelist_patterns,
)
if not usable_files:
print("No usable files found.")
return
pickFile = True
while pickFile:
file = random.choice(usable_files)
print(f"Random file: {file}")
if use_geeqie and str(file).lower().endswith(tuple(IMG_EXTENSIONS)):
open_file_with_geeqie(file)
else:
open_path_with_default_app(file)
selectionTime = True
while selectionTime:
print("Options: [u]pload, [n]ext, [d]elete, [f]older, [q]uit")
choice = getch().lower()
# Skip escape sequences (arrow keys)
if choice.encode("utf-8") == b'\x1b':
_ = getch() # Skip the next two characters
_ = getch()
continue
#print(choice.encode("utf-8")) # For debugging purposes
if choice == "u":
print("\nUploading...")
upload_file(file)
print(f"\nSuccessfully uploaded {file}")
print("Upload complete.")
#selectionTime = False
elif choice == "d":
print("\nDeleting...")
os.remove(file)
usable_files.remove(file)
selectionTime = False
elif choice == "n":
print("\nNext file...")
selectionTime = False
usable_files.remove(file)
elif choice == "f":
open_path_in_dolphin(file)
elif choice == "q":
print("\nQuitting...")
pickFile = False
break
elif choice == "m":
print("\nMoving to meme folder...")
move_file_to_meme_folder(file)
usable_files.remove(file)
selectionTime = False
else:
print(f"\n'{choice}' is an invalid option. Please choose again.")
if __name__ == "__main__":
main()