heart2heart/src/utils.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-08-08 09:39:32 +03:00
import fs from 'fs';
2024-08-08 14:42:20 +03:00
import {
EncryptionAlgorithm,
MatrixClient,
MessageEvent,
RustSdkCryptoStorageProvider,
SimpleFsStorageProvider,
} from "matrix-bot-sdk";
2024-08-03 03:48:20 +03:00
2024-08-08 09:39:32 +03:00
const configPath = './config.json';
const messagesPath = './messages.json';
2024-08-03 03:48:20 +03:00
const logError = (message) => {
2024-08-08 09:39:32 +03:00
let time = new Date;
console.error(`[${time.toLocaleString()}] [LOG] [E] ${message}`);
};
2024-08-03 03:48:20 +03:00
const logInfo = (message) => {
2024-08-08 09:39:32 +03:00
let time = new Date;
console.log(`[${time.toLocaleString()}] [LOG] [I] ${message}`);
};
2024-08-03 03:48:20 +03:00
const readConfig = () => {
2024-08-03 03:48:20 +03:00
if (!fs.existsSync(configPath)) {
2024-08-03 12:18:42 +03:00
fs.writeFileSync(configPath,
2024-08-03 03:48:20 +03:00
`{
"homeserverURL": "https://matrix.org/",
2024-08-08 09:39:32 +03:00
"token": "Super secret token! Do not show to anyone! Even your mum! ;)",
"maxAmountOfPhotoesPerUser": 5
2024-08-03 03:48:20 +03:00
}`
);
2024-08-08 09:39:32 +03:00
logError('[LOG] [E] Config file was not found. I have created a template, please, edit it and restart a bot.');
2024-08-03 03:48:20 +03:00
2024-08-08 09:39:32 +03:00
process.exit(-1);
2024-08-03 03:48:20 +03:00
}
2024-08-08 09:39:32 +03:00
return JSON.parse(fs.readFileSync(configPath));
};
2024-08-03 03:48:20 +03:00
const readMessages = () => {
2024-08-03 03:48:20 +03:00
if (!fs.existsSync(messagesPath)) {
2024-08-08 09:39:32 +03:00
logError("No 'messages.json' file found. Please, ensure that you are up to date by syncing using 'git pull' command.");
process.exit(-1);
2024-08-03 03:48:20 +03:00
}
2024-08-08 09:39:32 +03:00
return JSON.parse(fs.readFileSync(messagesPath));
};
2024-08-08 14:42:20 +03:00
const uploadMediaFromEvent = async (client, event) => {
const message = new MessageEvent(event);
const fileEvent = new MessageEvent(message.raw);
const decrypted = await client.crypto.decryptMedia(fileEvent.content.file);
const mxc = await client.uploadContent(decrypted);
return mxc;
};
const convertMsgType = (msgtype) => {
switch (msgtype) {
case "m.image":
return "p";
case "m.video":
return "v";
case "m.text":
return "t";
default:
return msgtype;
}
};
export { readMessages, readConfig, logError, logInfo, uploadMediaFromEvent, convertMsgType };