-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreseed.py
executable file
·375 lines (300 loc) · 10 KB
/
reseed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python3
import argparse
import configparser
import gazelle
import html
import os
import re
import subprocess
import string
import sys
import tempfile
# WARNING untested
cross_seeding = False
dry_run = False
##
##
##
def find_all(dir):
return [f for f in os.listdir(dir) if os.path.isdir(os.path.join(dir, f))]
def find_flac_torrents(torrents_dir):
o = []
for folder in find_all(torrents_dir):
if folder.lower().find('flac') != -1:
o.append(folder)
return o
##
##
##
def sanitize_tag(tag):
tag = ' '.join(tag.split()) # fold whitespace
tag = re.sub(r'\(.*?\)', '', tag) # remove (parentheticals)
tag = re.sub(r'\[.*?\]', '', tag) # remove [brace comments]
return tag
def get_metaflac_tag(path, tag):
key = subprocess.check_output(['metaflac', '--show-tag='+tag, path])
key = key.decode('utf-8')
pos = key.find('=')
if pos != -1:
key = key[pos+1:]
return sanitize_tag(key)
def has_log(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.log'):
return True
return False
def build_search_queries(path):
queries = []
query_strs = []
log = has_log(path)
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.flac'):
path = os.path.join(root, name)
album = get_metaflac_tag(path, 'ALBUM')
artist = get_metaflac_tag(path, 'ARTIST')
if album and artist:
query = {'searchstr': album,
'artistname': artist,
'hasLog': log,
'format': 'FLAC'}
query_str = str(query)
if query_str not in query_strs:
queries.append(query)
query_strs.append(query_str)
elif name.endswith('.mp3'):
# TODO:
pass
# don't return too many:
# VA compilations spam with redundant searches
max_queries = 5
if len(queries) > max_queries:
queries = queries[:max_queries]
return queries
##
##
##
def get_prefix_and_suffix(s):
suffix = None
pos = s.rfind('.')
if pos != -1:
suffix = s[pos+1:].lower()
prefix = None
pos = 0
while s[pos].isdigit():
pos += 1
prefix = s[0:pos].lower()
return prefix, suffix
def find_matching_file(path, fname, fsize):
candidate = os.path.join(path, fname)
if os.path.isfile(candidate):
# look for an easy match first
s = os.path.getsize(candidate)
if s == fsize:
print('perfect match: ' + fname)
return fname
candidates = []
for root, dirs, files in os.walk(path):
for name in files:
prefix, suffix = get_prefix_and_suffix(name)
full = os.path.join(root, name)
size = os.path.getsize(full)
rel = os.path.relpath(full, path)
candidates.append([prefix, suffix, rel, size])
# next look & see if someone renamed the file
for candidate in candidates:
if fsize == candidate[3]:
print('filesize match: ' + candidate[2])
return candidate[2]
# maybe they renamed it /and/ edited the metainfo.
# look for a file that begins with the same number
# ends with the same suffix
# differs by <5%
# prefix, suffix = get_prefix_and_suffix(fname)
# for candidate in candidates:
# print("prefix==%s suffix==%s fname==%s candidate==[%s] fsize==%s"
# % (prefix, suffix, fname, candidate, fsize))
# if prefix==candidate[0] and suffix==candidate[1]:
# if file_size_is_close(candidate[3], fsize):
# print('prefix, suffix match: ' + candidate[2])
# return candidate[2]
# print('seeking %s (%s)' % (fname, fsize))
# for candidate in candidates:
# print(candidate)
# print('no match.')
return None
def is_match(torrent_path, filepath, filelist):
filemap = {}
for fname in filelist:
fsize = filelist[fname]
match = find_matching_file(torrent_path, fname, fsize)
if match:
filemap[fname] = match
elif not fname.endswith('.flac') and not fname.endswith('.mp3'):
pass # missing supporting files are ok
else:
print('discarding candidate "%s" because we have no match for "%s"'
% (filepath, fname))
return False, {}
return True, filemap
##
##
##
def mv(src, tgt):
print('$ mv "%s" "%s"' % (src, tgt))
if not dry_run:
dirname = os.path.dirname(tgt)
if not os.path.isdir(dirname):
os.makedirs(dirname)
os.rename(src, tgt)
def move_torrent(src, tgt, filemap):
# move the torrent folder over
mv(src, tgt)
# if the user's renamed any files, update them too
for key in filemap:
if key != filemap[key]:
fin = os.path.join(tgt, filemap[key])
fout = os.path.join(tgt, key)
mv(fin, fout)
def link(src, tgt):
print('$ ln -s "%s" "%s"' % (src, tgt))
if not dry_run:
dirname = os.path.dirname(tgt)
if not os.path.isdir(dirname):
os.makedirs(dirname)
os.symlink(src, tgt)
def link_torrent(src, tgt, filemap):
no_changes = True
for key in filemap:
if key != filemap[key]:
no_changes = False
break
if no_changes:
# everything's the same, one symlink is enough
link(src, tgt)
else:
# symlink each file into a new folder
os.makedirs(tgt)
for key in filemap:
fin = os.path.join(src, filemap[key])
fout = os.path.join(tgt, key)
link(fin, fout)
def add_torrent_from_id(id, api, add_cmd):
torrent_file = api.snatch_torrent(id)
fd, fname = tempfile.mkstemp()
os.write(fd, torrent_file)
os.close(fd)
cmd = string.Template(add_cmd).safe_substitute({'torrent': fname})
print('$ ' + cmd)
if not dry_run:
os.system(cmd)
os.remove(fname)
##
##
##
# returns a map of filename -> filesize
def parse_filelist(str):
filelist = {}
for f in str.split('|||'):
pos = f.rfind('{{{')
fname = f[0:pos]
fname = html.unescape(fname)
f = f[pos+3:]
pos = f.rfind('}}}')
fsize = int(f[:pos])
filelist[fname] = fsize
return filelist
def find_match(torrent_path, api):
print(torrent_path)
for query in build_search_queries(torrent_path):
print(query)
reply = api.request('browse', **query)
for result in reply.get('results', {}):
# FIXME: sort candidates by size closeness
for candidate in result.get('torrents', []):
torrent = api.request('torrent', id=candidate['torrentId'])
if torrent:
t = torrent['torrent']
filepath = html.unescape(t['filePath'])
files = parse_filelist(t['fileList'])
match, filemap = is_match(torrent_path,
filepath, files)
if match:
torrentid = t['id']
return match, torrentid, filepath, filemap
return False, '', '', {}
def process_torrent(torrent_path, api, tracker_root, action_func, add_cmd):
match, torrentid, filepath, filemap = find_match(torrent_path, api)
if match:
src = torrent_path
tgt = os.path.join(tracker_root, filepath)
action_func(src, tgt, filemap)
add_torrent_from_id(torrentid, api, add_cmd)
##
##
##
def build_default_config(config, filename):
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
section = 'source'
config.add_section(section)
config.set(section, 'path', '/path/to/old/torrents')
section = 'target'
config.add_section(section)
config.set(section, 'path', '/where/to/put/new/torrents')
config.set(section, 'url', 'https://passtheheadphones.me/')
config.set(section, 'username', '')
config.set(section, 'password', '')
section = 'user-agent'
config.add_section(section)
config.set(section, 'add',
' '.join(['transmission-remote',
'--add', '"$torrent"',
'--start-paused',
'--download-dir', '"$dir"']))
config.write(open(filename, 'w'))
print('Please edit the configuration file "%s"' % filename)
def main():
# command-line parsing
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog='reseed')
parser.add_argument(
'--config',
help='the location of the configuration file',
default=os.path.expanduser('~/.reseed/config'))
args = parser.parse_args()
# read the config file
config = configparser.SafeConfigParser()
try:
config.readfp(open(args.config))
section = 'source'
torrent_root = config.get(section, 'path')
section = 'target'
tracker_root = config.get(section, 'path')
username = config.get(section, 'username')
password = config.get(section, 'password')
url = config.get(section, 'url')
section = 'user-agent'
add_cmd = config.get(section, 'add')
d = {'dir': tracker_root}
add_cmd = string.Template(add_cmd).safe_substitute(d)
except:
build_default_config(config, args.config)
sys.exit(2)
if cross_seeding:
action_func = link_torrent
else:
action_func = move_torrent
print('logging in')
api = gazelle.Gazelle(url, username, password)
print('looking for torrents in %s' % torrent_root)
folders = find_flac_torrents(torrent_root)
for f in folders:
torrent_path = os.path.join(torrent_root, f)
process_torrent(torrent_path, api, tracker_root, action_func, add_cmd)
api.logout()
if __name__ == '__main__':
main()