diff --git a/transmission_move_music.py b/transmission_move_music.py new file mode 100644 index 0000000..8242be2 --- /dev/null +++ b/transmission_move_music.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +# Copyright 2014-2015 Luca Beltrame +# Licensed under the terms of the terms of the GPL, version 3, or later. +# See the LICENSE file for details. + +import argparse +from functools import singledispatch, wraps +from enum import Enum +import os +from pathlib import Path +import re +import stat + +import transmissionrpc +from xdg import Mime + + +class FileType(Enum): + + music = 1 + video = 2 + application = 3 + image = 4 + unknown = 100 + + @staticmethod + def detect(filelist: dict): + + # Get the largest file + largest = max(filelist, key=lambda x: filelist[x]) + + category = Mime.get_type_by_name(largest).media + + if category == "audio": + return FileType.music + elif category == "video": + return FileType.video + elif category == "application": + return FileType.application + elif category == "image": + return FileType.image + + def destination_dir(self) -> Path: + + if self is FileType.music: + return Path("/home/storage/music/Anime/") + elif self is FileType.video: + return Path("/home/storage/video/Anime/") + elif self is FileType.application: + return Path("/home/storage/applications/") + elif self is FileType.image: + return Path("/home/storage/images/") + else: + return Path("/home/storage/transmission-downloads/") + + +def main(): + + # Get the information from Transmission + + source_directory = os.environ.get("TR_TORRENT_DIR") + source_file = os.environ.get("TR_TORRENT_NAME") + torrent_id = os.environ.get("TR_TORRENT_ID") + + with open("/var/lib/transmission/rpcpass", "r") as handle: + rpc_pass = handle.read().strip() + + if source_directory is None or source_file is None: + print("Please run this script from Transmission.") + exit(1) + + source = Path(source_directory) / source_file + + assert source.exists() + + client = transmissionrpc.Client("localhost", port=9091, + username="transmission", password=rpc_pass) + + filelist = client.get_files(torrent_id) + filelist = {filelist[item]["name"]: filelist[item]["size"] for item in + filelist} + + filetype = FileType.detect(filelist) + + destination = filetype.destination_dir() + + if destination == source_directory: + return + + dest_path = destination / source.name + source.rename(dest_path) + permissions = dest_path.st_mode | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH + dest_path.chmod(permissions) + client.stop_torrent(torrent_id) + + print("Moved {} to {}".format(source, dest_path)) + + +if __name__ == "__main__": + main()