Initial script

This commit is contained in:
Jose134 2024-11-23 19:40:33 +01:00
parent 48ce242088
commit de7109b580

95
src/main.py Normal file
View File

@ -0,0 +1,95 @@
import os
import shutil
import re
import json
import requests
def login_qbittorrent(api_url, username, password):
login_url = f'{api_url}/api/v2/auth/login'
data = {
'username': username,
'password': password
}
response = requests.post(login_url, data=data)
if response.status_code != 200 or response.text != 'Ok.':
print(f"Failed to login to qBittorrent: {response.status_code}")
return None
return response.cookies
def logout_qbittorrent(api_url, cookies):
response = requests.get(f'{api_url}/api/v2/auth/logout', cookies=cookies)
if response.status_code != 200 or response.text != 'Ok.':
print(f"Failed to logout from qBittorrent: {response.status_code}")
return False
return True
def get_qbittorrent_files_downloading(api_url, cookies):
ALLOWED_EXTENSIONS = ['mkv', 'mp4', 'avi', 'wmv', 'flv', 'mov', 'webm', 'mpg', 'mpeg']
response = requests.get(f'{api_url}/api/v2/torrents/info?filter=downloading', cookies=cookies)
if response.status_code != 200:
print(f"Failed to fetch data from qBittorrent API: {response.status_code}")
return []
torrents = response.json()
files = []
for torrent in torrents:
file_extension = torrent['name'].rpartition('.')[-1] if '.' in torrent['name'] else ''
if file_extension in ALLOWED_EXTENSIONS:
files.append(torrent['name'])
return files
def group_files_by_prefix(directory, patterns_str, downloading_files):
if not os.path.isdir(directory):
print(f"The directory {directory} does not exist.")
return
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files:
skip = False
for downloading_file in downloading_files:
if file.startswith(downloading_file):
print(f"File {file} is downloading. Skipping...")
skip = True
continue
if skip:
continue
for pattern_str in patterns_str:
pattern = re.compile(pattern_str)
match = pattern.match(file)
if match:
prefix_dir = os.path.join(directory, match.group(1))
if not os.path.exists(prefix_dir):
os.makedirs(prefix_dir)
shutil.move(os.path.join(directory, file), os.path.join(prefix_dir, file))
config_file_path = os.path.join(os.getcwd(), 'config', 'patterns.txt')
if os.path.isfile(config_file_path):
with open(config_file_path, 'r') as file:
patterns = [line.strip() for line in file if line.strip()]
else:
print(f"The config file {config_file_path} does not exist.")
patterns = []
if len(patterns) > 0:
# TODO: READ USER AND PASS FROM ENV FILE
cookies = login_qbittorrent('http://qbittorrent.xdarkbird.duckdns.org', 'USER', 'PASS')
downloading = get_qbittorrent_files_downloading('http://qbittorrent.xdarkbird.duckdns.org', cookies)
logout_qbittorrent('http://qbittorrent.xdarkbird.duckdns.org', cookies)
print(f"Patterns: {patterns}")
print(f"Downloading files: {downloading}")
group_files_by_prefix(os.path.join(os.getcwd(), 'testfiles'), patterns, downloading)