-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_store.py
More file actions
57 lines (52 loc) · 2.2 KB
/
state_store.py
File metadata and controls
57 lines (52 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# state_store.py
import os
import json
import datetime as dt
import tempfile
from typing import Dict, Any
from time_utils import now_kst, parse_iso, iso
class StateStore:
def __init__(self, data_file: str):
self.data_file = data_file
self.state: Dict[str, Any] = {
"totals": {}, # user_id(str) -> 누적 초(int) [주간 리포트용]
"sessions": {}, # user_id(str) -> 시작시각(ISO str)
"schedule_progress": {}, # [추가] page_id(str) -> 누적 초(int) [일정별 칭찬용]
"praised_pages": [] # [추가] page_id(str) 목록 [중복 칭찬 방지용]
}
def load(self):
if os.path.exists(self.data_file):
try:
with open(self.data_file, "r", encoding="utf-8") as f:
data = json.load(f)
self.state["totals"] = data.get("totals", {})
self.state["sessions"] = data.get("sessions", {})
self.state["schedule_progress"] = data.get("schedule_progress", {})
self.state["praised_pages"] = data.get("praised_pages", [])
except Exception:
pass
def save(self):
directory = os.path.dirname(self.data_file) or "."
os.makedirs(directory, exist_ok=True)
fd, temp_path = tempfile.mkstemp(prefix="state_", suffix=".json", dir=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(self.state, f, ensure_ascii=False)
os.replace(temp_path, self.data_file)
except Exception:
try:
os.unlink(temp_path)
except OSError:
pass
raise
def add_session_time(self, user_id: int, until: dt.datetime | None = None):
uid = str(user_id)
start_iso = self.state["sessions"].get(uid)
if not start_iso:
return 0 # 경과 시간 반환하도록 수정
start = parse_iso(start_iso)
end = until or now_kst()
elapsed = int((end - start).total_seconds())
if elapsed > 0:
self.state["totals"][uid] = self.state["totals"].get(uid, 0) + elapsed
return elapsed