Changes in config : it is now fully included in utils
[re6stnet.git] / db.py
1 import utils
2 import sqlite3
3 import xmlrpclib
4
5 class PeersDB:
6 def __init__(self, dbPath):
7
8 utils.log('Connectiong to peers database', 4)
9 self.db = sqlite3.connect(dbPath, isolation_level=None)
10 utils.log('Preparing peers database', 4)
11 try:
12 self.db.execute("UPDATE peers SET used = 0")
13 except sqlite3.OperationalError, e:
14 if e.args[0] == 'no such table: peers':
15 raise RuntimeError
16
17 def populate(self, n):
18 # TODO: don't reconnect to server each time ?
19 utils.log('Connecting to remote server', 3)
20 self.proxy = xmlrpclib.ServerProxy('http://%s:%u' % (utils.config.server, utils.config.server_port))
21 utils.log('Updating peers database : populating', 2)
22 # TODO: determine port and proto
23 port = 1194
24 proto = 'udp'
25 new_peer_list = self.proxy.getPeerList(n, (utils.config.internal_ip, utils.config.external_ip, port, proto))
26 self.db.executemany("INSERT OR IGNORE INTO peers (ip, port, proto, used) VALUES (?,?,?,0)", new_peer_list)
27 self.db.execute("DELETE FROM peers WHERE ip = ?", (utils.config.external_ip,))
28
29 def getUnusedPeers(self, nPeers):
30 return self.db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
31 "ORDER BY RANDOM() LIMIT ?", (nPeers,))
32
33 def usePeer(self, id):
34 utils.log('Updating peers database : using peer ' + str(id), 5)
35 self.db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,))
36
37 def unusePeer(self, id):
38 utils.log('Updating peers database : unusing peer ' + str(id), 5)
39 self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))