Last active
August 29, 2015 14:18
-
-
Save swasher/f1a6646cbaaff33d2874 to your computer and use it in GitHub Desktop.
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/python3 | |
# -*- coding: utf-8 -*- | |
# bencode can be found here https://github.com/celend/bencode | |
import bencode | |
import os | |
import argparse | |
from zipfile import ZipFile | |
from datetime import datetime | |
from copy import deepcopy | |
""" | |
Пользовательские настройки | |
directory - путь, где искать .torrent файлы | |
old_entry - строка, которую нужно заменть | |
new_entry - новая строка | |
tags_for_replacing - список тегов, в которых проводится поиск и замена. | |
Нужные теги можно определить с помощью анализа торрентов: announce_changer.py --inspect | |
""" | |
directory = '/home/rtorrent/session' | |
old_entry = 'tracker.hdclub.com.ua' | |
new_entry = 'hdclub.org' | |
tags_for_replacing = ['comment', 'announce', 'announce-list', 'publisher-url', 'publisher-url.utf-8'] | |
def create_backup(directory): | |
""" | |
Принудительный бекап директории с торрентами. | |
Архив создается в родительской директории относительно пути к торрентам. | |
""" | |
print('Create backup...') | |
try: | |
archive = '../backup_torrent_{}.zip'.format(datetime.now().strftime("%H.%M")) | |
os.chdir(directory) | |
with ZipFile(archive, 'w') as myzip: | |
for root, dirs, files in os.walk(directory): | |
for file in files: | |
myzip.write(file) | |
print('Done.') | |
except Exception as e: | |
print('Backup error! {}'.format(e)) | |
def inspect(torrentfile, data): | |
""" | |
Возможность просмотреть содержимое торрентов | |
""" | |
print('\n\nANALYZE {}'.format(torrentfile)) | |
try: | |
for param in data.keys(): | |
if not type(data[param]) is dict: | |
print('{}: {}'.format(param, data[param])) | |
else: | |
print('`{}` VALUES:'.format(str(param).upper())) | |
for key, value in data[param].items(): | |
# skip 'pieces' because it's too long | |
if not key == 'pieces': | |
print('\t', key, '\t', value) | |
except Exception as e: | |
print(e) | |
def replacing(torrentfile, data): | |
global count | |
torrentname = os.path.basename(torrentfile) | |
orig_data = deepcopy(data) | |
for tag in tags_for_replacing: | |
try: | |
value = data[tag] | |
except: | |
pass | |
else: | |
if type(value) is str: | |
# заменить строку value | |
data[tag] = value.replace(old_entry, new_entry) | |
elif type(value) is list: | |
# замена в списке списков, типа announce-list [['http://bt4.rutracker.org/ann?uk=1eVMs0KvoX'], ['http://retracker.local/announce'], ['http://ix4.rutracker.net/ann?uk=1eVMs0KvoX']] | |
try: | |
data[tag] = [[x[0].replace(old_entry, new_entry)] for x in value] | |
except: | |
print('Error replace tag {} in {}'.format(tag, torrentfile)) | |
else: | |
print('Type of tag for replacing must be `str` or `list` but here is {}'.format(type(value))) | |
if orig_data != data: | |
try: | |
bencode.save(data, torrentfile) | |
count += 1 | |
try: | |
movietitle = data['info']['name'] | |
except: | |
movietitle = torrentname | |
print('{}: {}'.format(count, movietitle)) | |
except Exception as e: | |
print('WARNING! {} CANNOT SAVED! Error {}'.format(torrentname, e)) | |
def walking(action): | |
for root, dirs, files in os.walk(directory): | |
for file in files: | |
if file.endswith('.torrent'): | |
try: | |
torrentfile = os.path.join(root, file) | |
data = bencode.load(torrentfile, 'encoding; default is utf-8') | |
action(torrentfile, data) | |
except Exception as e: | |
print('ERROR `decode` in torrent {} with {}'.format(file, e)) | |
if __name__ == "__main__": | |
count = 0 | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-i', '--inspect', help="Look and analyze torrent's tags", action="store_true") | |
parser.add_argument('-r', '--replace', help="Search and replace tags", action="store_true") | |
args = parser.parse_args() | |
if args.inspect: | |
walking(inspect) | |
elif args.replace: | |
create_backup(directory) | |
walking(replacing) | |
else: | |
parser.print_help() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment