예제 #1
0
def cmd_start(*args):
	'''start downloading for torrent(s)
....$start <ids>|all'''
	if len(args) != 1:
		return "Oops, wrong number of arguments, type $help for more"

	if args[0].lower() == 'all':
		ids = [str(x) for x in TransmissionClient.list().keys()]	
	else:
		ids = args[0].split(',')

	TransmissionClient.start(ids)
	return 'Torrent ' + ','.join(sort_as_int(ids)) + ' started'
예제 #2
0
def cmd_add(*args):
	"""add a new torrent to transmission
....$add url <torrent_url>
....$add base64 '<torrent_base64>'"""
	if len(args) != 2:
		return "Oops, wrong number of arguments, type $help for more"

	if args[0].lower() == 'url':
		TransmissionClient.add_uri(args[1])
		resp = 'Torrent added'
	elif args[0].lower() == 'base64':
		TransmissionClient.add(args[1])
		resp = 'Torrent added'
	else:
		return "'%s' is not a valid option, type $help for more" % args[0].lower()

	return resp
예제 #3
0
def cmd_status(*args):
	'''show the status of all torrents'''
	resp = 'ID  Status  Progress  Size  Name\n'
	torrents = TransmissionClient.list()
	tids = torrents.keys()
	tids.sort()
	tfiles = TransmissionClient.get_files(tids)
	
	disk_usage = 0.0
	for tid in tids:
		to = torrents[tid]
		total_size = sum([x['size'] for x in tfiles[tid].values()])/float(1024*1024*1024)
		disk_usage += (to.progress*total_size)/100
		resp += '%2d  %s  %.2f%%  %.2fG  %-s\n' % (tid, to.status, to.progress, total_size, to.name)
	
	resp += 'Total disk usage is %.2fG\n'%(disk_usage)
	return resp
예제 #4
0
def cmd_remove(*args):
	'''remove torrent only or both torrent and data
....$remove <ids>|all [data]'''
	if len(args) not in [1,2]:
		return "Oops, wrong number of arguments, type $help for more"	
	
	resp = ''
	delete_data = False

	if args[0].lower() == 'all':
		ids = [str(x) for x in TransmissionClient.list().keys()]
	else:
		ids = args[0].split(',')

	if len(args)==2 and args[1].lower() == 'data':
		delete_data = True
		resp = 'Torrent ' + ','.join(sort_as_int(ids)) + ' removed with data'
	else:
		resp =  'Torrent ' + ','.join(sort_as_int(ids)) + ' removed'

	TransmissionClient.stop(ids)
	TransmissionClient.remove(ids, delete_data)
	return resp
예제 #5
0
def periodic_task(xmpp, settings):
	'''this is the function that tranmission bot need to run periodically
	xmpp: the TransmissionBot instance, use to send messages
	settings: the global settings'''
	
	# xmpp.send_message(  mto='',
 #                        mtype='chat',
 #                        mbody='hello',
 #                        mhtml='''<a href="http://www.google.co.jp">hello</a>''')

	dynamics = settings.dynamics
	logger = settings.logger

	logger.info('periodic task starting...')
	# check if there are new feed items and put them to queue
	for _id, fd in dynamics['feeds'].items():
		if fd['status'] == 'disabled':
			continue

		finfo, fdoc = feed.fetch_feed(fd['url'], fd['etag'], fd['modified'])
		logger.info('feed info: ' + str(finfo))
		if len(fdoc.entries)==0:
			logger.info('[%s] has no items'%(fd['title']))
			#print '%s has no items'%(fd['title'])
		else:
			#find new items
			new_items = feed.discover(fdoc, feed.decode_time(fd['last_published']))
			if len(new_items) == 0:
				logger.info('[%s] has no new items since %s'%(fd['title'], fd['last_published']))
				#print '%s has no new items since %s'%(fd['title'], fd['last_published'])
			else:
				#update queue in dynamics
				maxid = 0
				if not dynamics.has_key('queue'):
					dynamics['queue'] = {}
				elif dynamics['queue'].keys():
					maxid = max([int(x) for x in dynamics['queue'].keys()])	

				msg = 'I got something new for you in the queue\n'
				htmlmsg = '<p>I got something new for you in the queue<br>'
				for item in new_items:
					maxid += 1
					dynamics['queue'][str(maxid)] = {	'title':item['title'],
										 	  			'torrent_uri':item['torrent_uri'],
										 	  			'link':item['link'],
										 	  			'published':item['published'] }
					msg += '''%(title)s\n'''%item
					htmlmsg += '''<a href="%(link)s">%(title)s</a><br>'''%item
				htmlmsg += '</p>'
				logger.info(msg)
				# notify users with the new items
				if dynamics.get('notify', 'off') == 'on':
					for u in settings.accept_command_from:
						#print msg
						#print htmlmsg
						xmpp.send_message(  mto=u,
					 						mtype='chat',
					  						mbody=msg)
					   						#mhtml=htmlmsg )

				#new items found, so update the last_published to latest
				fd['last_published'] = feed.encode_time(finfo['last_published'])
				logger.info('Feed(%s) [%s]: update last_published to %s' % (_id, fd['title'], feed.encode_time(finfo['last_published'])))
		#whatever there are new items or not, update these info
		fd['title'] = finfo['title']
		fd['etag'] = finfo['etag']
		fd['modified'] = finfo['modified']
		#commit the change
		dynamics.sync()

	# notify completed downloads 
	torrents = TransmissionClient.list()
	if dynamics.get('downloads') == None:
		dynamics['downloads'] = {}
	# cleanup the downloads which do not exist 
	hslist = [x.hashString for x in torrents.values()]
	for hs in dynamics['downloads'].keys():
		if hs not in hslist:
			del dynamics['downloads'][hs]
			
	if dynamics.get('notify','off') == 'on':
		for _id, to in torrents.items():
			if to.progress < 100:
					dynamics['downloads'][to.hashString] = {'id':_id, 'name':to.name, 'progress':to.progress, 'status':to.status}
			else:
				if to.hashString in dynamics['downloads'].keys():
					for u in settings.accept_command_from:
						msg = '%s downloaded'%to.name
						xmpp.send_message(  mto=u,
				 							mtype='chat',
				  							mbody=msg )
					del dynamics['downloads'][to.hashString]

	dynamics.sync()

	# autostop the completed torrents
	if dynamics.get('autostop', 'off') == 'on':
		for _id, to in torrents.items():
			if to.progress >= 100:
				TransmissionClient.stop(_id)
			
	#ok, brb
	return True
예제 #6
0
def cmd_queue(*args):
	'''manage item queue discovered from subscribed feeds  	
....$queue list
....$queue download <ids>|all
....$queue remove <ids>|all'''

	if len(args) not in [1,2]:
		return "Oops, wrong number of arguments, type $help for more"	

	resp = ''
	if len(args) == 1 and args[0].lower() == 'list':
		resp += 'ID  Published  Title\n'
		if dynamics.get('queue', {}) == {}:
			return 'Queue is empty'
		
		#when json loaded to dict, it's not sorted by key
		sorted_ids = [int(x) for x in dynamics['queue'].keys()]
		sorted_ids.sort()
		for k in sorted_ids:
			v = dynamics['queue'][str(k)]
			resp += "%s  %-s  %-s\n" %(k, v['published'], v['title'])
		
		return resp

	elif len(args) == 2 and args[0].lower() == 'download':
		if dynamics.get('queue', {}) == {}:
			return 'Queue is empty'
				
		if args[1].lower() == 'all':
			ids_to_dl = dynamics['queue'].keys()
		else:
			ids_to_dl = args[1].split(',')

		ids_downloading = []
		for _id in ids_to_dl:
			if dynamics['queue'].has_key(_id):
				TransmissionClient.add_uri(dynamics['queue'][_id]['torrent_uri'])
				ids_downloading.append(_id)
				del dynamics['queue'][_id]

		dynamics.sync()

		if ids_downloading:
			return "Started downloading item %s" % (','.join(sort_as_int(ids_downloading)))
		else:
			return "No download started"

	elif len(args) == 2 and args[0].lower() == 'remove':
		if dynamics.get('queue', {}) == {}:
			return 'Queue is empty'
				
		if args[1].lower() == 'all':
			ids_to_rm = dynamics['queue'].keys()
		else:
			ids_to_rm = args[1].split(',')

		ids_removed = []
		for _id in ids_to_rm:
			if dynamics['queue'].has_key(_id):
				ids_removed.append(_id)
				del dynamics['queue'][_id]

		dynamics.sync()

		if ids_removed:
			return "Removed item %s" % (','.join(sort_as_int(ids_removed)))
		else:
			return "No item removed"

	else:
		return "Oops, invalid arguments, type $help for more"