forked from dmitriym09/calendar-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.mjs
275 lines (245 loc) · 6.12 KB
/
db.mjs
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
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import WSEvent from './types/wsevent.mjs';
export const EventStatus = {
ok: 1,
notFound: 2,
needPost: 3,
needUpdate: 4,
};
const { DB_NAME = '/var/lib/calendar_bot.db' } = process.env;
/**
* Создание подключения к БД.
*
* @param {string} filename - Путь к файлу БД.
* @returns {sqlite3.Database} - Созданный инстанс подключения к БД.
*/
export async function openDb(filename = DB_NAME) {
return open({
filename,
driver: sqlite3.Database,
});
}
/**
* Поиск события в БД.
*
* @param {string} fileName - Относительный путь файла события в архиве.
* @param {WSEvent} event - Событие.
* @param {string} markdown - Markdown описание события.
* @param {?sqlite3.Database} db - Инстанс подключения к БД.
* @returns {{ action: EventStatus, messageId: ?number }} - Статус в БД и Id поста события.
*/
export async function getEvent(fileName, event, markdown, db = null) {
if (typeof fileName != 'string' || !fileName) {
throw new TypeError(fileName);
}
if (!(event instanceof WSEvent)) {
throw new TypeError(event);
}
if (typeof markdown != 'string' || !markdown) {
throw new TypeError(markdown);
}
if (!db) {
db = await openDb();
}
const rows = await db.all(
`
select
ea.name
,t.markdown
,t.message_id
,t.created
from
events as e
left outer join telegram as t on e.id = t.event_id
left outer join event_actions as ea on ea.id = t.event_action_id
where
e.file_name = ?
order by
t.created desc,
t.id desc
limit 1;
`,
fileName,
);
if (rows.length == 0) {
return {
action: EventStatus.notFound,
};
}
if (rows[0].message_id === null) {
return {
action: EventStatus.needPost,
};
}
if (markdown === rows[0].markdown && rows[0].name == 'post') {
return {
action: EventStatus.ok,
};
}
if (markdown === rows[0].markdown && rows[0].name == 'delete') {
return {
action: EventStatus.needPost,
};
}
return {
action: EventStatus.needUpdate,
messageId: rows[0].message_id,
};
}
/**
* Запись о посте события в БД, при отсутствии события в БД оно будет создано.
*
* @param {string} fileName - Относительный путь файла события в архиве.
* @param {WSEvent} event - Событие.
* @param {string} markdown - Markdown описание события.
* @param {number} messageId - Id поста события.
* @param {?sqlite3.Database} db - Инстанс подключения к БД.
*/
export async function postEvent(
fileName,
event,
markdown,
messageId,
db = null,
) {
if (typeof fileName != 'string' || !fileName) {
throw new TypeError(fileName);
}
if (!(event instanceof WSEvent)) {
throw new TypeError(event);
}
if (typeof markdown != 'string' || !markdown) {
throw new TypeError(markdown);
}
if (typeof messageId != 'number') {
throw new TypeError(markdown);
}
if (!db) {
db = await openDb();
}
const { changes } = await db.run(
`
insert into events (file_name)
values (?)
ON CONFLICT(file_name) DO UPDATE SET
updated = julianday('now');
`,
fileName,
);
if (changes !== 1) {
throw new Error(`Error changes ${changes}`);
}
{
const { changes } = await db.run(
`
insert into telegram (
event_id,
event_action_id,
name,
city,
link,
start,
finish,
online,
markdown,
message_id)
values (
(select id from events where file_name = ?),
(select id from event_actions where name = 'post'),
?,
?,
?,
?,
?,
?,
?,
?
);
`,
fileName,
event.name,
event.city,
event.link,
event.start.valueOf(),
event.finish.valueOf(),
event.isOnline,
markdown,
messageId,
);
if (changes !== 1) {
throw new Error(`Error changes ${changes}`);
}
}
}
/**
* Запись о удалении поста события в БД, при отсутствии события в БД - исключение.
*
* @param {string} fileName - Относительный путь файла события в архиве.
* @param {WSEvent} event - Событие.
* @param {string} markdown - Markdown описание события.
* @param {number} messageId - Id поста события.
* @param {?sqlite3.Database} db - Инстанс подключения к БД.
*/
export async function deleteEvent(
fileName,
event,
markdown,
messageId,
db = null,
) {
if (typeof fileName != 'string' || !fileName) {
throw new TypeError(fileName);
}
if (!(event instanceof WSEvent)) {
throw new TypeError(event);
}
if (typeof markdown != 'string' || !markdown) {
throw new TypeError(markdown);
}
if (typeof messageId != 'number') {
throw new TypeError(markdown);
}
if (!db) {
db = await openDb();
}
const { changes } = await db.run(
`
insert into telegram (
event_id,
event_action_id,
name,
city,
link,
start,
finish,
online,
markdown,
message_id)
values (
(select id from events where file_name = ?),
(select id from event_actions where name = 'delete'),
?,
?,
?,
?,
?,
?,
?,
?
);
`,
fileName,
event.name,
event.city,
event.link,
event.start.valueOf(),
event.finish.valueOf(),
event.isOnline,
markdown,
messageId,
);
if (changes !== 1) {
throw new Error(`Error changes ${changes}`);
}
}