-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_console.py
More file actions
executable file
·293 lines (250 loc) · 6.78 KB
/
Copy pathadmin_console.py
File metadata and controls
executable file
·293 lines (250 loc) · 6.78 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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/python3
import os
import csv
import subprocess
from pprint import pprint, pformat
from datetime import datetime, timezone
from typing import Literal, Any
from IPython import embed
from table2string import Table, Themes, Theme
from config import WSGI_PATH, __version__
from notes_api.types import db, Account as notes_api_Account
from notes_bot.types import TelegramAccount # noqa
def execute(
query: str,
params: dict | tuple = (),
commit: bool = False,
mode: Literal["table", "raw", "pprint"] = "table",
max_width: int | type(max) | type(max) | None = max,
max_height: int | type(max) | type(max) | None = max,
maximize_height: bool = False,
align: tuple[str, ...] | str = "*",
name: str | None = None,
name_align: str = "^",
return_data: bool = False,
theme: Theme = Themes.ascii_thin,
) -> None | str | list[tuple[int | str | bytes | Any, ...], ...]:
"""
:param query: SQL query
:param params: tuple[str | int] or dict[str, str | int]
:param commit: bool
# :param functions: (func_name, func) or None
:param mode: "table" - ASCII table "raw" "pprint"
:param max_width:
:param max_height:
:param maximize_height:
:param align:
:param name:
:param name_align:
:param return_data:
:param theme:
:return:
"""
with db.connect():
result = db.execute(
query,
params or {},
commit,
column_names=True,
)
if mode == "table":
if max_width is max or max_height is max:
_max_width, _max_height = terminal_size()
if max_width is max:
max_width = _max_width
if max_height is max:
max_height = _max_height
if max_width is min:
max_width = None
if max_height is min:
max_height = None
if result and len(result) > 1:
table = result[1:]
column_names = result[0]
else:
table = result or [["ok"]]
column_names = None
Table(
table,
name=name,
column_names=column_names,
).print(
h_align=align,
name_h_align=name_align,
max_width=max_width,
max_height=max_height,
maximize_height=maximize_height,
theme=theme,
line_break_symbol="\\",
)
elif mode == "raw":
if return_data:
return result
print(result)
else:
if return_data:
return pformat(result)
pprint(result)
return None
def export(query: str = "SELECT * FROM events;", params: dict | tuple = ()) -> str:
path = f"data/exports/{datetime.now(timezone.utc):%Y-%m-%d_%H-%M-%S}.csv"
try:
os.mkdir("data/exports")
except FileExistsError:
pass
with open(path, "w", newline="", encoding="UTF-8") as file:
table = execute(query, params, mode="raw", return_data=True)
file_writer = csv.writer(file)
file_writer.writerows(table)
return path
def terminal_size() -> tuple[int, int]:
try:
_terminal_size = os.get_terminal_size()
except OSError:
_terminal_size = os.terminal_size((120, 30))
return _terminal_size.columns, _terminal_size.lines
def restart_server() -> None:
if WSGI_PATH:
subprocess.call(["touch", WSGI_PATH])
else:
print(f"{WSGI_PATH=}")
def chat_list(page: int = 1) -> None:
execute(
"""
SELECT c.date,
c.id,
c.type,
c.title,
c.username,
c.first_name,
c.last_name,
(
SELECT group_concat(j.key || ': ' || j.value, char(10))
FROM json_each(c.json) AS j
) AS json
FROM chats AS c
LIMIT :limit
OFFSET :offset;
""",
params={
"limit": 10,
"offset": (page - 1) * 10,
},
)
def user_list(page: int = 1) -> None:
execute(
"""
SELECT user_id,
username,
email,
user_status,
max_event_id - 1 as event_count,
reg_date,
chat_id
FROM users
LIMIT :limit
OFFSET :offset;
""",
params={
"limit": 10,
"offset": (page - 1) * 10,
},
)
def group_list(page: int = 1) -> None:
execute(
"""
SELECT group_id,
name,
owner_id,
max_event_id - 1 as event_count,
chat_id
FROM groups
LIMIT :limit
OFFSET :offset;
""",
params={
"limit": 10,
"offset": (page - 1) * 10,
},
)
def user(*, user_id: int | None = None, chat_id: int | str | None = None) -> None:
execute(
"""
SELECT user_id,
username,
email,
user_status,
max_event_id as event_count,
reg_date,
chat_id
FROM users
WHERE user_id = :user_id
OR chat_id IS :chat_id;
""",
params={
"user_id": user_id,
"chat_id": chat_id,
},
)
def ban(user_id: int, user_status: int = -1) -> None:
execute(
"""
UPDATE users
SET user_status = :user_status
WHERE user_id = :user_id;
""",
params={
"user_id": user_id,
"user_status": user_status,
},
commit=True,
)
print("\x1b[2A")
user(user_id=user_id)
class Account(notes_api_Account):
def __init__(self, user_id: int, group_id: str | None = None):
with db.connect():
super().__init__(user_id, group_id)
self.conn = None
def __enter__(self):
self.conn = db.connect()
self.conn.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return self.conn.__exit__(exc_type, exc_val, exc_tb)
HELP = """
exit -> Ctrl+D
execute(
query: str,
params: dict | tuple = (),
commit: bool = False,
mode: Literal["table", "raw", "pprint"] = "table",
max_width: int | type(max) | type(max) | None = max,
max_height: int | type(max) | type(max) | None = max,
maximize_height: bool = False,
align: tuple[str, ...] | str = "*",
name: str = None,
name_align: str = "^",
return_data: bool = False,
theme: Theme = Themes.ascii_thin,
)
export(
query: str = "SELECT * FROM events;",
params: dict | tuple = (),
) -> str # file path
terminal_size() -> tuple[int, int]
restart_server()
chat_list(page: int = 1)
user_list(page: int = 1)
group_list(page: int = 1)
user(*, user_id: int | None = None, chat_id: int | str | None = None)
ban(user_id: int, user_status: int = -1)
with Account(user_id: int) as account:
...
db.register_function(name: str, func: (...) -> Any)
Account(user_id: int, group_id: str | None = None)
TelegramAccount(chat_id: int, group_chat_id: int | None = None)
"""
if __name__ == "__main__":
print(f"notes-assistant {__version__}")
embed(colors="Linux")