Skip to content

Commit

Permalink
chore(qbtools): refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
buroa committed Oct 8, 2024
1 parent c2c0757 commit 880fdde
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 50 deletions.
16 changes: 8 additions & 8 deletions qbtools/commands/orphaned.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


def __init__(app, logger):
logger.info(f"Checking for orphaned files on disk not in qBittorrent...")
logger.info("Checking for orphaned files on disk not in qBittorrent...")

completed_dir = app.client.application.preferences.save_path
categories = [
Expand All @@ -16,20 +16,20 @@ def __init__(app, logger):

def delete(item_path):
if app.dry_run:
logger.info(f"Skipping {item_path} because --dry-run was specified")
logger.info("Skipping %s because --dry-run was specified", item_path)
return

try:
if os.path.isfile(item_path):
os.remove(item_path)
logger.info(f"Deleted file {item_path}")
logger.info("Deleted file %s", item_path)
elif os.path.isdir(item_path):
shutil.rmtree(item_path)
logger.info(f"Deleted folder {item_path}")
logger.info("Deleted folder %s", item_path)
else:
logger.debug(f"{item_path} does not exist")
logger.debug("%s does not exist", item_path)
except Exception as e:
logger.error(f"An error occurred: {e}")
logger.error("An error occurred: %s", e)

def cleanup_dir(folder_path, owned_files):
"""
Expand All @@ -47,7 +47,7 @@ def cleanup_dir(folder_path, owned_files):
for pattern in exclude_patterns
):
logger.info(
f"Skipping {item_path} because it matches an exclude pattern"
"Skipping %s because it matches an exclude pattern", item_path
)
continue

Expand All @@ -57,7 +57,7 @@ def cleanup_dir(folder_path, owned_files):
owned_subfiles = set(
filter(lambda x: x.startswith(item_path), owned_files)
)
if len(owned_subfiles) == 0 and item_path not in categories:
if not owned_subfiles and item_path not in categories:
delete(item_path)
else:
cleanup_dir(item_path, owned_subfiles)
Expand Down
24 changes: 14 additions & 10 deletions qbtools/commands/prune.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,43 @@ def __init__(app, logger):

if not categories:
logger.info(
f"No torrents can be pruned since no categories were included based on selectors"
"No torrents can be pruned since no categories were included based on selectors"
)

torrents = app.client.torrents.info()
torrents = list(
filter(lambda x: x.category in categories, torrents)
)
torrents = list(filter(lambda x: x.category in categories, torrents))

include_tags = [i for s in app.include_tag for i in s]
if include_tags:
torrents = list(
filter(lambda x: all(y in x.tags for y in include_tags), torrents)
)

exclude_tags = [i for s in app.exclude_tag for i in s]
if exclude_tags:
torrents = list(
filter(
lambda x: not any(y in x.tags for y in exclude_tags), torrents
)
filter(lambda x: not any(y in x.tags for y in exclude_tags), torrents)
)

logger.info(
f"Pruning torrents with tags [{' AND '.join(include_tags)}] but does not contain tags [{' OR '.join(exclude_tags)}]..."
"Pruning torrents with tags [%s] but does not contain tags [%s]...",
" AND ".join(include_tags),
" OR ".join(exclude_tags),
)

for t in torrents:
logger.info(
f"Pruned torrent {t['name']} with category [{t.category}] and tags [{t.tags}] and ratio [{round(t['ratio'], 2)}] and seeding time [{utils.dhms(t['seeding_time'])}]"
"Pruned torrent %s with category [%s] and tags [%s] and ratio [%.2f] and seeding time [%s]",
t["name"],
t.category,
t.tags,
round(t["ratio"], 2),
utils.dhms(t["seeding_time"]),
)
if not app.dry_run:
t.delete(delete_files=app.with_data)

logger.info(f"Deleted {len(torrents)} torrents")
logger.info("Deleted %s torrents", len(torrents))


def add_arguments(command, subparser):
Expand Down
54 changes: 26 additions & 28 deletions qbtools/commands/tagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,11 @@
def __init__(app, logger):
logger.info(f"Tagging torrents in qBittorrent...")

tags = collections.defaultdict(list)
content_paths = []

today = datetime.today()
extractTLD = tldextract.TLDExtract(cache_dir=None)

torrents = app.client.torrents.info()
trackers = app.config.get("trackers", [])
trackers = {y: x for x in trackers for y in x["urls"]}

unregistered_matches = app.config.get("unregistered_matches", UNREGISTERED_MATCHES)
maintenance_matches = app.config.get("maintenance_matches", MAINTENANCE_MATCHES)

exclude_categories = [i for s in app.exclude_category for i in s]
if exclude_categories:
torrents = list(
Expand All @@ -70,20 +63,20 @@ def __init__(app, logger):
exclude_tags = [i for s in app.exclude_tag for i in s]
if exclude_tags:
torrents = list(
filter(
lambda x: any(y not in x.tags for y in exclude_tags), torrents
)
filter(lambda x: any(y not in x.tags for y in exclude_tags), torrents)
)

torrents = app.client.torrents.info()
extractTLD = tldextract.TLDExtract(cache_dir=None)
tags = collections.defaultdict(list)
paths = []

for t in torrents:
tags_to_add = []
filtered = []

url = t.tracker
if not url:
filtered = [s for s in t.trackers if s.tier >= 0] # Expensive
filtered = [s for s in t.trackers if s.tier >= 0] # Expensive
if not filtered:
continue
url = filtered[0].url
Expand All @@ -92,7 +85,7 @@ def __init__(app, logger):

if app.added_on:
tags_to_add.append(calculate_date_tags("added", t.added_on, today))

if app.last_activity:
tags_to_add.append(calculate_date_tags("activity", t.last_activity, today))

Expand All @@ -103,33 +96,34 @@ def __init__(app, logger):
tags_to_add.append(f"site:unmapped")

if (app.unregistered or app.tracker_down or app.not_working) and filtered:
tracker_messages = [z.msg.upper() for z in filtered]
messages = [z.msg.upper() for z in filtered]
if app.unregistered and any(
x in msg for msg in tracker_messages for x in unregistered_matches
match in msg for msg in messages for match in UNREGISTERED_MATCHES
):
tags_to_add.append("unregistered")
elif app.tracker_down and any(
x in msg for msg in tracker_messages for x in maintenance_matches
match in msg for msg in messages for match in MAINTENANCE_MATCHES
):
tags_to_add.append("tracker-down")
elif app.not_working:
tags_to_add.append("not-working")

if app.expired and tracker and t.state_enum.is_complete:
if (
tracker["required_seed_ratio"] != 0
tracker["required_seed_ratio"]
and t.ratio >= tracker["required_seed_ratio"]
):
tags_to_add.append("expired")
elif tracker["required_seed_days"] != 0 and t.seeding_time >= utils.seconds(
elif tracker["required_seed_days"] and t.seeding_time >= utils.seconds(
tracker["required_seed_days"]
):
tags_to_add.append("expired")

if app.duplicates:
if t.content_path in content_paths and not t.content_path == t.save_path:
if t.content_path in paths and not t.content_path == t.save_path:
tags_to_add.append("dupe")
content_paths.append(t.content_path)
else:
paths.append(t.content_path)

if app.not_linked and not utils.is_linked(t.content_path):
tags_to_add.append("not-linked")
Expand All @@ -139,24 +133,26 @@ def __init__(app, logger):

empty_tags = list(
filter(
lambda tag: tag not in tags and any(tag.lower().startswith(x.lower()) for x in DEFAULT_TAGS),
app.client.torrents_tags()
lambda tag: tag not in tags
and any(tag.lower().startswith(x.lower()) for x in DEFAULT_TAGS),
app.client.torrents_tags(),
)
)
if empty_tags:
app.client.torrents_delete_tags(tags=empty_tags)
logger.info(f"Removed {len(empty_tags)} old tags from qBittorrent")
logger.info("Removed %s old tags from qBittorrent", len(empty_tags))

for tag, tagged in tags.items():
old_torrents = [t.hash for t in torrents if tag in t.tags and not t in tagged]
new_torrents = [t.hash for t in tagged if not tag in t.tags]

if old_torrents:
app.client.torrents_remove_tags(tags=tag, torrent_hashes=old_torrents)
logger.info(f"Untagged {len(old_torrents)} old torrents with tag: {tag}")
logger.info("Untagged %s old torrents with tag: %s", len(old_torrents), tag)

new_torrents = [t.hash for t in tagged if not tag in t.tags]
if new_torrents:
app.client.torrents_add_tags(tags=tag, torrent_hashes=new_torrents)
logger.info(f"Tagged {len(new_torrents)} new torrents with tag: {tag}")
logger.info("Tagged %s new torrents with tag: %s", len(new_torrents), tag)

logger.info("Finished tagging torrents in qBittorrent")

Expand Down Expand Up @@ -235,7 +231,9 @@ def add_arguments(command, subparser):
help="Tag torrents with not working tracker status",
)
parser.add_argument(
"--sites", action="store_true", help="Tag torrents with site names (defined in config.yaml)"
"--sites",
action="store_true",
help="Tag torrents with site names (defined in config.yaml)",
)
parser.add_argument(
"--tracker-down",
Expand Down
8 changes: 4 additions & 4 deletions qbtools/qbtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def load_command(command):
if subparser:
add_default_args(subparser)
except ImportError:
logger.error(f"Error loading module: {command}", exc_info=True)
logger.error("Error loading module: %s", command, exc_info=True)
sys.exit(1)
else:
globals()[command] = mod
Expand Down Expand Up @@ -99,10 +99,10 @@ def get_config(app):
with open(app.config, "r") as stream:
config = yaml.safe_load(stream)
except FileNotFoundError:
logger.error(f"Configuration file not found: {app.config}", exc_info=True)
logger.error("Configuration file not found: %s", app.config, exc_info=True)
sys.exit(1)
except yaml.YAMLError:
logger.error(f"Error parsing configuration file: {app.config}", exc_info=True)
logger.error("Error parsing configuration file: %s", app.config, exc_info=True)
sys.exit(1)
else:
return config
Expand Down Expand Up @@ -133,7 +133,7 @@ def main():
mod = globals()[app.command]
mod.__init__(app, logger)
except Exception:
logger.error(f"Error executing command: {app.command}", exc_info=True)
logger.error("Error executing command: %s", app.command, exc_info=True)
sys.exit(1)
finally:
app.client.auth_log_out()
Expand Down

0 comments on commit 880fdde

Please sign in to comment.