From 047815fc04c215299305b2f3b1ebe9d0f174022d Mon Sep 17 00:00:00 2001 From: Ilya Sumbatyants Date: Wed, 1 Dec 2021 18:12:49 +0700 Subject: [PATCH] Add tg contact if it is required (#436) Signed-off-by: Ilya Sumbatyants --- .../src/components/Chat.svelte | 50 +++++++++++++++++-- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/plugins/telegram-resources/src/components/Chat.svelte b/plugins/telegram-resources/src/components/Chat.svelte index 4d0681b2a8..467f01feb7 100644 --- a/plugins/telegram-resources/src/components/Chat.svelte +++ b/plugins/telegram-resources/src/components/Chat.svelte @@ -61,20 +61,62 @@ }) const client = getClient() - async function onMessage(event: CustomEvent) { - await fetch(url + '/send-msg', { + async function sendMsg (to: string, msg: string) { + return await fetch(url + '/send-msg', { method: 'POST', headers: { Authorization: 'Bearer ' + getMetadata(login.metadata.LoginToken), 'Content-Type': 'application/json' }, body: JSON.stringify({ - to: contactString?.value ?? '', - msg: event.detail + to, + msg }) }) } + async function addContact (phone: string) { + const [lastName, firstName] = object.name.split(',') + + return await fetch(url + '/add-contact', { + method: 'POST', + headers: { + Authorization: 'Bearer ' + getMetadata(login.metadata.LoginToken), + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + firstName: firstName ?? '', + lastName: lastName ?? '', + phone + }) + }) + } + + async function onMessage(event: CustomEvent) { + const to = contactString?.value ?? '' + const sendRes = await sendMsg(to, event.detail) + + if (sendRes.status !== 400 || !to.startsWith('+')) { + return + } + + + const err = await sendRes.json() + if (err.code !== 'CONTACT_IMPORT_REQUIRED') { + return + } + + const addRes = await addContact(to) + + if (Math.trunc(addRes.status / 100) !== 2) { + const { message } = await addRes.json().catch(() => ({ message: 'Unknown error' })) + + throw Error(message) + } + + await sendMsg(to, event.detail) + } + function isNewDate (messages: TelegramMessage[], i: number): boolean { if (i === 0) return true const current = new Date(messages[i].modifiedOn).toLocaleDateString()