-
Notifications
You must be signed in to change notification settings - Fork 1
/
whatbetter
executable file
·219 lines (195 loc) · 9.99 KB
/
whatbetter
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
#!/usr/bin/env python
import os
import sys
import shutil
import argparse
import tempfile
import urlparse
import subprocess
import ConfigParser
import cPickle as pickle
from multiprocessing import cpu_count
import whatapi
import transcode
import tagging
from _version import __version__
def banner():
return 'Created with [url=http://github.com/zacharydenton/whatbetter]whatbetter[/url] version %s.' % __version__
def create_description(torrent, flac_dir, format, permalink):
# Create an example command to document the transcode process.
cmds = transcode.transcode_commands(format,
transcode.needs_resampling(flac_dir),
transcode.resample_rate(flac_dir),
'input.flac', 'output' + transcode.encoders[format]['ext'])
description = [
'Transcode of [url=%s]%s[/url]' % (permalink, permalink),
'',
'Transcode process:',
'',
'[code]%s[/code]' % ' | '.join(cmds),
'',
banner()
]
return description
def formats_needed(group, torrent, supported_formats):
same_group = lambda t: t['media'] == torrent['media'] and\
t['remasterYear'] == torrent['remasterYear'] and\
t['remasterTitle'] == torrent['remasterTitle'] and\
t['remasterRecordLabel'] == torrent['remasterRecordLabel'] and\
t['remasterCatalogueNumber'] == torrent['remasterCatalogueNumber']
others = filter(same_group, group['torrents'])
current_formats = set((t['format'], t['encoding']) for t in others)
missing_formats = [format for format, details in [(f, whatapi.formats[f]) for f in supported_formats]\
if (details['format'], details['encoding']) not in current_formats]
allowed_formats = whatapi.allowed_transcodes(torrent)
return [format for format in missing_formats if format in allowed_formats]
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog='whatbetter')
parser.add_argument('release_urls', nargs='*', help='the URL where the release is located')
parser.add_argument('-s', '--single', action='store_true', help='only add one format per release (useful for getting unique groups)')
parser.add_argument('-j', '--threads', type=int, help='number of threads to use when transcoding',
default=cpu_count())
parser.add_argument('--config', help='the location of the configuration file', \
default=os.path.expanduser('~/.whatbetter/config'))
parser.add_argument('--cache', help='the location of the cache', \
default=os.path.expanduser('~/.whatbetter/cache'))
parser.add_argument('-U', '--no-upload', action='store_true', help='don\'t upload new torrents (in case you want to do it manually)')
parser.add_argument('-E', '--no-24bit-edit', action='store_true', help='don\'t try to edit 24-bit torrents mistakenly labeled as 16-bit')
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
args = parser.parse_args()
config = ConfigParser.SafeConfigParser()
try:
open(args.config)
config.read(args.config)
except:
if not os.path.exists(os.path.dirname(args.config)):
os.makedirs(os.path.dirname(args.config))
config.add_section('whatcd')
config.set('whatcd', 'username', '')
config.set('whatcd', 'password', '')
config.set('whatcd', 'data_dir', '')
config.set('whatcd', 'output_dir', '')
config.set('whatcd', 'torrent_dir', '')
config.set('whatcd', 'formats', 'flac, v0, 320, v2')
config.set('whatcd', 'media', ', '.join(whatapi.lossless_media))
config.write(open(args.config, 'w'))
print 'Please edit the configuration file: %s' % args.config
sys.exit(2)
finally:
username = config.get('whatcd', 'username')
password = config.get('whatcd', 'password')
data_dir = os.path.expanduser(config.get('whatcd', 'data_dir'))
try:
output_dir = os.path.expanduser(config.get('whatcd', 'output_dir'))
except ConfigParser.NoOptionError:
output_dir = None
if not output_dir:
output_dir = data_dir
torrent_dir = os.path.expanduser(config.get('whatcd', 'torrent_dir'))
supported_formats = [format.strip().upper() for format in config.get('whatcd', 'formats').split(',')]
try:
media_config = config.get('whatcd', 'media')
if not media_config:
supported_media = whatapi.lossless_media
else:
supported_media = set([medium.strip().lower() for medium in media_config.split(',')])
if not supported_media.issubset(set(whatapi.lossless_media)):
print 'Unsupported media type "%s", edit your configuration' % (supported_media - whatapi.lossless_media).pop()
print 'Supported types are:', ', '.join(whatapi.lossless_media)
sys.exit(2)
except ConfigParser.NoOptionError:
supported_media = whatapi.lossless_media
upload_torrent = not args.no_upload
print 'Logging in to What.CD...'
api = whatapi.WhatAPI(username, password)
try:
seen = pickle.load(open(args.cache))
except:
seen = set()
pickle.dump(seen, open(args.cache, 'wb'))
print 'Searching for transcode candidates...'
if args.release_urls:
print 'You supplied one or more release URLs, ignoring your configuration\'s media types.'
candidates = [(int(query['id']), int(query['torrentid'])) for query in\
[dict(urlparse.parse_qsl(urlparse.urlparse(url).query)) for url in args.release_urls]]
else:
candidates = api.snatched(skip=seen, media=supported_media)
for groupid, torrentid in candidates:
group = api.request('torrentgroup', id=groupid)
torrent = [t for t in group['torrents'] if t['id'] == torrentid][0]
print
print "Release found: %s (%s)" % (whatapi.unescape(group['group']['name']), group['group']['year'])
print "Release URL: %s" % api.release_url(group, torrent)
if not torrent['filePath']:
flac_file = os.path.join(data_dir, whatapi.unescape(torrent['fileList']).split('{{{')[0])
if not os.path.exists(flac_file):
print "Path not found - skipping: %s" % flac_file
continue
flac_dir = os.path.join(data_dir, "%s (%s) [FLAC]" % (whatapi.unescape(group['group']['name']), group['group']['year']))
if not os.path.exists(flac_dir):
os.makedirs(flac_dir)
shutil.copy(flac_file, flac_dir)
else:
flac_dir = os.path.join(data_dir, whatapi.unescape(torrent['filePath']))
flac_dir = flac_dir.encode(sys.getfilesystemencoding())
try:
if transcode.is_24bit(flac_dir) and torrent['encoding'] != '24bit Lossless':
# A lot of people are uploading FLACs from Bandcamp without realizing
# that they're actually 24 bit files (usually 24/44.1). Since we know for
# sure whether the files are 24 bit, we might as well correct the listing
# on the site (and get an extra upload in the process).
if args.no_24bit_edit:
print "Release is actually 24-bit lossless, skipping."
continue
print "Marking release as 24bit lossless."
api.set_24bit(torrent)
group = api.request('torrentgroup', id=groupid)
torrent = [t for t in group['torrents'] if t['id'] == torrentid][0]
except Exception as e:
print "Error: can't edit 24-bit torrent - skipping: %s" % e
continue
if transcode.is_multichannel(flac_dir):
print "This is a multichannel release, which is unsupported - skipping"
continue
needed = formats_needed(group, torrent, supported_formats)
print "Formats needed: %s" % ', '.join(needed)
if needed:
# Before proceeding, do the basic tag checks on the source
# files to ensure any uploads won't be reported, but punt
# on the tracknumber formatting; problems with tracknumber
# may be fixable when the tags are copied.
broken_tags = False
for flac_file in transcode.locate(flac_dir, transcode.ext_matcher('.flac')):
(ok, msg) = tagging.check_tags(flac_file, check_tracknumber_format=False)
if not ok:
print "A FLAC file in this release has unacceptable tags - skipping: %s" % msg
print "You might be able to trump it."
broken_tags = True
break
if broken_tags:
continue
for format in needed:
if os.path.exists(flac_dir):
print 'Adding format %s...' % format,
tmpdir = tempfile.mkdtemp()
try:
transcode_dir = transcode.transcode_release(flac_dir, output_dir, format, max_threads=args.threads)
new_torrent = transcode.make_torrent(transcode_dir, tmpdir, api.tracker, api.passkey)
if upload_torrent:
permalink = api.permalink(torrent)
description = create_description(torrent, flac_dir, format, permalink)
api.upload(group, torrent, new_torrent, format, description)
shutil.copy(new_torrent, torrent_dir)
print "done!"
if args.single: break
except Exception as e:
print "Error adding format %s: %s" % (format, e)
finally:
shutil.rmtree(tmpdir)
else:
print "Path not found - skipping: %s" % flac_dir
break
seen.add(str(torrentid))
pickle.dump(seen, open(args.cache, 'wb'))
if __name__ == "__main__":
main()