69 lines
1.9 KiB
TypeScript
69 lines
1.9 KiB
TypeScript
|
|
import { tgBotDesignDocumentsDb } from "../dbs";
|
||
|
|
import { saveUpdateString as saveUpdate } from "@hereconnect/tg-bot-webhook-ddoc";
|
||
|
|
import { type TelegramWebhookDesignDocument } from "@hereconnect/tg-bot-webhook-ddoc";
|
||
|
|
|
||
|
|
function generateTelegramSecretToken(length = 256) {
|
||
|
|
const characters =
|
||
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
|
||
|
|
let token = "";
|
||
|
|
for (let i = 0; i < length; i++) {
|
||
|
|
const randomIndex = Math.floor(Math.random() * characters.length);
|
||
|
|
token += characters[randomIndex];
|
||
|
|
}
|
||
|
|
return token;
|
||
|
|
}
|
||
|
|
|
||
|
|
export const setupWebhookDesignDocument = async () => {
|
||
|
|
const _id = "_design/webhook";
|
||
|
|
|
||
|
|
const result: TelegramWebhookDesignDocument = {
|
||
|
|
_id,
|
||
|
|
type: "_design/webhook",
|
||
|
|
created_at: "",
|
||
|
|
updated_at: "",
|
||
|
|
updates: {
|
||
|
|
saveUpdate,
|
||
|
|
},
|
||
|
|
constants: {
|
||
|
|
telegram_secret_token: "",
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
const { rev } = await tgBotDesignDocumentsDb.upsert(_id, (ddoc) => {
|
||
|
|
const isEmptyTelegramSecretToken =
|
||
|
|
!ddoc.constants?.telegram_secret_token?.length;
|
||
|
|
const needToSetSaveUpdateFunction =
|
||
|
|
ddoc.updates?.saveUpdate !== result.updates.saveUpdate;
|
||
|
|
|
||
|
|
if (!needToSetSaveUpdateFunction && !isEmptyTelegramSecretToken) {
|
||
|
|
Object.assign(result, ddoc);
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
ddoc.updated_at = new Date().toISOString();
|
||
|
|
if (!ddoc.created_at) {
|
||
|
|
ddoc.created_at = ddoc.updated_at;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (isEmptyTelegramSecretToken) {
|
||
|
|
if (!ddoc.constants) {
|
||
|
|
ddoc.constants = result.constants;
|
||
|
|
}
|
||
|
|
ddoc.constants.telegram_secret_token = generateTelegramSecretToken();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (needToSetSaveUpdateFunction) {
|
||
|
|
if (ddoc.updates) {
|
||
|
|
ddoc.updates.saveUpdate = result.updates.saveUpdate;
|
||
|
|
} else {
|
||
|
|
ddoc.updates = result.updates;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return Object.assign(result, ddoc) satisfies TelegramWebhookDesignDocument;
|
||
|
|
});
|
||
|
|
|
||
|
|
result._rev = rev;
|
||
|
|
return result;
|
||
|
|
};
|