forked from iambus/xunlei-lixian
/
lixian_cli_extended.py
271 lines (235 loc) · 7.75 KB
/
lixian_cli_extended.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
__all__ = []
from lixian import XunleiClient
from lixian_config import *
from lixian_encoding import default_encoding
from lixian_cli_parser import parse_command_line
from lixian_cli_parser import expand_command_line
##################################################
# command decorator
##################################################
def command(name='', usage='', help=''):
def as_command(f):
assert usage, 'missing command usage: ' + f.func_name
f.command_name = name or f.func_name.replace('_', '-')
f.command_usage = usage
f.command_help = help or f.func_doc
import textwrap
if f.command_help:
f.command_help = textwrap.dedent(f.command_help)
return f
return as_command
##################################################
@command(name='hash', usage='compute hashes')
def print_hash(args):
'''
lx hash --sha1 file...
lx hash --md5 file...
lx hash --md4 file...
lx hash --ed2k file...
lx hash --info-hash xxx.torrent...
lx hash --verify-sha1 file hash
lx hash --verify-md5 file hash
lx hash --verify-md4 file hash
lx hash --verify-ed2k file ed2k://...
lx hash --verify-bt file xxx.torrent
'''
#assert len(args) == 1
import lixian_hash
#import lixian_hash_ed2k
#print 'ed2k:', lixian_hash_ed2k.hash_file(args[0])
#print 'dcid:', lixian_hash.dcid_hash_file(args[0])
lixian_hash.main(expand_command_line(args))
##################################################
@command(name='diagnostics', usage='print helpful information for diagnostics')
def lx_diagnostics(args):
'''
usage: lx diagnostics
'''
print 'default_encoding ->', default_encoding
import sys
print 'sys.getdefaultencoding() ->', sys.getdefaultencoding()
print 'sys.getfilesystemencoding() ->', sys.getfilesystemencoding()
print r"print u'\u4e2d\u6587'.encode('utf-8') ->", u'\u4e2d\u6587'.encode('utf-8')
print r"print u'\u4e2d\u6587'.encode('gbk') ->", u'\u4e2d\u6587'.encode('gbk')
##################################################
@command(usage='convert thunder:// (and more) to normal url')
def decode_url(args):
'''
usage: lx decode-url thunder://...
'''
from lixian_url import url_unmask
for x in args:
print url_unmask(x)
##################################################
@command(usage='parse links from kuai.xunlei.com')
def kuai(args):
'''
usage: lx kuai http://kuai.xunlei.com/d/xxx...
Note that you can simply use:
lx add http://kuai.xunlei.com/d/xxx...
or:
lx download http://kuai.xunlei.com/d/xxx...
'''
import lixian_kuai
lixian_kuai.main(args)
##################################################
@command(usage='parse links')
def extend_links(args):
'''
usage: lx extend-links http://kuai.xunlei.com/d/... http://www.verycd.com/topics/...
parse and print links from pages
lx extend-links urls...
lx extend-links --name urls...
'''
args = parse_command_line(args, [], ['name'])
import lixian_tasks_extended
for x in (lixian_tasks_extended.extend_links if not args.name else lixian_tasks_extended.extend_links_name)(args):
print x
##################################################
@command(usage='list files in local .torrent')
def list_torrent(args):
'''
usage: lx list-torrent [--size] xxx.torrent...
'''
args = parse_command_line(args, [], ['size'])
for p in args:
with open(p, 'rb') as stream:
from lixian_hash_bt import bdecode
info = bdecode(stream.read())['info']
print '*', info['name'].decode('utf-8')
for f in info['files']:
path = '/'.join(f['path']).decode('utf-8')
if args.size:
from lixian_util import format_size
print u'%s (%s)' % (path, format_size(f['length']))
else:
print path
##################################################
@command(usage='get .torrent by task id or info hash')
def get_torrent(args):
'''
usage: lx get-torrent [info-hash|task-id]...
'''
from lixian_cli import parse_login_command_line
args = parse_login_command_line(args)
client = XunleiClient(args.username, args.password, args.cookies)
for id in args:
id = id.lower()
import re
if re.match(r'[a-fA-F0-9]{40}$', id):
torrent = client.get_torrent_file_by_info_hash(id)
elif re.match(r'#?\d+$', id):
tasks = client.read_all_tasks()
from lixian_tasks import find_task_by_id
task = find_task_by_id(tasks, id)
assert task, id + ' not found'
id = task['bt_hash']
id = id.lower()
torrent = client.get_torrent_file_by_info_hash(id)
else:
raise NotImplementedError()
path = id + '.torrent'
print path
with open(path, 'wb') as output:
output.write(torrent)
##################################################
def export_aria2_conf(args):
client = XunleiClient(args.username, args.password, args.cookies)
import lixian_tasks
tasks = lixian_tasks.search_tasks(client, args, status=(args.completed and 'completed' or 'all'))
files = []
for task in tasks:
if task['type'] == 'bt':
subs, skipped, single_file = lixian_tasks.expand_bt_sub_tasks(client, task)
if not subs:
continue
if single_file:
files.append((subs[0]['xunlei_url'], subs[0]['name'], None))
else:
for f in subs:
import os.path
files.append((f['xunlei_url'], f['name'], task['name']))
else:
files.append((task['xunlei_url'], task['name'], None))
output = ''
for url, name, dir in files:
if type(url) == unicode:
url = url.encode(default_encoding)
output += url + '\n'
output += ' out=' + name.encode(default_encoding) + '\n'
if dir:
output += ' dir=' + dir.encode(default_encoding) + '\n'
output += ' header=Cookie: gdriveid=' + client.get_gdriveid() + '\n'
return output
@command(usage='export task download urls as aria2 format')
def export_aria2(args):
'''
usage: lx export-aria2 [id|name]...
'''
from lixian_cli import parse_login_command_line
args = parse_login_command_line(args)
print export_aria2_conf(args)
def download_aria2_stdin(aria2_conf, j):
aria2_opts = ['aria2c', '-i', '-', '-j', j]
aria2_opts.extend(get_config('aria2-opts', '').split())
from subprocess import Popen, PIPE
sub = Popen(aria2_opts, stdin=PIPE, bufsize=1, shell=True)
sub.communicate(aria2_conf)
sub.stdin.close()
exit_code = sub.wait()
if exit_code != 0:
raise Exception('aria2c exited abnormaly')
def download_aria2_temp(aria2_conf, j):
import tempfile
temp = tempfile.NamedTemporaryFile('w', delete=False)
temp.file.write(aria2_conf)
temp.file.close()
try:
aria2_opts = ['aria2c', '-i', temp.name, '-j', j]
aria2_opts.extend(get_config('aria2-opts', '').split())
import subprocess
exit_code = subprocess.call(aria2_opts)
finally:
import os
os.unlink(temp.name)
if exit_code != 0:
raise Exception('aria2c exited abnormaly')
@command(usage='concurrently download tasks in aria2')
def download_aria2(args):
'''
usage: lx download-aria2 -j 5 [id|name]...
'''
from lixian_cli import parse_login_command_line
args = parse_login_command_line(args, keys=['j'], alias={'max-concurrent-downloads':'j'})
j = get_config('aria2-j', args.j) or '5'
aria2_conf = export_aria2_conf(args)
import platform
if platform.system() == 'Windows':
download_aria2_temp(aria2_conf, j)
else:
download_aria2_stdin(aria2_conf, j)
##################################################
# update helps
##################################################
extended_commands = [
print_hash,
lx_diagnostics,
decode_url,
kuai,
extend_links,
list_torrent,
get_torrent,
export_aria2,
download_aria2,
]
commands = dict((x.command_name, x) for x in extended_commands)
def update_helps(commands):
helps = dict((name, doc) for (name, usage, doc) in commands)
if commands:
import lixian_help
lixian_help.extended_usage = '''\nExtended commands:
''' + lixian_help.join_commands([(x[0], x[1]) for x in commands])
for name, usage, doc in commands:
assert not hasattr(lixian_help, name)
setattr(lixian_help, name, doc)
update_helps([(x.command_name, x.command_usage, x.command_help) for x in extended_commands])