2021-06-17 16:02:50 +02:00
|
|
|
import datetime as dt
|
|
|
|
from . import json_websockets
|
|
|
|
from . import crossword
|
|
|
|
|
|
|
|
|
|
|
|
class Session(object):
|
2021-07-03 20:21:04 +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-07-03 20:21:04 +02:00
|
|
|
|
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:
|
2021-07-03 20:21:04 +02:00
|
|
|
|
2021-06-17 16:02:50 +02:00
|
|
|
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-07-03 20:21:04 +02:00
|
|
|
def create_crossword(self, width: int = 20, height: int = 20, lang: str = "en", difficulty: int = 0):
|
2021-06-17 16:02:50 +02:00
|
|
|
self.crossword = crossword.Crossword(width=width,
|
|
|
|
height=height,
|
2021-07-03 20:21:04 +02:00
|
|
|
lang_code=lang,
|
|
|
|
difficulty=difficulty)
|
2021-06-17 16:02:50 +02:00
|
|
|
|
2021-07-03 20:21:04 +02:00
|
|
|
def get_crossword(self, lang: str = "en", difficulty: int = 0) -> crossword.Crossword:
|
2021-06-17 16:02:50 +02:00
|
|
|
if self.crossword is None:
|
2021-08-31 17:43:09 +02:00
|
|
|
size = 20
|
|
|
|
if difficulty == 0:
|
|
|
|
size = 15
|
|
|
|
if difficulty == 1:
|
|
|
|
size = 20
|
|
|
|
if difficulty == 2:
|
|
|
|
size = 30
|
|
|
|
self.create_crossword(width = size, height = size, lang=lang, difficulty=difficulty)
|
2021-07-03 20:21:04 +02:00
|
|
|
|
2021-06-17 16:02:50 +02:00
|
|
|
return self.crossword
|
2021-07-03 20:21:04 +02:00
|
|
|
|
2021-06-24 12:10:59 +02:00
|
|
|
def touch(self):
|
|
|
|
self.last_touched = dt.datetime.utcnow()
|
2021-07-03 20:21:04 +02:00
|
|
|
|
2021-06-24 12:10:59 +02:00
|
|
|
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
|
|
|
|
|
2021-07-03 20:21:04 +02:00
|
|
|
return False
|