2015-08-20 17:27:15 +02:00
|
|
|
from collections import Counter
|
|
|
|
import datetime
|
2018-02-20 19:30:56 +01:00
|
|
|
from twisted.internet import task, threads
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
|
2017-04-10 16:51:49 +02:00
|
|
|
class HashWatcher(object):
|
2018-02-20 19:30:56 +01:00
|
|
|
def __init__(self, clock=None):
|
|
|
|
if not clock:
|
|
|
|
from twisted.internet import reactor as clock
|
2015-08-20 17:27:15 +02:00
|
|
|
self.ttl = 600
|
|
|
|
self.hashes = []
|
2018-02-20 19:30:56 +01:00
|
|
|
self.lc = task.LoopingCall(self._remove_old_hashes)
|
|
|
|
self.lc.clock = clock
|
2015-08-20 17:27:15 +02:00
|
|
|
|
2018-02-20 19:30:56 +01:00
|
|
|
def start(self):
|
|
|
|
return self.lc.start(10)
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
def stop(self):
|
2018-02-20 19:30:56 +01:00
|
|
|
return self.lc.stop()
|
2015-08-20 17:27:15 +02:00
|
|
|
|
2017-05-25 20:01:39 +02:00
|
|
|
def add_requested_hash(self, hashsum, contact):
|
|
|
|
from_ip = contact.compact_ip
|
2015-08-20 17:27:15 +02:00
|
|
|
matching_hashes = [h for h in self.hashes if h[0] == hashsum and h[2] == from_ip]
|
|
|
|
if len(matching_hashes) == 0:
|
|
|
|
self.hashes.append((hashsum, datetime.datetime.now(), from_ip))
|
|
|
|
|
|
|
|
def most_popular_hashes(self, num_to_return=10):
|
|
|
|
hash_counter = Counter([h[0] for h in self.hashes])
|
|
|
|
return hash_counter.most_common(num_to_return)
|
|
|
|
|
|
|
|
def _remove_old_hashes(self):
|
|
|
|
remove_time = datetime.datetime.now() - datetime.timedelta(minutes=10)
|
2016-12-14 00:16:12 +01:00
|
|
|
self.hashes = [h for h in self.hashes if h[1] < remove_time]
|