-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.py
79 lines (53 loc) · 1.7 KB
/
database.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Import core libraries
import pickle
import typing
import config
import os
import hashlib
from enum import Enum
# Define Database Schema
class Feedback(Enum):
LIKE = 1
DISLIKE = -1
def __int__(self) -> int:
return self.value
class PostType(typing.TypedDict):
feedbacks: typing.Dict[str, Feedback]
media: typing.Optional[str]
shash: str
rating: int
class DatabaseType(typing.TypedDict):
posts: typing.Dict[int, PostType]
timings: typing.Dict[str, int]
autodelete: typing.List[int]
# Database Core Functions
def save(db: DatabaseType, name: str = config.DATABASE_FILE) -> None:
with open(file=name, mode="wb") as f:
pickle.dump(obj=db, file=f)
def load(name: str = config.DATABASE_FILE) -> DatabaseType:
try:
with open(file=name, mode="rb") as f:
db: DatabaseType = pickle.load(file=f)
return db
except FileNotFoundError:
db: DatabaseType = {"posts": {}, "timings": {}, "autodelete": []}
save(db=db)
return db
# Sugarcoated Functions
def hash(num: int) -> str:
return hashlib.md5(string=str(num + config.SEED).encode()).hexdigest()
def add_post(db: DatabaseType, shash: str, id: int, media: str = None) -> None:
if id in db["posts"]:
return
db["posts"][id] = {"feedbacks": {}, "media": media, "shash": shash, "rating": 0}
def remove_post(db: DatabaseType, id: int) -> None:
if id not in db["posts"]:
return
if id in db["autodelete"]:
db["autodelete"].remove(id)
if db["posts"][id]["media"] is not None:
try:
os.remove(db["posts"][id]["media"])
except FileNotFoundError:
pass
del db["posts"][id]