crosswords/server/session.py

65 lines
2.0 KiB
Python
Raw Normal View History

2021-06-17 16:02:50 +02:00
import datetime as dt
from . import json_websockets
from . import crossword
class Session(object):
2021-06-24 12:10:59 +02:00
def __init__(self, days_to_expire:int = 2) -> None:
2021-06-17 16:02:50 +02:00
self.crossword = None
self.datetime_created = dt.datetime.utcnow()
self.connected_sockets = set()
2021-06-24 12:10:59 +02:00
self.last_touched = self.datetime_created
self.days_to_expire = 2
2021-06-17 16:02:50 +02:00
def cleanup(self):
sockets_to_remove = []
for socket in self.connected_sockets:
if socket.is_closed():
sockets_to_remove.append(socket)
for socket in sockets_to_remove:
self.connected_sockets.remove(socket)
def connect_socket(self,
websocket: json_websockets.JsonWebsocketConnection) -> None:
self.cleanup()
self.connected_sockets.add(websocket)
def disconnect_socket(self,
websocket: json_websockets.JsonWebsocketConnection) -> None:
if websocket in self.connected_sockets:
self.connected_sockets.remove(websocket)
def get_sockets(self) -> json_websockets.JsonWebsocketConnection:
self.cleanup()
return self.connected_sockets
def get_datetime_created(self) -> dt.datetime:
return self.datetime_created
2021-06-23 19:11:34 +02:00
def create_crossword(self, width: int = 20, height: int = 20, lang: str = "en"):
2021-06-17 16:02:50 +02:00
self.crossword = crossword.Crossword(width=width,
height=height,
2021-06-23 19:11:34 +02:00
lang_code=lang)
2021-06-17 16:02:50 +02:00
2021-06-23 19:11:34 +02:00
def get_crossword(self, lang: str = "en") -> crossword.Crossword:
2021-06-17 16:02:50 +02:00
if self.crossword is None:
2021-06-23 19:11:34 +02:00
self.create_crossword(lang = lang)
2021-06-17 16:02:50 +02:00
return self.crossword
2021-06-24 12:10:59 +02:00
def touch(self):
self.last_touched = dt.datetime.utcnow()
def is_expired(self):
self.cleanup()
if len(self.connected_sockets) > 0:
return False
now = dt.datetime.utcnow()
if (now - self.last_touched).days > self.days_to_expire:
return True
return False