Skip to content

Commit

Permalink
WIP: Refactor calendar handling; add user association and implement M…
Browse files Browse the repository at this point in the history
…iniSearch for calendar indexing
  • Loading branch information
qertis committed Feb 21, 2025
1 parent 95048f3 commit 41c5b8a
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 11 deletions.
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"express": "4.21.2",
"ical-browser": "0.1.4",
"minimist": "1.2.8",
"minisearch": "7.1.1",
"pdf-to-png-converter": "3.6.4",
"request-json-rpc2": "2.3.0",
"telegram-bot-activitystreams": "1.0.7",
Expand Down
3 changes: 2 additions & 1 deletion src/actions/private/text.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ module.exports = async (bot, message, dialog) => {
const data =
`Что: ${name}\n` +
`Где: ${location?.name ?? '-'}\n` +
`Когда: ${time}\n` +
`Когда: ${time} ${dialog.user.timezone} \n` +
'Напомнить за: 15 минут\n\n'; // todo убрать хардкод
await sendPrepareMessage(bot, message);
const googleCalendarUrl = formatGoogleCalendarUrl({
Expand Down Expand Up @@ -98,6 +98,7 @@ module.exports = async (bot, message, dialog) => {
});
await saveCalendar({
id: message.chat.id + '' + myMessage.message_id,
userId: message.chat.id,
title: name,
details: summary,
location: location?.name,
Expand Down
2 changes: 1 addition & 1 deletion src/actions/system/registration-phone.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ module.exports = async (bot, message, dialog) => {
width: page.width,
height: page.height,
caption:
page.pageNumber === 0
page.pageNumber === 1
? 'Вы зарегистрированы!\nПродолжая использовать сервис вы принимаете условия пользовательского соглашения.'
: undefined,
};
Expand Down
2 changes: 1 addition & 1 deletion src/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const { bot, middleware } = botController({
['video_note']: checkAuth(videoAction),
['document']: checkAuth(documentAction),
['contact']: checkAuth(contactAction),
['inline_query']: checkAuth(inlineAction),
['inline_query']: inlineAction,
['message_forwards']: checkAuth(textForwards),
['reply_to_message']: checkAuth(replyToMessageAction),
['pinned_message']: () => {},
Expand Down
8 changes: 3 additions & 5 deletions src/libs/dialog.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ class Dialog {
*/
constructor(user) {
this.user = user;
this.clear();
const x = getMessages(user.id);
}
clear() {
clearMessageById(this.user.id);
this._activity = {
'@context': ['https://www.w3.org/ns/activitystreams'],
'summary': '',
Expand All @@ -24,6 +19,9 @@ class Dialog {
'items': [],
};
}
clear() {
clearMessageById(this.user.id);
}
/**
* @description Обрабатывает входящее сообщение и добавляет его в активность.
* @param {object} message - Входящее сообщение.
Expand Down
27 changes: 27 additions & 0 deletions src/libs/minisearch.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const MiniSearch = require('minisearch');
const { getCalendarsByUser } = require('../models/calendars.cjs');

const miniSearch = new MiniSearch({
fields: ['title', 'details'],
storeFields: ['title', 'details'],
});

async function indexAllCalendars(userId) {
if (miniSearch.documentCount === 0) {
const documents = [];
for (const calendar of getCalendarsByUser(userId)) {
console.log('calendar', calendar)
documents.push({
id: calendar.id,
title: calendar.title,
details: calendar.details,
});
}
console.log('documents', documents)
await miniSearch.addAllAsync(documents);
}
}

module.exports.indexAllCalendars = indexAllCalendars;
module.exports.miniSearch = miniSearch;
module.exports.MiniSearch = MiniSearch;
16 changes: 13 additions & 3 deletions src/models/calendars.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ function createCalendarsTable() {
calendarsDB.exec(`
CREATE TABLE if not exists calendars(
id INTEGER PRIMARY KEY,
user_id TEXT,
message_id INTEGER,
title TEXT,
details TEXT NULL,
Expand All @@ -28,23 +29,32 @@ module.exports.getCalendarMessage = (id) => {
return events[0];
};

module.exports.getCalendarsByUser = (userId) => {
const query = calendarsDB.prepare(`SELECT * FROM calendars WHERE user_id == ${userId}`);
const events = query.all();

return events;
};

/**
* @description сохранение в базу SQLite на временное хранилище
* @param {object} calendar - объект события
* @param {number} calendar.id - идентификатор сообщения
* @param {string} calendar.userId - идентификатор пользователя
* @param {string} calendar.title - заголовок события
* @param {string} [calendar.details] - детали события
* @param {string|null} [calendar.location] - местоположение события
* @param {string} calendar.start - время начала события
* @param {string} calendar.end - время окончания события
* @param {number[]} [calendar.geo] - geo координата события
*/
module.exports.saveCalendar = ({ id, title, details = '', location = null, start, end, geo = [] }) => {
module.exports.saveCalendar = ({ id, userId, title, details = '', location = null, start, end, geo = [] }) => {
const insert = calendarsDB.prepare(`
INSERT INTO calendars (message_id, title, details, location, start, end, geo)
VALUES (:message_id, :title, :details, :location, :start, :end, :geo)`);
INSERT INTO calendars (message_id, user_id, title, details, location, start, end, geo)
VALUES (:message_id, :user_id, :title, :details, :location, :start, :end, :geo)`);
insert.run({
message_id: id,
user_id: userId,
title: title,
details: details,
location: location,
Expand Down

0 comments on commit 41c5b8a

Please sign in to comment.