Last active
February 8, 2025 04:31
-
-
Save KokoseiJ/ceb82e7fedcf29969b84d8d87b815743 to your computer and use it in GitHub Desktop.
Torrent hardlink duplicator
This file contains hidden or 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
import io | |
import os | |
import sys | |
import json | |
import pathlib | |
def bencode_read(data): | |
type_ = data.read(1) | |
char = b"" | |
buf = b"" | |
if type_ == b'i': | |
while 1: | |
char = data.read(1) | |
if char == b'e': | |
break | |
buf += char | |
return int(buf) | |
elif type_ in [b'l', b'd']: | |
buf = [] | |
while 1: | |
char = data.read(1) | |
if char == b'e': | |
break | |
data.seek(data.tell()-1) | |
buf.append(bencode_read(data)) | |
if type_ == b'l': | |
return buf; | |
else: | |
return dict(zip( | |
[x.decode() for x in buf[::2]], | |
buf[1::2] | |
)) | |
else: | |
data.seek(data.tell()-1) | |
while 1: | |
char = data.read(1) | |
if char == b':': | |
break | |
buf += char | |
return data.read(int(buf)) | |
def parse_files(data): | |
return {b'/'.join(x['path']).decode(): x['length'] for x in data} | |
check_dir = os.path.abspath(sys.argv[1]) | |
torrent = sys.argv[2] | |
data = bencode_read(io.BufferedReader(open(torrent, 'rb'))) | |
target_dir = os.path.abspath(data['info']['name'].decode()) | |
os.mkdir(target_dir) | |
if data['info'].get('meta version') == 2: | |
print("Torrent v2 detected, not supported") | |
exit() | |
files = parse_files(data['info']['files']) | |
for path, target_size in files.items(): | |
fullpath = os.path.join(check_dir, path) | |
print(fullpath) | |
targetpath = os.path.join(target_dir, path) | |
try: | |
size = os.path.getsize(fullpath) | |
if size == target_size: | |
print("size match, linking") | |
pathlib.Path(os.path.dirname(targetpath)).mkdir(parents=True, exist_ok=True) | |
os.link(fullpath, targetpath) | |
except Exception as e: | |
print(e) | |
print("file does not exist!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment