-from typing import Optional, Any
-from pathlib import PurePath, Path
+from sys import stderr
+from typing import Any
+from pathlib import PurePath, Path
+from time import time
+from datetime import datetime
class Game(dict):
"""Game object generated from a directory."""
- dir : PurePath = None
- name : str = ""
- code : str = None
- src : str = ""
- tags : list = None
- desc : str = ""
- icon : Path = None # "main" icon
- icons : dict = None # all found icons
- support : Any = None # should be gamiki.Support
- library : Any = None # should be gamiki.Library
+ dir : PurePath = None
+ name : str = ""
+ code : str = None
+ src : str = ""
+ tags : list = None
+ desc : str = ""
+ total_time : int = 0
+ total_sessions : int = 0
+ sessions : list = None # list of (YYYY-MM-DD, HH:MM, time in sec)
+ icon : Path = None # "main" icon
+ icons : dict = None # all found icons
+ support : Any = None # should be gamiki.Support
+ library : Any = None # should be gamiki.Library
def __init__(self, library, dir: PurePath):
self.dir = dir
self.tags = []
self.library = library
- self._read_info(self.dir.joinpath("gameinfo.txt"))
+ self._read_info()
self._init()
self._init_icons()
icon = self._read_icon("-" + key)
if (icon): self.icons[key] = icon
- def _read_info(self, file: PurePath):
+ def _read_info(self):
+ file = self.dir.joinpath("gameinfo.txt")
try:
with open(file, encoding="utf-8") as data:
for ln in data:
self[key] = val
except FileNotFoundError:
pass
+
+ file = self.dir.joinpath("sessions.total")
+ try:
+ with open(file, encoding="utf-8") as data:
+ ln = data.readline() # number of sessions
+ sessions = int(ln.split(":", maxsplit=1)[1].strip())
+ ln = data.readline() # total time in human formated time
+ ln = data.readline() # total time in seconds
+ total = int(ln.split(":", maxsplit=1)[1].strip())
+ self.total_time = total
+ self.total_sessions = sessions
+ except FileNotFoundError:
+ pass
+ except Exception as e:
+ print(f"Error when querying {file.as_posix()}: {e}", file=stderr)
def _read_icon(self, suffix: str = "") -> PurePath:
"""
def get_icon(self, key: str) -> PurePath:
return self.icons.get(key, self.icon)
+
+ def _read_sessions(self) -> list:
+ self.sessions = []
+ file = self.dir.joinpath("sessions.txt")
+ if (file.exists()):
+ try:
+ with open(file, "r", encoding="utf-8") as data:
+ for ln in data:
+ start_d = ""
+ start_h = ""
+ total = 0
+ tab = ln.strip().split(" ")
+ if (len(tab) >= 4):
+ start_d = tab[2]
+ start_h = tab[3]
+ tab = ln.strip().split(":")
+ if (len(tab) == 5):
+ total += int(tab[2]) * 3600
+ total += int(tab[3]) * 60
+ total += int(tab[4])
+ if (start_d and start_h):
+ self.sessions.append((start_d, start_h, total))
+ except Exception as e:
+ print(f"Error when querying {file.as_posix()}: {e}",file=stderr)
+
+ def add_session(self, when: datetime, elapsed: int):
+ def human(seconds: int) -> str:
+ ss = (seconds % 60)
+ mm = (seconds // 60) % 60
+ hh = (seconds // 3600)
+ return f"{hh:02}:{mm:02}:{ss:02}"
+
+ start_d = when.strftime('%Y-%m-%d')
+ start_h = when.strftime('%H:%M')
+ text = f"Session of {start_d} ({start_h}) lasted: {human(elapsed)}"
+ print(f"[{self.name}]: {text}")
+
+ if (not self.sessions):
+ self._read_sessions()
+
+ self.sessions.append((start_d, start_h, elapsed))
+
+ total = 0
+ for session in self.sessions:
+ total += session[2]
+ print(
+ f"[{self.name}]: Total time: "
+ f"{human(total)} (in {len(self.sessions)} session(s))"
+ )
+
+ try:
+ file = self.dir.joinpath("sessions.txt")
+ with open(file, "a", encoding="utf-8") as data:
+ data.write(text)
+ data.write("\n")
+ except Exception as e:
+ print("Cannot save session time:", e, file=stderr)
+ total = None
+
+ try:
+ if (total):
+ file = self.dir.joinpath("sessions.total")
+ with open(file, "w", encoding="utf-8") as data:
+ data.write(f"Sessions: {len(self.sessions)}\n")
+ data.write(f"Total time: {human(total)}\n")
+ data.write(f"...in seconds: {total}\n")
+ except:
+ print("Cannot save total time", file=stderr)
- def start(self, params: list = None):
- if (self.support == None):
+ def run(self, params: list = None):
+ if (not self.support):
raise RuntimeError("Unsupported game was called: " + game.name)
- self.support.start(self, params)
+ begin = time()
+ today = datetime.now()
+
+ self.support._start(self, params)
+
+ elapsed = int(time() - begin)
+ self.add_session(today, elapsed)