You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.6 KiB

3 years ago
import { Request, Response } from "express";
import { Op } from "sequelize";
3 years ago
import { Contact, TelegramID, User } from "../db/db";
import { strings_en } from "../strings";
3 years ago
import { sendTelegramMessage } from "../telegram";
3 years ago
interface TelegramWebhookRequest extends Request {
body: {
message: {
text: string;
from: {
id: TelegramID;
};
connected_website: string;
3 years ago
};
};
}
3 years ago
export function TelegramWebhookRoute(
req: TelegramWebhookRequest,
res: Response
) {
try {
if (req.body.message.connected_website) {
sendTelegramMessage(
req.body.message.from.id,
"Thanks for using OurSejahtera! Let's stay safer together <3"
);
} else {
3 years ago
const messageText = req.body.message.text;
const telegramID = req.body.message.from.id;
if (messageText.toLowerCase() == "/covidpositive") {
userInfected(telegramID, (result) => {
if (result.saved) {
sendTelegramMessage(
telegramID,
strings_en.telegram_inform_positive,
3 years ago
);
informContacts(telegramID);
} else {
sendTelegramMessage(telegramID, "Sorry, something went wrong.");
}
3 years ago
});
}
}
3 years ago
} catch (e) {
console.log("Could not get Telegram Message");
}
3 years ago
res.send();
}
3 years ago
function informContacts(telegramID: TelegramID) {
User.findOne({
where: {
telegram: telegramID,
},
}).then((user) => {
if (user) {
const userRowID = user.id;
Contact.findAll({
where: {
3 years ago
[Op.or]: [{ user: userRowID }, { with: userRowID }],
},
}).then((result) => {
result.forEach((contact) => {
const otherPersonID =
contact.user == userRowID ? contact.with : contact.user;
User.findOne({
where: {
id: otherPersonID,
},
}).then((otherPerson) => {
otherPerson &&
sendTelegramMessage(otherPerson.telegram, strings_en.telegram_inform_infect);
3 years ago
});
});
});
}
});
}
3 years ago
function userInfected(
telegramID: TelegramID,
callback: (callbackObject: { saved: boolean }) => void
): void {
User.findOne({
where: {
telegram: telegramID,
},
})
.then((user) => {
if (!user) {
callback({ saved: false });
} else {
user.isInfected = true;
user
.save()
.then((result) => {
if (result) {
callback({ saved: true });
}
})
.catch((err) => {
callback({ saved: false });
});
}
})
3 years ago
.catch((err) => {
callback({ saved: false });
});
}