summaryrefslogtreecommitdiff
path: root/anidb_add
blob: 04dc1dff7e21ea7138d5bf6edbc4665e1ebd3775 (plain)
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
#!/usr/bin/env python

import pyanidb as anidb
import ConfigParser, os, sys, thread, time, getpass, multihash

num_threads = 0

def file_hash(name):
	e = multihash.Ed2k()
	f = open(name)
	data = f.read(32768)	
	while data:
		e.update(data)
		data = f.read(32768)
	f.close()
	return e.digest()

def hash_file(name):
	if not os.access(name, os.R_OK):
		print 'Invalid file: %s' % (name)
		return
	size = os.stat(name).st_size
	hash = file_hash(name)
	print 'Hashed: ed2k://|file|%s|%d|%s|' % (name, size, hash)
	return name, size, hash

def hash_thread(filelist, hashlist):
	global num_threads
	num_threads += 1
	try:
		while filelist:
			h = hash_file(filelist.pop(0))
			if h:
				hashlist.append(h)
	except IndexError:
		pass
	num_threads -= 1

def auth():
	try:
		c = ConfigParser.ConfigParser()
		c.read(os.path.expanduser('~/.pyanidb.conf'))
		username = c.get('auth', 'username')
		password = c.get('auth', 'password')
	except:
		username = raw_input('Username: ')
		password = getpass.getpass()
	return username, password

username, password = auth()

try:
	a = anidb.AniDB(username, password)
	#t = a.ping()
	#if t:
	#	print 'AniDB is reachable, %.3fs' % (t)
	#else:
	#	print 'AniDB is unreachable.'
	#	sys.exit(1)
	a.auth()
	print 'Logged in as user %s.' % (username)
	if a.new_version:
		print 'New version available.'
	
	filelist = sys.argv[1:]
	hashlist = []
	
	thread.start_new_thread(hash_thread, (filelist, hashlist))
		
	while hashlist or num_threads or filelist:
		if not hashlist:
			time.sleep(0.1)
			continue
		name, size, hash = hashlist.pop(0)
		try:
			while 1:
				try:
					a.add_hash(size, hash)
				except anidb.AniDBTimeout:
					print 'Connection timed out, retrying.'
					continue
				break
		except anidb.AniDBUnknownFile:
			print 'Unknown file: %s' % (name)
			continue
		print 'Added file: %s' % (name)
	print 'All operations finished.'
except anidb.AniDBUserError:
	print 'Invalid username/password.'
	sys.exit(1)
except anidb.AniDBTimeout:
	print 'Connection timed out.'
	sys.exit(1)
except anidb.AniDBError, e:
	print 'Fatal error:', e
	sys.exit(1)