55 lines
1.9 KiB
Python
55 lines
1.9 KiB
Python
import os
|
|
from fastapi import BackgroundTasks, FastAPI
|
|
import logging
|
|
from dotenv import load_dotenv
|
|
from os import path
|
|
from qbittorrent_api import get_qbittorrent_files_downloading
|
|
from filemoving import group_files_by_prefix
|
|
from deduplication import deduplicate_files
|
|
import uuid
|
|
|
|
logger = logging.getLogger(__name__).setLevel(logging.INFO)
|
|
|
|
load_dotenv()
|
|
|
|
qbit_url = os.getenv('QB_URL')
|
|
qbit_user = os.getenv('QB_USER')
|
|
qbit_password = os.getenv('QB_PASSWORD')
|
|
target_dir = os.getenv('TARGET_DIR')
|
|
if not qbit_url or not qbit_user or not qbit_password or not target_dir:
|
|
logger.error("Please provide all the required environment variables.")
|
|
exit(1)
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
@app.get("/")
|
|
def root(background_tasks: BackgroundTasks):
|
|
job_id = str(uuid.uuid4())
|
|
logger.info(f"[{job_id}] Received request to start job.")
|
|
background_tasks.add_task(launch_job, job_id)
|
|
return job_id
|
|
|
|
def launch_job(job_id):
|
|
logger.info(f"[{job_id}] Fetching downloading files from qBittorrent.")
|
|
downloading = get_qbittorrent_files_downloading(qbit_url, qbit_user, qbit_password)
|
|
logger.info(f"[{job_id}] Found {len(downloading)} downloading files.")
|
|
|
|
logger.info(f"[{job_id}] Deduplicating files.")
|
|
deduplicate_files(target_dir, downloading)
|
|
|
|
logger.info(f"[{job_id}] Loading patterns.")
|
|
patterns = _load_patterns_file(job_id)
|
|
logger.info(f"[{job_id}] Using patterns: {patterns}")
|
|
logger.info(f"[{job_id}] Creating subdirectories and moving files.")
|
|
group_files_by_prefix(target_dir, downloading, patterns)
|
|
|
|
logger.info(f"[{job_id}] Job completed.")
|
|
|
|
def _load_patterns_file(job_id):
|
|
config_file_path = os.path.join(os.getcwd(), '..', 'config', 'patterns.txt')
|
|
if not path.exists(config_file_path):
|
|
logger.error(f"[{job_id}] The config file {config_file_path} does not exist.")
|
|
return []
|
|
with open(config_file_path, 'r') as file:
|
|
return [line.strip() for line in file if line.strip()] |