Пример #1
0
def download_task(args):
	args = parse_login_command_line(args,
	                                ['tool', 'output', 'output-dir', 'input'],
	                                ['delete', 'continue', 'overwrite', 'torrent', 'all', 'mini-hash', 'hash'],
									alias={'o': 'output', 'i': 'input', 'c':'continue', 'bt':'torrent'},
									default={'tool':get_config('tool', 'wget'),'delete':get_config('delete'),'continue':get_config('continue'),'output-dir':get_config('output-dir'), 'mini-hash':get_config('mini-hash'), 'hash':get_config('hash', True)},
	                                help=lixian_help.download)
	download = {'wget':wget_download, 'curl': curl_download, 'aria2':aria2_download, 'aria2c':aria2_download, 'axel':axel_download, 'asyn':asyn_download, 'urllib2':urllib2_download}[args.tool]
	download_args = {'output':args.output, 'output_dir':args.output_dir, 'delete':args.delete, 'resuming':args._args['continue'], 'overwrite':args.overwrite, 'mini_hash':args.mini_hash, 'no_hash': not args.hash}
	client = XunleiClient(args.username, args.password, args.cookies)
	links = None
	if len(args) or args.input:
		assert not args.output
		tasks = find_tasks_to_download(client, args)
		if args.output:
			assert len(tasks) == 1
			download_single_task(client, download, tasks[0], download_args)
		else:
			download_multiple_tasks(client, download, tasks, download_args)
	elif args.all:
		#tasks = client.read_all_completed()
		tasks = client.read_all_tasks()
		download_multiple_tasks(client, download, tasks, download_args)
	else:
		usage(doc=lixian_help.download, message='Not enough arguments')
Пример #2
0
def list_task(args):
	args = parse_login_command_line(args, [],
	                                ['all', 'completed',
	                                 'id', 'name', 'status', 'size', 'dcid', 'gcid', 'original-url', 'download-url', 'speed', 'progress', 'date',
	                                 'n'],
									default={'id': True, 'name': True, 'status': True, 'n': get_config('n')},
									help=lixian_help.list)

	parent_ids = [a[:-1] for a in args if re.match(r'^#?\d+/$', a)]
	if parent_ids and not all(re.match(r'^#?\d+/$', a) for a in args):
		raise NotImplementedError("Can't mix 'id/' with others")
	assert len(parent_ids) <= 1, "sub-tasks listing only supports single task id"
	ids = [a[:-1] if re.match(r'^#?\d+/$', a) else a for a in args]

	client = XunleiClient(args.username, args.password, args.cookies)
	if parent_ids:
		args[0] = args[0][:-1]
		tasks = search_tasks(client, args, status=(args.completed and 'completed' or 'all'))
		assert len(tasks) == 1
		tasks = client.list_bt(tasks[0])
		#tasks = client.list_bt(client.get_task_by_id(parent_ids[0]))
		tasks.sort(key=lambda x: int(x['index']))
	elif len(ids):
		tasks = search_tasks(client, args, status=(args.completed and 'completed' or 'all'))
	elif args.completed:
		tasks = client.read_all_completed()
	else:
		tasks = client.read_all_tasks()
	columns = ['n', 'id', 'name', 'status', 'size', 'progress', 'speed', 'date', 'dcid', 'gcid', 'original-url', 'download-url']
	columns = filter(lambda k: getattr(args, k), columns)
	for i, t in enumerate(tasks):
		for k in columns:
			if k == 'n':
				if not parent_ids:
					print '#%d' % t['#'],
			elif k == 'id':
				print t.get('index', t['id']),
			elif k == 'name':
				print t['name'].encode(default_encoding),
			elif k == 'status':
				print t['status_text'],
			elif k == 'size':
				print t['size'],
			elif k == 'progress':
				print t['progress'],
			elif k == 'speed':
				print t['speed'],
			elif k == 'date':
				print t['date'],
			elif k == 'dcid':
				print t['dcid'],
			elif k == 'gcid':
				print t['gcid'],
			elif k == 'original-url':
				print t['original_url'],
			elif k == 'download-url':
				print t['xunlei_url'],
			else:
				raise NotImplementedError(k)
		print
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
Пример #4
0
def logout(args):
    if len(args):
        raise RuntimeError('Too many arguments')
    print 'logging out from', args.cookies
    assert args.cookies
    client = XunleiClient(cookie_path=args.cookies, login=False)
    client.logout()
Пример #5
0
def login(args):
    args = parse_login_command_line(args, help=lixian_help.login)
    if args.cookies == '-':
        args._args['cookies'] = None
    if len(args) < 1:
        args.username = args.username or XunleiClient(
            cookie_path=args.cookies, login=False).get_username(
            ) or get_config('username') or raw_input('ID: ')
        args.password = args.password or get_config('password') or getpass(
            'Password: '******'username')
        args.password = args[0]
        if args.password == '-':
            args.password = getpass('Password: '******'-':
            args.password = getpass('Password: '******'-':
            args.password = getpass('Password: '******'Too many arguments')
    if not args.username:
        raise RuntimeError("What's your name?")
    if args.cookies:
        print 'Saving login session to', args.cookies
    else:
        print 'Testing login without saving session'
    client = XunleiClient(args.username, args.password, args.cookies)
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)
Пример #7
0
def add_task(args):
    args = parse_login_command_line(args, ['input'], ['torrent'],
                                    alias={'i': 'input'},
                                    help=lixian_help.add)
    assert len(args) or args.input
    client = XunleiClient(args.username, args.password, args.cookies)
    links = []
    links.extend(args)
    if args.input:
        with open(args.input) as x:
            links.extend(line.strip() for line in x.readlines()
                         if line.strip())
    if not args.torrent:
        print 'Adding below tasks:'
        for link in links:
            print link
        client.add_batch_tasks(links)
        print 'All tasks added. Checking status...'
        tasks = client.read_all_tasks()
        for link in links:
            found = filter_tasks(tasks, 'original_url', link)
            if found:
                print found[0]['status_text'], link
            else:
                print 'unknown', link
    else:
        tasks = find_torrents_task_to_download(client, links)
        assert len(tasks) == len(links)
        print 'All tasks added:'
        for link, task in zip(links, tasks):
            print task['status_text'], link
Пример #8
0
def restart_task(args):
	client = XunleiClient(args.username, args.password, args.cookies)
	to_restart = search_tasks(client, args)
	print "Below files are going to be restarted:"
	for x in to_restart:
		print x['name'].encode(default_encoding)
	client.restart_tasks(to_restart)
Пример #9
0
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)
Пример #10
0
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
Пример #11
0
def list_task(args):

	parent_ids = [a[:-1] for a in args if re.match(r'^#?\d+/$', a)]
	if parent_ids and not all(re.match(r'^#?\d+/$', a) for a in args):
		raise NotImplementedError("Can't mix 'id/' with others")
	assert len(parent_ids) <= 1, "sub-tasks listing only supports single task id"
	ids = [a[:-1] if re.match(r'^#?\d+/$', a) else a for a in args]

	client = XunleiClient(args.username, args.password, args.cookies)
	if parent_ids:
		args[0] = args[0][:-1]
		tasks = lixian_query.search_tasks(client, args)
		assert len(tasks) == 1
		tasks = client.list_bt(tasks[0])
		#tasks = client.list_bt(client.get_task_by_id(parent_ids[0]))
		tasks.sort(key=lambda x: int(x['index']))
	else:
		tasks = lixian_query.search_tasks(client, args)
		if len(args) == 1 and re.match(r'\d+/', args[0]) and len(tasks) == 1 and 'files' in tasks[0]:
			parent_ids = [tasks[0]['id']]
			tasks = tasks[0]['files']
	columns = ['n', 'id', 'name', 'status', 'size', 'progress', 'speed', 'date', 'dcid', 'gcid', 'original-url', 'download-url']
	columns = filter(lambda k: getattr(args, k), columns)

	output_tasks(tasks, columns, args, not parent_ids)
Пример #12
0
def logout(args):
	if len(args):
		raise RuntimeError('Too many arguments')
	print 'logging out from', args.cookies
	assert args.cookies
	client = XunleiClient(cookie_path=args.cookies, login=False)
	client.logout()
Пример #13
0
def list_task(args):
	args = parse_login_command_line(args, [],
	                                ['all', 'completed',
	                                 'task-id', 'name', 'status', 'size', 'dcid', 'original-url', 'download-url',
	                                 'id', 'file', 'url',],
									default={'task-id': True, 'name': True, 'status': True})
	client = XunleiClient(args.username, args.password, args.cookies)
	client.set_page_size(100)
	if args.id or args.file or args.url or len(args):
		tasks = search_tasks(client, args, status=(args.completed and 'completed' or 'all'), check=False)
	elif args.completed:
		tasks = client.read_all_completed()
	else:
		tasks = client.read_all_tasks()
	columns = ['task-id', 'name', 'status', 'size', 'dcid', 'original-url', 'download-url']
	columns = filter(lambda k: getattr(args, k), columns)
	for t in tasks:
		for k in columns:
			if k == 'task-id':
				print t['id'],
			elif k == 'name':
				print t['name'].encode(default_encoding),
			elif k == 'status':
				print t['status_text'],
			elif k == 'size':
				print t['size'],
			elif k == 'dcid':
				print t['dcid'],
			elif k == 'original-url':
				print t['original_url'],
			elif k == 'download-url':
				print t['xunlei_url'],
			else:
				raise NotImplementedError()
		print
Пример #14
0
def readd_task(args):
	args = parse_login_command_line(args, [], ['deleted', 'expired'], help=lixian_help.readd)
	client = XunleiClient(args.username, args.password, args.cookies)
	if args.deleted:
		status = 'deleted'
	elif args.expired:
		status = 'expired'
	else:
		raise NotImplementedError('Please use --expired or --deleted')
	to_readd = search_tasks(client, args, status=status)
	non_bt = []
	bt = []
	if not to_readd:
		return
	print "Below files are going to be re-added:"
	for x in to_readd:
		print x['name'].encode(default_encoding)
		if x['type'] == 'bt':
			bt.append((x['bt_hash'], x['id']))
		else:
			non_bt.append((x['original_url'], x['id']))
	if non_bt:
		urls, ids = zip(*non_bt)
		client.add_batch_tasks(urls, ids)
	for hash, id in bt:
		client.add_torrent_task_by_info_hash2(hash, id)
Пример #15
0
def download_task(args):
	args = parse_login_command_line(args, ['tool', 'output', 'output-dir', 'input'], ['delete', 'continue', 'overwrite', 'torrent', 'id', 'name', 'url'], alias={'o': 'output', 'i': 'input'}, default={'tool':'wget'})
	download = {'wget':wget_download, 'curl': curl_download, 'aria2':aria2_download, 'asyn':asyn_download, 'urllib2':urllib2_download}[args.tool]
	download_args = {'output_dir':args.output_dir, 'delete':args.delete, 'resuming':args._args['continue'], 'overwrite':args.overwrite}
	client = XunleiClient(args.username, args.password, args.cookies)
	links = None
	if len(args) > 1 or args.input:
		assert not(args.id or args.name or args.url or args.output)
		tasks = find_tasks_to_download(client, args)
		download_multiple_tasks(client, download, tasks, **download_args)
	elif args.torrent:
		# TODO: --torrent should support multiple torrent tasks. Workaround: use bt://infohash without --torrent.
		assert not(args.id or args.name or args.url)
		assert len(args) == 1
		tasks = find_torrents_task_to_download(client, [args[0]])
		assert len(tasks) == 1
		download_single_task(client, download, tasks[0], args.output, **download_args)
	else:
		if len(args) == 1:
			assert not args.url
			args.url = args[0]
		tasks = search_tasks(client, args, status='all', check=False)
		if not tasks:
			assert args.url
			print 'Adding new task %s ...' % args.url
			client.add_task(args.url)
			tasks = client.read_all_completed()
			tasks = filter_tasks(tasks, 'original_url', args.url)
			assert tasks, 'task not found, wired'
		if args.output:
			assert len(tasks) == 1
			download_single_task(client, download, tasks[0], args.output, **download_args)
		else:
			download_multiple_tasks(client, download, tasks, **download_args)
Пример #16
0
def pause_task(args):
	client = XunleiClient(args.username, args.password, args.cookies)
	to_pause = search_tasks(client, args)
	print "Below files are going to be paused:"
	for x in to_pause:
		print x['name'].encode(default_encoding)
	client.pause_tasks(to_pause)
Пример #17
0
def export_aria2(args):
	import lixian_cli
	args = lixian_cli.parse_login_command_line(args)
	from lixian import XunleiClient
	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))
	for url, name, dir in files:
		print url
		from lixian_encoding import default_encoding
		print '  out=' + name.encode(default_encoding)
		if dir:
			print '  dir=' + dir.encode(default_encoding)
		print '  header=Cookie: gdriveid=' + client.get_gdriveid()
Пример #18
0
def list_task(args):

    parent_ids = [a[:-1] for a in args if re.match(r'^#?\d+/$', a)]
    if parent_ids and not all(re.match(r'^#?\d+/$', a) for a in args):
        raise NotImplementedError("Can't mix 'id/' with others")
    assert len(
        parent_ids) <= 1, "sub-tasks listing only supports single task id"
    ids = [a[:-1] if re.match(r'^#?\d+/$', a) else a for a in args]

    client = XunleiClient(args.username, args.password, args.cookies)
    if parent_ids:
        args[0] = args[0][:-1]
        tasks = lixian_query.search_tasks(client, args)
        assert len(tasks) == 1
        tasks = client.list_bt(tasks[0])
        #tasks = client.list_bt(client.get_task_by_id(parent_ids[0]))
        tasks.sort(key=lambda x: int(x['index']))
    else:
        tasks = lixian_query.search_tasks(client, args)
        if len(args) == 1 and re.match(
                r'\d+/', args[0]) and len(tasks) == 1 and 'files' in tasks[0]:
            parent_ids = [tasks[0]['id']]
            tasks = tasks[0]['files']
    columns = [
        'n', 'id', 'name', 'status', 'size', 'progress', 'speed', 'date',
        'dcid', 'gcid', 'original-url', 'download-url'
    ]
    columns = filter(lambda k: getattr(args, k), columns)

    output_tasks(tasks, columns, args, not parent_ids)
Пример #19
0
def readd_task(args):
    client = XunleiClient(args.username, args.password, args.cookies)
    if args.deleted:
        status = "deleted"
    elif args.expired:
        status = "expired"
    else:
        raise NotImplementedError("Please use --expired or --deleted")
    to_readd = search_tasks(client, args, status=status)
    non_bt = []
    bt = []
    if not to_readd:
        return
    print "Below files are going to be re-added:"
    for x in to_readd:
        print x["name"].encode(default_encoding)
        if x["type"] == "bt":
            bt.append((x["bt_hash"], x["id"]))
        else:
            non_bt.append((x["original_url"], x["id"]))
    if non_bt:
        urls, ids = zip(*non_bt)
        client.add_batch_tasks(urls, ids)
    for hash, id in bt:
        client.add_torrent_task_by_info_hash2(hash, id)
Пример #20
0
def add_task(args):
	args = parse_login_command_line(args, ['input'], ['torrent'], alias={'i':'input'}, help=lixian_help.add)
	assert len(args) or args.input
	client = XunleiClient(args.username, args.password, args.cookies)
	links = []
	links.extend(args)
	if args.input:
		with open(args.input) as x:
			links.extend(line.strip() for line in x.readlines() if line.strip())
	if not args.torrent:
		print 'Adding below tasks:'
		for link in links:
			print link
		client.add_batch_tasks(links)
		print 'All tasks added. Checking status...'
		tasks = client.read_all_tasks()
		for link in links:
			found = filter_tasks(tasks, 'original_url', link)
			if found:
				print found[0]['status_text'], link
			else:
				print 'unknown', link
	else:
		tasks = find_torrents_task_to_download(client, links)
		assert len(tasks) == len(links)
		print 'All tasks added:'
		for link, task in zip(links, tasks):
			print task['status_text'], link
Пример #21
0
def download_task(args):
	args = parse_login_command_line(args,
	                                ['tool', 'output', 'output-dir', 'input'],
	                                ['delete', 'continue', 'overwrite', 'torrent', 'all', 'mini-hash', 'hash'],
									alias={'o': 'output', 'i': 'input', 'c':'continue', 'bt':'torrent'},
									default={'tool':get_config('tool', 'wget'),'delete':get_config('delete'),'continue':get_config('continue'),'output-dir':get_config('output-dir'), 'mini-hash':get_config('mini-hash'), 'hash':get_config('hash', True)},
	                                help=lixian_help.download)
	import lixian_download_tools
	download = lixian_download_tools.get_tool(args.tool)
	download_args = {'output':args.output, 'output_dir':args.output_dir, 'delete':args.delete, 'resuming':args._args['continue'], 'overwrite':args.overwrite, 'mini_hash':args.mini_hash, 'no_hash': not args.hash}
	client = XunleiClient(args.username, args.password, args.cookies)
	links = None
	if len(args) or args.input:
		tasks = find_tasks_to_download(client, args)
		if args.output:
			assert len(tasks) == 1
			download_single_task(client, download, tasks[0], download_args)
		else:
			download_multiple_tasks(client, download, tasks, download_args)
	elif args.all:
		#tasks = client.read_all_completed()
		tasks = client.read_all_tasks()
		download_multiple_tasks(client, download, tasks, download_args)
	else:
		usage(doc=lixian_help.download, message='Not enough arguments')
Пример #22
0
def download_task(args):
    import lixian_download_tools

    download = lixian_download_tools.get_tool(args.tool)
    download_args = {
        "output": args.output,
        "output_dir": args.output_dir,
        "delete": args.delete,
        "resuming": args._args["continue"],
        "overwrite": args.overwrite,
        "mini_hash": args.mini_hash,
        "no_hash": not args.hash,
    }
    client = XunleiClient(args.username, args.password, args.cookies)
    links = None
    if len(args) or args.input:
        tasks = find_tasks_to_download(client, args)
        if args.output:
            assert len(tasks) == 1
            download_single_task(client, download, tasks[0], download_args)
        else:
            download_multiple_tasks(client, download, tasks, download_args)
    elif args.all:
        tasks = client.read_all_tasks()
        download_multiple_tasks(client, download, tasks, download_args)
    else:
        usage(doc=lixian_help.download, message="Not enough arguments")
Пример #23
0
def login(args):
	if args.cookies == '-':
		args._args['cookies'] = None
	if len(args) < 1:
		args.username = args.username or XunleiClient(cookie_path=args.cookies, login=False).get_username() or get_config('username') or raw_input('ID: ')
		args.password = args.password or get_config('password') or getpass('Password: '******'username')
		args.password = args[0]
		if args.password == '-':
			args.password = getpass('Password: '******'-':
			args.password = getpass('Password: '******'-':
			args.password = getpass('Password: '******'Too many arguments')
	if not args.username:
		raise RuntimeError("What's your name?")
	if args.cookies:
		print 'Saving login session to', args.cookies
	else:
		print 'Testing login without saving session'
	import lixian_verification_code
	verification_code_reader = lixian_verification_code.default_verification_code_reader(args)
	XunleiClient(args.username, args.password, args.cookies, login=True, verification_code_reader=verification_code_reader)
Пример #24
0
def addtask():
	rs={'msg':'','log':'','rst':'','data':{}}
	form = cgi.FieldStorage()
	if "url" in form:
		url=form["url"].value
	else:
		url = None
		rs['msg']="needurl"
		return rs	
		
	bt = 0
	if "tasktype" in form:
		bt = (form["tasktype"].value == "bt")	
		
		
	try:
		sys.path.append('core')
		from lixian_url import url_unmask
		url = url_unmask(url)			
		conf=readconf()		
		from lixian import XunleiClient
		client = XunleiClient(conf['username'],conf['password'],conf['LIXIAN_HOME'] +'/.xunlei.lixian.cookies')		
		if (url.startswith('http://') or url.startswith('ftp://')) and bt:
			torrent = urllib2.urlopen(url, timeout=60).read()		
			client.add_torrent_task_by_content(torrent, os.path.basename(url))
			rs['msg']="addok"
		else:
			client.add_task(url)	
			rs['msg']="addok"
	except Exception as inst:
		rs['msg']="addng"
		rs['log']=str(inst)
		
	return rs
Пример #25
0
def restart_task(args):
	client = XunleiClient(args.username, args.password, args.cookies)
	to_restart = lixian_query.search_tasks(client, args)
	print "Below files are going to be restarted:"
	for x in to_restart:
		print x['name'].encode(default_encoding)
	client.restart_tasks(to_restart)
Пример #26
0
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
Пример #27
0
def pause_task(args):
    client = XunleiClient(args.username, args.password, args.cookies)
    to_pause = lixian_query.search_tasks(client, args)
    print "Below files are going to be paused:"
    for x in to_pause:
        print x['name'].encode(default_encoding)
    client.pause_tasks(to_pause)
Пример #28
0
def create_client(args):
	from lixian import XunleiClient
	import lixian_verification_code
	verification_code_reader = lixian_verification_code.default_verification_code_reader(args)
	client = XunleiClient(args.username, args.password, args.cookies, verification_code_reader=verification_code_reader)
	if args.page_size:
		client.page_size = int(args.page_size)
	return client
Пример #29
0
def restart_task(args):
	args = parse_login_command_line(args, [], ['i', 'all'], help=lixian_help.restart)
	client = XunleiClient(args.username, args.password, args.cookies)
	to_restart = search_tasks(client, args)
	print "Below files are going to be restarted:"
	for x in to_restart:
		print x['name'].encode(default_encoding)
	client.restart_tasks(to_restart)
Пример #30
0
def pause_task(args):
    args = parse_login_command_line(args, [], ["i", "all"], help=lixian_help.pause)
    client = XunleiClient(args.username, args.password, args.cookies)
    to_pause = search_tasks(client, args)
    print "Below files are going to be paused:"
    for x in to_pause:
        print x["name"].encode(default_encoding)
    client.pause_tasks(to_pause)
Пример #31
0
def restart_task(args):
	args = parse_login_command_line(args, [], ['id', 'file', 'url', 'i', 'all'])
	client = XunleiClient(args.username, args.password, args.cookies)
	to_restart = search_tasks(client, args)
	print "Below files are going to be restarted:"
	for x in to_restart:
		print x['name']
	client.restart_tasks(to_restart)
Пример #32
0
def create_client(args):
	from lixian import XunleiClient
	import lixian_verification_code
	verification_code_reader = lixian_verification_code.default_verification_code_reader(args)
	client = XunleiClient(args.username, args.password, args.cookies, verification_code_reader=verification_code_reader)
	if args.page_size:
		client.page_size = int(args.page_size)
	return client
Пример #33
0
def logout(args):
	args = parse_command_line(args, ['cookies'], default={'cookies': LIXIAN_DEFAULT_COOKIES}, help=lixian_help.logout)
	if len(args):
		raise RuntimeError('Too many arguments')
	print 'logging out from', args.cookies
	assert args.cookies
	client = XunleiClient(cookie_path=args.cookies, login=False)
	client.logout()
Пример #34
0
def rename_task(args):
    if len(args) != 2 or not re.match(r'\d+$', args[0]):
        usage(lixian_help.rename, 'Incorrect arguments')
        sys.exit(1)
    client = XunleiClient(args.username, args.password, args.cookies)
    taskid, new_name = args
    task = client.get_task_by_id(taskid)
    client.rename_task(task, from_native(new_name))
Пример #35
0
def logout(args):
	args = parse_command_line(args, ['cookies'], default={'cookies': LIXIAN_DEFAULT_COOKIES}, help=lixian_help.logout)
	if len(args):
		raise RuntimeError('Too many arguments')
	print 'logging out from', args.cookies
	assert args.cookies
	client = XunleiClient(cookie_path=args.cookies, login=False)
	client.logout()
Пример #36
0
def restart_task(args):
	args = parse_login_command_line(args, [], ['i', 'all'], help=lixian_help.restart)
	client = XunleiClient(args.username, args.password, args.cookies)
	to_restart = search_tasks(client, args)
	print "Below files are going to be restarted:"
	for x in to_restart:
		print x['name'].encode(default_encoding)
	client.restart_tasks(to_restart)
Пример #37
0
def pause_task(args):
	args = parse_login_command_line(args, [], ['search', 'i', 'all'], help=lixian_help.pause)
	client = XunleiClient(args.username, args.password, args.cookies)
	to_pause = search_tasks(client, args)
	print "Below files are going to be paused:"
	for x in to_pause:
		print x['name']
	client.pause_tasks(to_pause)
Пример #38
0
def rename_task(args):
	if len(args) != 2 or not re.match(r'\d+$', args[0]):
		usage(lixian_help.rename, 'Incorrect arguments')
		sys.exit(1)
	client = XunleiClient(args.username, args.password, args.cookies)
	taskid, new_name = args
	task = client.get_task_by_id(taskid)
	client.rename_task(task, from_native(new_name))
Пример #39
0
def rename_task(args):
    args = parse_login_command_line(args, [], [], help=lixian_help.rename)
    if len(args) != 2 or not re.match(r"\d+$", args[0]):
        usage(lixian_help.rename, "Incorrect arguments")
        sys.exit(1)
    client = XunleiClient(args.username, args.password, args.cookies)
    taskid, new_name = args
    task = client.get_task_by_id(taskid)
    client.rename_task(task, from_native(new_name))
Пример #40
0
def lixian_info(args):
    args = parse_login_command_line(args, help=lixian_help.info)
    client = XunleiClient(args.username,
                          args.password,
                          args.cookies,
                          login=False)
    print 'id:', client.get_username()
    print 'internalid:', client.get_userid()
    print 'gdriveid:', client.get_gdriveid() or ''
Пример #41
0
def pause_task(args):
    args = parse_login_command_line(args, [], ['search', 'i', 'all'],
                                    help=lixian_help.pause)
    client = XunleiClient(args.username, args.password, args.cookies)
    to_pause = search_tasks(client, args)
    print "Below files are going to be paused:"
    for x in to_pause:
        print x['name']
    client.pause_tasks(to_pause)
Пример #42
0
def list():
	rs={'msg':'','log':'','rst':'','data':{}}
	form = cgi.FieldStorage()

	if "tasktype" in form:
		status=form["tasktype"].value
	else:
		status = 'all'

	if "id" in form:
		id=form["id"].value
	else:
		id = None

	try:
		sys.path.append('core')
		from wshconfig import readconf
		conf=readconf()
		from lixian import XunleiClient
		client = XunleiClient(conf['username'],conf['password'],conf['LIXIAN_HOME'] +'/.xunlei.lixian.cookies')
	except  Exception as e:
		rs['msg'] = "needlogin"
		rs['log'] = str(e)
		return rs

	if status == 'all':
		tasks = client.read_all_tasks()
	elif status == 'completed':
		tasks = filter(lambda x: x['status_text'] == 'completed', client.read_all_tasks())
	elif status == 'deleted':
		tasks = client.read_all_deleted()
	elif status == 'expired':
		tasks = client.read_all_expired()

	outputs=[]
	for i, t in enumerate(tasks):
		one={}
		one['name']=t['name']
		one['id']=t['id']
		one["status"]=t["status_text"]
		one["size"]=t["size"]
		one["progress"]=t["progress"]
		one["type"]=t["type"]
		outputs.append(one)

	rs["data"]=outputs

	return rs
Пример #43
0
def delete_task(args):
    args = parse_login_command_line(args, [], ["i", "all"], help=lixian_help.delete)
    client = XunleiClient(args.username, args.password, args.cookies)
    to_delete = search_tasks(client, args)
    print "Below files are going to be deleted:"
    for x in to_delete:
        print x["name"].encode(default_encoding)
    if args.i:
        yes_or_no = raw_input("Are your sure to delete below files from Xunlei cloud? ")
        while yes_or_no.lower() not in ("y", "yes", "n", "no"):
            yes_or_no = raw_input("yes or no? ")
        if yes_or_no.lower() in ("y", "yes"):
            pass
        elif yes_or_no.lower() in ("n", "no"):
            raise RuntimeError("Deletion abort per user request.")
    client.delete_tasks(to_delete)
Пример #44
0
def delete_task(args):
	args = parse_login_command_line(args, [], ['i', 'all'], help=lixian_help.delete)
	client = XunleiClient(args.username, args.password, args.cookies)
	to_delete = search_tasks(client, args)
	print "Below files are going to be deleted:"
	for x in to_delete:
		print x['name'].encode(default_encoding)
	if args.i:
		yes_or_no = raw_input('Are your sure to delete below files from Xunlei cloud? ')
		while yes_or_no.lower() not in ('y', 'yes', 'n', 'no'):
			yes_or_no = raw_input('yes or no? ')
		if yes_or_no.lower() in ('y', 'yes'):
			pass
		elif yes_or_no.lower() in ('n', 'no'):
			raise RuntimeError('Deletion abort per user request.')
	client.delete_tasks(to_delete)
Пример #45
0
def delete_task(args):
	args = parse_login_command_line(args, [], ['i', 'all'], help=lixian_help.delete)
	client = XunleiClient(args.username, args.password, args.cookies)
	to_delete = search_tasks(client, args)
	print "Below files are going to be deleted:"
	for x in to_delete:
		print x['name'].encode(default_encoding)
	if args.i:
		yes_or_no = raw_input('Are your sure to delete below files from Xunlei cloud? ')
		while yes_or_no.lower() not in ('y', 'yes', 'n', 'no'):
			yes_or_no = raw_input('yes or no? ')
		if yes_or_no.lower() in ('y', 'yes'):
			pass
		elif yes_or_no.lower() in ('n', 'no'):
			raise RuntimeError('Deletion abort per user request.')
	client.delete_tasks(to_delete)
Пример #46
0
def list_task(args):
    args = parse_login_command_line(args, [], [
        'all', 'completed', 'id', 'name', 'status', 'size', 'dcid',
        'original-url', 'download-url', 'search'
    ],
                                    default={
                                        'id': True,
                                        'name': True,
                                        'status': True
                                    },
                                    help=lixian_help.list)

    parent_ids = [a[:-1] for a in args if re.match(r'^\d+/$', a)]
    if parent_ids and not all(re.match(r'^\d+/$', a) for a in args):
        raise NotImplementedError("Can't mix 'id/' with others")
    assert len(
        parent_ids) <= 1, "sub-tasks listing only supports single task id"
    ids = [a[:-1] if re.match(r'^\d+/$', a) else a for a in args]

    client = XunleiClient(args.username, args.password, args.cookies)
    client.set_page_size(100)
    if parent_ids:
        tasks = client.list_bt(client.get_task_by_id(parent_ids[0]))
        tasks.sort(key=lambda x: int(x['index']))
    elif len(ids):
        tasks = search_tasks(client,
                             args,
                             status=(args.completed and 'completed' or 'all'),
                             check=False)
    elif args.completed:
        tasks = client.read_all_completed()
    else:
        tasks = client.read_all_tasks()
    columns = [
        'id', 'name', 'status', 'size', 'dcid', 'original-url', 'download-url'
    ]
    columns = filter(lambda k: getattr(args, k), columns)
    for t in tasks:
        for k in columns:
            if k == 'id':
                print t.get('index', t['id']),
            elif k == 'name':
                print t['name'].encode(default_encoding),
            elif k == 'status':
                print t['status_text'],
            elif k == 'size':
                print t['size'],
            elif k == 'dcid':
                print t['dcid'],
            elif k == 'original-url':
                print t['original_url'],
            elif k == 'download-url':
                print t['xunlei_url'],
            else:
                raise NotImplementedError()
        print
Пример #47
0
def readd_task(args):
    if args.deleted:
        status = 'deleted'
    elif args.expired:
        status = 'expired'
    else:
        raise NotImplementedError('Please use --expired or --deleted')
    client = XunleiClient(args.username, args.password, args.cookies)
    if status == 'expired' and args.all:
        return client.readd_all_expired_tasks()
    to_readd = lixian_query.search_tasks(client, args)
    non_bt = []
    bt = []
    if not to_readd:
        return
    print "Below files are going to be re-added:"
    for x in to_readd:
        print x['name'].encode(default_encoding)
        if x['type'] == 'bt':
            bt.append((x['bt_hash'], x['id']))
        else:
            non_bt.append((x['original_url'], x['id']))
    if non_bt:
        urls, ids = zip(*non_bt)
        client.add_batch_tasks(urls, ids)
    for hash, id in bt:
        client.add_torrent_task_by_info_hash2(hash, id)
Пример #48
0
def delete_task(args):
    client = XunleiClient(args.username, args.password, args.cookies)
    to_delete = search_tasks(client, args)
    from lixian_colors import colors

    with colors.red.bold():
        print "Below files are going to be deleted:"
        for x in to_delete:
            print x["name"].encode(default_encoding)
    if args.i:
        yes_or_no = raw_input("Are your sure to delete below files from Xunlei cloud? ")
        while yes_or_no.lower() not in ("y", "yes", "n", "no"):
            yes_or_no = raw_input("yes or no? ")
        if yes_or_no.lower() in ("y", "yes"):
            pass
        elif yes_or_no.lower() in ("n", "no"):
            raise RuntimeError("Deletion abort per user request.")
    client.delete_tasks(to_delete)
Пример #49
0
def download_task(args):
	import lixian_download_tools
	download = lixian_download_tools.get_tool(args.tool)
	download_args = {'output':args.output, 'output_dir':args.output_dir, 'delete':args.delete, 'resuming':args._args['continue'], 'overwrite':args.overwrite, 'mini_hash':args.mini_hash, 'no_hash': not args.hash}
	client = XunleiClient(args.username, args.password, args.cookies)
	links = None
	if len(args) or args.input:
		tasks = find_tasks_to_download(client, args)
		if args.output:
			assert len(tasks) == 1
			download_single_task(client, download, tasks[0], download_args)
		else:
			download_multiple_tasks(client, download, tasks, download_args)
	elif args.all:
		tasks = client.read_all_tasks()
		download_multiple_tasks(client, download, tasks, download_args)
	else:
		usage(doc=lixian_help.download, message='Not enough arguments')
Пример #50
0
def download_task(args):
    import lixian_download_tools
    download = lixian_download_tools.get_tool(args.tool)
    download_args = {'output':args.output, 'output_dir':args.output_dir, 'delete':args.delete, 'resuming':args._args['continue'], 'overwrite':args.overwrite, 'mini_hash':args.mini_hash, 'no_hash': not args.hash, 'no_bt_dir': not args.bt_dir, 'save_torrent_file':args.save_torrent_file}
    client = XunleiClient(args.username, args.password, args.cookies)
    links = None
    if len(args) or args.input:
        tasks = find_tasks_to_download(client, args)
        if args.output:
            assert len(tasks) == 1
            download_single_task(client, download, tasks[0], download_args)
        else:
            download_multiple_tasks(client, download, tasks, download_args)
    elif args.all:
        tasks = client.read_all_tasks()
        download_multiple_tasks(client, download, tasks, download_args)
    else:
        usage(doc=lixian_help.download, message='Not enough arguments')
Пример #51
0
def lixian_info(args):
	client = XunleiClient(args.username, args.password, args.cookies, login=False)
	if args.id:
		print client.get_username()
	else:
		print 'id:', client.get_username()
		print 'internalid:', client.get_userid()
		print 'gdriveid:', client.get_gdriveid() or ''
Пример #52
0
def delete_task(args):
    client = XunleiClient(args.username, args.password, args.cookies)
    to_delete = lixian_query.search_tasks(client, args)
    if not to_delete:
        print 'Nothing to delete'
        return
    with colors(args.colors).red.bold():
        print "Below files are going to be deleted:"
        for x in to_delete:
            print x['name'].encode(default_encoding)
    if args.i:
        yes_or_no = raw_input(
            'Are your sure to delete below files from Xunlei cloud? ')
        while yes_or_no.lower() not in ('y', 'yes', 'n', 'no'):
            yes_or_no = raw_input('yes or no? ')
        if yes_or_no.lower() in ('y', 'yes'):
            pass
        elif yes_or_no.lower() in ('n', 'no'):
            raise RuntimeError('Deletion abort per user request.')
    client.delete_tasks(to_delete)
Пример #53
0
def add_task(args):
    assert len(args) or args.input
    client = XunleiClient(args.username, args.password, args.cookies)
    tasks = lixian_query.find_tasks_to_download(client, args)
    print 'All tasks added. Checking status...'
    columns = ['id', 'status', 'name']
    if get_config('n'):
        columns.insert(0, 'n')
    if args.size:
        columns.append('size')
    output_tasks(tasks, columns, args)
Пример #54
0
def execute_args(args):
	download = {'wget':wget_download, 'urllib2':urllib2_download}[args.tool]

	if args.links:
		assert len(args.links) == 1
		url = args.links[0]
	else:
		url = args.link
	assert url or args.task_id or args.task_name

	client = XunleiClient(args.username, args.password, args.cookies)
	client.set_page_size(100)
	tasks = client.read_all_completed()
	if url:
		matched = filter(lambda t: t['original_url'] == url, tasks)
		if matched:
			task = matched[0]
		else:
			# if the task doesn't exist yet, add it
			# TODO: check space, check queue, delete after download done, add loggings
			client.add_task(url)
			tasks = client.read_all_completed()
			task = filter(lambda t: t['original_url'] == url, tasks)[0]
	elif args.task_name:
		task = filter(lambda t: t['name'].find(args.task_name) != -1, tasks)[0]
	elif args.task_id:
		task = filter(lambda t: t['id'] == args.task_id, tasks)[0]
	else:
		raise NotImplementedError()

	download_url = str(task['xunlei_url'])
	filename = args.output or task['name'].encode(sys.getfilesystemencoding())
	referer = str(client.get_referer())
	gdriveid = str(client.get_gdriveid())

	download(client, download_url, filename)
Пример #55
0
def get_torrent(args):
    '''
	usage: lx get-torrent [info-hash|task-id]...
	'''
    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()
            import lixian_query
            base = lixian_query.TaskBase(client, client.read_all_tasks)
            task = base.get_task_by_id(id)
            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)
Пример #56
0
def add_task(args):
	args = parse_login_command_line(args, ['input'], ['torrent'], alias={'i':'input','bt':'torrent'}, help=lixian_help.add)
	assert len(args) or args.input
	client = XunleiClient(args.username, args.password, args.cookies)
	links = []
	links.extend(args)
	if args.input:
		import fileinput
		links.extend(line.strip() for line in fileinput.input(args.input) if line.strip())
	if not args.torrent:
		tasks = find_normal_tasks_to_download(client, links)
	else:
		tasks = find_torrent_tasks_to_download(client, links)
	print 'All tasks added. Checking status...'
	for t in tasks:
		print t['id'], t['status_text'], t['name'].encode(default_encoding)
Пример #57
0
def add_task(args):
	assert len(args) or args.input
	client = XunleiClient(args.username, args.password, args.cookies)
	links = []
	links.extend(args)
	if args.input:
		import fileinput
		links.extend(line.strip() for line in fileinput.input(args.input) if line.strip())
	if not args.torrent:
		tasks = find_normal_tasks_to_download(client, links)
	else:
		tasks = find_torrent_tasks_to_download(client, links)
	print 'All tasks added. Checking status...'
	columns = ['id', 'status', 'name']
	if args.size:
		columns.append('size')
	output_tasks(tasks, columns, args)
Пример #58
0
def list_task(args):
	status = 'all'
	if args.completed:
		status = 'completed'
	elif args.deleted:
		status = 'deleted'
	elif args.expired:
		status = 'expired'

	parent_ids = [a[:-1] for a in args if re.match(r'^#?\d+/$', a)]
	if parent_ids and not all(re.match(r'^#?\d+/$', a) for a in args):
		raise NotImplementedError("Can't mix 'id/' with others")
	assert len(parent_ids) <= 1, "sub-tasks listing only supports single task id"
	ids = [a[:-1] if re.match(r'^#?\d+/$', a) else a for a in args]

	client = XunleiClient(args.username, args.password, args.cookies)
	if parent_ids:
		args[0] = args[0][:-1]
		tasks = search_tasks(client, args, status=status)
		assert len(tasks) == 1
		tasks = client.list_bt(tasks[0])
		#tasks = client.list_bt(client.get_task_by_id(parent_ids[0]))
		tasks.sort(key=lambda x: int(x['index']))
	elif len(ids):
		tasks = search_tasks(client, args, status=status)
	elif status == 'all':
		tasks = client.read_all_tasks()
	elif status == 'completed':
		tasks = filter(lambda x: x['status_text'] == 'completed', client.read_all_tasks()) # by #139
	elif status == 'deleted':
		tasks = client.read_all_deleted()
	elif status == 'expired':
		tasks = client.read_all_expired()
	else:
		raise NotImplementedError(status)
	columns = ['n', 'id', 'name', 'status', 'size', 'progress', 'speed', 'date', 'dcid', 'gcid', 'original-url', 'download-url']
	columns = filter(lambda k: getattr(args, k), columns)

	output_tasks(tasks, columns, args, not parent_ids)
Пример #59
0
def create_client(args):
    from lixian import XunleiClient
    client = XunleiClient(args.username, args.password, args.cookies)
    if args.page_size:
        client.page_size = int(args.page_size)
    return client
Пример #60
0
def download_task(args):
    args = parse_login_command_line(
        args, ['tool', 'output', 'output-dir', 'input'],
        ['delete', 'continue', 'overwrite', 'torrent', 'search', 'mini-hash'],
        alias={
            'o': 'output',
            'i': 'input',
            'c': 'continue'
        },
        default={
            'tool': get_config('tool', 'wget'),
            'delete': get_config('delete'),
            'continue': get_config('continue'),
            'output-dir': get_config('output-dir'),
            'mini-hash': get_config('mini-hash')
        },
        help=lixian_help.download)
    download = {
        'wget': wget_download,
        'curl': curl_download,
        'aria2': aria2_download,
        'asyn': asyn_download,
        'urllib2': urllib2_download
    }[args.tool]
    download_args = {
        'output_dir': args.output_dir,
        'delete': args.delete,
        'resuming': args._args['continue'],
        'overwrite': args.overwrite,
        'mini_hash': args.mini_hash
    }
    client = XunleiClient(args.username, args.password, args.cookies)
    links = None
    if len(args) > 1 or args.input:
        assert not args.output
        tasks = find_tasks_to_download(client, args)
        tasks = merge_bt_sub_tasks(tasks)
        download_multiple_tasks(client, download, tasks, **download_args)
    elif args.torrent:
        assert not args.search
        assert len(args) == 1
        tasks = find_torrents_task_to_download(client, [args[0]])
        assert len(tasks) == 1
        download_single_task(client, download, tasks[0], args.output,
                             **download_args)
    else:
        assert len(args) == 1, 'Not enough argument'
        tasks = search_tasks(client, args, status='all', check=False)
        if not tasks:
            url = args[0]
            print 'Adding new task %s ...' % url
            client.add_task(url)
            tasks = client.read_all_completed()
            tasks = filter_tasks(tasks, 'original_url', url)
            assert tasks, 'task not found, wired'
        tasks = merge_bt_sub_tasks(tasks)
        if args.output:
            assert len(tasks) == 1
            download_single_task(client, download, tasks[0], args.output,
                                 **download_args)
        else:
            download_multiple_tasks(client, download, tasks, **download_args)