Last active
December 21, 2015 14:59
-
-
Save udoprog/6323723 to your computer and use it in GitHub Desktop.
Script to cleanup stale torrents, and or stale files depending on a list of source directories containing *.torrent files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import itertools | |
import bencode | |
import glob | |
import sys | |
import os | |
import shutil | |
def read_torrents(directory, download_root): | |
base = os.path.basename(directory) | |
path = os.path.join(directory, '*.torrent') | |
for p in glob.glob(path): | |
with open(p) as f: | |
torrent = bencode.bdecode(f.read()) | |
download_path = os.path.join( | |
download_root, base, torrent['info']['name'] | |
) | |
yield p, torrent, download_path | |
def list_entities(source, download_root): | |
source = os.path.basename(source) | |
root = os.path.join(download_root, source) | |
for e in os.listdir(root): | |
yield os.path.join(root, e) | |
def main(args): | |
if len(args) < 2: | |
print "Usage: torrentcleanup <downloaddir> <sourcedir> [<sourcedir>]" | |
print "" | |
print " Assumes that the basename of the <sourcedir> is the " | |
print " download directory in <downloaddir>." | |
print " Example: torrentcleanup /warez /mytorrents/thepiratebay " | |
print " would look for files in /warez/thepiratebay" | |
return 1 | |
download_root = os.path.abspath(args[0]) | |
args = map(os.path.abspath, args[1:]) | |
# list of all torrents in torrent directories. | |
torrents = itertools.chain( | |
*[read_torrents(a, download_root) for a in args] | |
) | |
# list of all files in download roots. | |
entities = itertools.chain( | |
*[list_entities(a, download_root) for a in args] | |
) | |
downloads = {} | |
for (path, torrent, download_path) in torrents: | |
check = os.path.isdir | |
# torrent is just a single file. | |
if 'files' not in torrent['info']: | |
check = os.path.isfile | |
if not check(download_path): | |
print "Missing download:", download_path | |
continue | |
downloads[download_path] = (path, torrent) | |
for path in entities: | |
if path in downloads: | |
continue | |
print "Removing:", path | |
if os.path.isfile(path): | |
os.unlink(path) | |
elif os.path.isdir(path): | |
shutil.rmtree(path) | |
else: | |
print "Not removing (unhandled type):", path | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment