-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileManager.py
225 lines (198 loc) · 8.36 KB
/
FileManager.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
from datetime import datetime
from os import listdir, remove
from os.path import isfile, join
from json import load, dump
from json.decoder import JSONDecodeError
from typing import List
from discord.guild import Guild
from discord.role import Role
from discord.channel import TextChannel
from discord.message import Message
from cfg import DATA_FOLDER, DEFAULT_PORT, STAT_DATA_FOLDER, WEEK_NUMBER_FILE, DEFAULT_LANG, LANGS
from Logger import Logger
class StatFileManager():
@classmethod
def __getFileList(cls) -> List[str]:
return [f for f in listdir(STAT_DATA_FOLDER) if isfile(join(STAT_DATA_FOLDER, f))]
@classmethod
def getGuildsIds(cls) -> List[int]:
rtrn = []
for file in cls.__getFileList():
try:
if not WEEK_NUMBER_FILE.endswith(file):
rtrn.append(int(file.replace(".json", "")))
except ValueError:
Logger.printLog(f"{file} had invalid name. Its ignored in statistics")
return rtrn
@classmethod
def createStats(cls, guild_id: int, val: int = 0):
with open(f"{STAT_DATA_FOLDER}{guild_id}.json", 'w') as f:
dump({
"total_calls": val,
"calls_this_week": val
}, f)
@classmethod
def getStats(cls, guild_id: int):
try:
with open(f"{STAT_DATA_FOLDER}{guild_id}.json", 'r') as f:
return load(f)
except FileNotFoundError:
return False
@classmethod
def __setStats(cls, guild_id: int, total_calls: int, calls_this_week: int):
with open(f"{STAT_DATA_FOLDER}{guild_id}.json", 'w') as f:
dump({
"total_calls": total_calls,
"calls_this_week": calls_this_week
}, f)
@classmethod
def setWeekCalls(cls, guild_id: int, calls_this_week: int):
data = cls.getStats(guild_id)
if not data:
return False
cls.__setStats(guild_id, data["total_calls"], calls_this_week)
@classmethod
def __checkIfWeekPassed(cls):
with open(WEEK_NUMBER_FILE, 'r') as f:
saved_week_number = load(f)
current_week_number = datetime.now().isocalendar()[1]
if current_week_number != saved_week_number:
Logger.printLog(f"New week number {current_week_number}. Weekly stats reset")
with open(WEEK_NUMBER_FILE, 'w') as f:
dump(current_week_number, f)
for guild_id in cls.getGuildsIds():
cls.setWeekCalls(guild_id, 0)
@classmethod
def incCallStat(cls, guild_id: int):
cls.__checkIfWeekPassed()
stats = cls.getStats(guild_id)
if not stats:
cls.createStats(guild_id, 1)
return
cls.__setStats(guild_id, stats["total_calls"] + 1, stats["calls_this_week"] + 1)
@classmethod
def rmFile(cls, guild_id: int):
remove(f"{STAT_DATA_FOLDER}{guild_id}.json")
class FileManager():
@classmethod
def __getFileList(cls) -> List[str]:
return [f for f in listdir(DATA_FOLDER) if isfile(join(DATA_FOLDER, f))]
@classmethod
def getGuildsIds(cls) -> List[int]:
rtrn = []
for file in cls.__getFileList():
try:
rtrn.append(int(file.replace(".json", "")))
except ValueError:
Logger.printLog(f"{file} had invalid name. Its ignored in statistics")
return rtrn
@classmethod
def getGuildData(cls, guild_id: int):
"""Returns guild data. If file is not present returns False"""
try:
with open(f"{DATA_FOLDER}{guild_id}.json", 'r') as f:
return load(f)
except FileNotFoundError:
return False
except JSONDecodeError:
cls.createNewGuild(guild_id)
Logger.printLog(f"Guild file with id {guild_id} had invalid json format. It was overwritten")
return False
@classmethod
def createNewGuild(cls, guild_id: int):
"""Creates new guild file with default empty values"""
cls.__setGuildData(
guild_id=guild_id,
manager_role_id=-1,
channel_id=-1,
message_id=-1,
server_ip="",
port=DEFAULT_PORT,
lang=DEFAULT_LANG
)
StatFileManager.createStats(guild_id)
@classmethod
def __setGuildData(cls, guild_id: int, manager_role_id: int, channel_id: int, message_id: int, server_ip: str, port: str, lang: str):
"""Saves dict {'mgr_role': manager_role.id, 'channel': channel.id, 'message': message.id} in file <id>.json"""
with open(f"{DATA_FOLDER}{guild_id}.json", 'w') as f:
dump({
"mgr_role": manager_role_id,
"channel": channel_id,
"message": message_id,
"server_ip": server_ip,
"port": port,
"lang": lang
}, f)
@classmethod
def getRole(cls, guild_id: int):
data = cls.getGuildData(guild_id)
if data:
return data["mgr_role"]
else:
return False
@classmethod
def setRole(cls, guild_id: int, new_manager_role: Role):
"""Sets manager role for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, new_manager_role.id, data["channel"], data["message"], data["server_ip"], data["port"], data["lang"])
@classmethod
def setChannel(cls, guild_id: int, new_channel: TextChannel):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], new_channel.id, data["message"], data["server_ip"], data["port"], data["lang"])
@classmethod
def setMessage(cls, guild_id: int, new_message: Message):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], new_message.id, data["server_ip"], data["port"], data["lang"])
@classmethod
def setServerIp(cls, guild_id: int, new_ip: str):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], data["message"], new_ip, data["port"], data["lang"])
@classmethod
def setPort(cls, guild_id: int, new_port: str):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], data["message"], data["server_ip"], new_port, data["lang"])
@classmethod
def setLangRu(cls, guild_id: int):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], data["message"], data["server_ip"], data["port"], LANGS["russian"])
@classmethod
def setLangEn(cls, guild_id: int):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], data["message"], data["server_ip"], data["port"], LANGS["english"])
@classmethod
def resetChannel(cls, guild_id: int):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], -1, data["message"], data["server_ip"], data["port"], data["lang"])
@classmethod
def resetMessage(cls, guild_id: int):
"""Sets channel for guild. Returns False if file is not present"""
data = cls.getGuildData(guild_id)
if not data:
return False
cls.__setGuildData(guild_id, data["mgr_role"], data["channel"], -1, data["server_ip"], data["port"], data["lang"])
@classmethod
def rmFile(cls, guild_id: int):
remove(f"{DATA_FOLDER}{guild_id}.json")