48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
import datetime
|
|
import logging
|
|
import time
|
|
from threading import Thread
|
|
|
|
from hopper.models.player import PlayerList
|
|
from settings import settings
|
|
|
|
|
|
class InactivityWatchdog(Thread):
|
|
def __init__(self, players: PlayerList, *args, **kwargs) -> None:
|
|
self.players = players
|
|
self.stopped = False
|
|
super().__init__(*args, **kwargs)
|
|
|
|
def run(self) -> None:
|
|
logging.info("Starting inactivity watchdog")
|
|
while not self.stopped:
|
|
self.cleanup_players()
|
|
time.sleep(settings.inacivity_watchdog.TICK_INTERVAL)
|
|
|
|
def cleanup_players(self) -> None:
|
|
now = datetime.datetime.now()
|
|
inactivity_threshold = now - datetime.timedelta(
|
|
seconds=settings.inacivity_watchdog.INACIVITY_TIMEOUT
|
|
)
|
|
kick_threshold = now - datetime.timedelta(
|
|
seconds=settings.inacivity_watchdog.KICK_TIMEOUT
|
|
)
|
|
|
|
for player in self.players:
|
|
if player.active and player.last_seen < inactivity_threshold:
|
|
player.active = False
|
|
logging.info(f"Player {player} set as inactive")
|
|
|
|
# safe remove from list
|
|
n = 0
|
|
while n < len(self.players):
|
|
player = self.players[n]
|
|
if player.last_seen < kick_threshold:
|
|
self.players.pop(n)
|
|
logging.info(f"Player {player} kicked out")
|
|
else:
|
|
n += 1
|
|
|
|
def stop(self) -> None:
|
|
self.stopped = True
|