#!/usr/bin/env python3 import os from pathlib import Path import subprocess import sys def show_notification(title, description, urgency): print("Notification: title: %s, description: %s" % (title, description)) process = subprocess.Popen(["notify-send", "-t", "10000", "-u", urgency, "--", title, description]) stdout, stderr = process.communicate() return process.returncode == 0 def get_tracked_episodes(): process = subprocess.Popen(["automedia", "downloaded", "--include-tracked"], stdout=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: return None return stdout.decode("utf-8").splitlines(False) def select_anime(anime_files): process = subprocess.Popen(["dmenu", "-i", "-l", "15", "-p", "Select anime to track"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = process.communicate(b"\n".join(anime_files)) if process.returncode != 0: return None return stdout.decode("utf-8").strip() def track_anime(anime): add_process = subprocess.Popen(["automedia", "add", "rss", anime], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = [] while True: c = add_process.stdout.read(1) if c == b':': break output.append(c) submitter_prompt = b"".join(output).decode("utf-8") dmenu_process = subprocess.Popen(["dmenu", "-i", "-l", "15", "-p", submitter_prompt], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = dmenu_process.communicate(b"") if dmenu_process.returncode != 0: return None chosen_submitter = stdout.decode("utf-8").strip() add_process.communicate((chosen_submitter + "\n" + "\n").encode("utf-8")) return add_process.returncode == 0 def main(): if len(sys.argv) != 2: print("usage: track.py ") sys.exit(1) anime_dir = sys.argv[1] all_files = sorted(Path(anime_dir).iterdir(), key=os.path.getmtime, reverse=True) anime_files = [os.path.basename(filepath).encode("utf-8") for filepath in all_files if os.path.isfile(filepath)] tracked_episodes = get_tracked_episodes() if not tracked_episodes: show_notification("Track anime", "Failed to get tracked episodes", "critical") sys.exit(1) tracked_episodes_set = set(tracked_episodes) anime_files = [anime_file for anime_file in anime_files if anime_file.decode("utf-8") not in tracked_episodes_set] selected_anime = select_anime(anime_files) if not selected_anime: sys.exit(0) if not track_anime(selected_anime): show_notification("Track anime", "Failed to track %s" % selected_anime, "critical") sys.exit(1) if __name__ == "__main__": main()