2021-05-16 17:50:22 +02:00
|
|
|
import atexit
|
2023-03-09 23:09:04 +02:00
|
|
|
from multiprocessing import Value
|
2021-05-16 17:50:22 +02:00
|
|
|
|
2023-03-09 23:09:04 +02:00
|
|
|
from libretranslate.storage import get_storage
|
2021-05-16 17:50:22 +02:00
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
|
2023-03-09 20:59:25 +02:00
|
|
|
|
2023-03-09 23:09:04 +02:00
|
|
|
setup_scheduler = Value('b', False)
|
2021-05-16 17:50:22 +02:00
|
|
|
active = False
|
|
|
|
threshold = -1
|
2021-05-18 05:41:02 +02:00
|
|
|
|
2021-11-24 19:41:12 +02:00
|
|
|
def forgive_banned():
|
2021-11-24 19:49:07 +02:00
|
|
|
global threshold
|
2021-05-16 17:50:22 +02:00
|
|
|
|
2021-11-24 19:41:12 +02:00
|
|
|
clear_list = []
|
2023-03-09 23:09:04 +02:00
|
|
|
s = get_storage()
|
|
|
|
banned = s.get_all_hash_int("banned")
|
2021-11-24 19:41:12 +02:00
|
|
|
|
|
|
|
for ip in banned:
|
|
|
|
if banned[ip] <= 0:
|
|
|
|
clear_list.append(ip)
|
|
|
|
else:
|
2021-11-24 19:49:07 +02:00
|
|
|
banned[ip] = min(threshold, banned[ip]) - 1
|
2021-11-24 19:41:12 +02:00
|
|
|
|
|
|
|
for ip in clear_list:
|
2023-03-09 23:09:04 +02:00
|
|
|
s.del_hash("banned", ip)
|
2022-02-20 10:09:02 +02:00
|
|
|
|
2021-05-18 05:41:02 +02:00
|
|
|
def setup(violations_threshold=100):
|
2021-05-16 17:50:22 +02:00
|
|
|
global active
|
|
|
|
global threshold
|
|
|
|
|
|
|
|
active = True
|
|
|
|
threshold = violations_threshold
|
|
|
|
|
2023-03-09 23:09:04 +02:00
|
|
|
# Only setup the scheduler and secrets on one process
|
|
|
|
if not setup_scheduler.value:
|
|
|
|
setup_scheduler.value = True
|
|
|
|
|
|
|
|
scheduler = BackgroundScheduler()
|
|
|
|
scheduler.add_job(func=forgive_banned, trigger="interval", minutes=30)
|
2023-03-10 05:00:27 +02:00
|
|
|
|
2023-03-09 23:09:04 +02:00
|
|
|
scheduler.start()
|
2021-05-16 17:50:22 +02:00
|
|
|
|
2023-03-09 23:09:04 +02:00
|
|
|
# Shut down the scheduler when exiting the app
|
|
|
|
atexit.register(lambda: scheduler.shutdown())
|
2021-05-16 17:50:22 +02:00
|
|
|
|
|
|
|
|
|
|
|
def report(request_ip):
|
2021-05-16 17:52:39 +02:00
|
|
|
if active:
|
2023-03-09 23:09:04 +02:00
|
|
|
get_storage().inc_hash_int("banned", request_ip)
|
2021-11-05 15:55:45 +02:00
|
|
|
|
|
|
|
def decrease(request_ip):
|
2023-03-09 23:09:04 +02:00
|
|
|
s = get_storage()
|
|
|
|
if s.get_hash_int("banned", request_ip) > 0:
|
|
|
|
s.dec_hash_int("banned", request_ip)
|
2021-11-05 15:55:45 +02:00
|
|
|
|
|
|
|
def has_violation(request_ip):
|
2023-03-09 23:09:04 +02:00
|
|
|
s = get_storage()
|
|
|
|
return s.get_hash_int("banned", request_ip) > 0
|
2021-05-18 05:41:02 +02:00
|
|
|
|
2021-05-16 17:50:22 +02:00
|
|
|
def is_banned(request_ip):
|
2023-03-09 23:09:04 +02:00
|
|
|
s = get_storage()
|
|
|
|
|
2021-05-16 17:50:22 +02:00
|
|
|
# More than X offences?
|
2023-03-09 23:09:04 +02:00
|
|
|
return active and s.get_hash_int("banned", request_ip) >= threshold
|