fix(all): Fix user switching on a single chip.

This commit is contained in:
Rodrigo Rodriguez 2023-09-09 13:04:20 -03:00
parent c577b64369
commit da02804ac9

View file

@ -198,8 +198,7 @@ export class WhatsappDirectLine extends GBService {
}; };
if (setUrl) { if (setUrl) {
createClient.bind(this)(); createClient.bind(this)();
} } else {
else {
this.customClient = minBoot.whatsAppDirectLine.customClient; this.customClient = minBoot.whatsAppDirectLine.customClient;
} }
setUrl = false; setUrl = false;
@ -309,21 +308,16 @@ export class WhatsappDirectLine extends GBService {
let answerText = null; let answerText = null;
let attachments = null; let attachments = null;
switch (provider) { switch (provider) {
case 'GeneralBots': case 'GeneralBots':
message = req; message = req;
to = message.to.endsWith('@g.us') ? message.to.split('@')[0] : message.to.split('@')[0]; to = message.to.endsWith('@g.us') ? message.to.split('@')[0] : message.to.split('@')[0];
const newThis= WhatsappDirectLine.botsByNumber[to]; const newThis = WhatsappDirectLine.botsByNumber[to];
if (newThis === undefined){ if (newThis === undefined) {
throw GBError.create(`Bot Number ${to} not setup for any loaded bot.`); throw GBError.create(`Bot Number ${to} not setup for any loaded bot.`);
} } else {
else if (newThis.min.botId !== this.min.botId) {
{ await newThis.received(req, res);
if (newThis.min.botId !== this.min.botId)
{
await newThis.received (req, res);
return; return;
} }
@ -336,9 +330,14 @@ export class WhatsappDirectLine extends GBService {
if (message.hasMedia) { if (message.hasMedia) {
const base64Image = await message.downloadMedia(); const base64Image = await message.downloadMedia();
let buf: any = Buffer.from(base64Image.data, "base64"); let buf: any = Buffer.from(base64Image.data, 'base64');
const gbaiName = DialogKeywords.getGBAIPath(this.min.botId); const gbaiName = DialogKeywords.getGBAIPath(this.min.botId);
const localName = Path.join('work', gbaiName, 'cache', `tmp${GBAdminService.getRndReadableIdentifier()}.docx`); const localName = Path.join(
'work',
gbaiName,
'cache',
`tmp${GBAdminService.getRndReadableIdentifier()}.docx`
);
Fs.writeFileSync(localName, buf, { encoding: null }); Fs.writeFileSync(localName, buf, { encoding: null });
const url = urlJoin(GBServer.globals.publicAddress, this.min.botId, 'cache', Path.basename(localName)); const url = urlJoin(GBServer.globals.publicAddress, this.min.botId, 'cache', Path.basename(localName));
@ -546,7 +545,6 @@ export class WhatsappDirectLine extends GBService {
); );
if (user.agentSystemId.indexOf('@') !== -1) { if (user.agentSystemId.indexOf('@') !== -1) {
// Agent is from Teams. // Agent is from Teams.
await this.min.conversationalService['sendOnConversation']( await this.min.conversationalService['sendOnConversation'](
this.min, this.min,
@ -584,7 +582,7 @@ export class WhatsappDirectLine extends GBService {
const prompt = `the person said: ${text}. what can I tell her?`; const prompt = `the person said: ${text}. what can I tell her?`;
const answer = await ChatServices.continue(this.min, prompt, 0); const answer = await ChatServices.continue(this.min, prompt, 0);
text = `${text} \n\nGeneral Bots: ${answer}` text = `${text} \n\nGeneral Bots: ${answer}`;
if (user.agentSystemId.indexOf('@') !== -1) { if (user.agentSystemId.indexOf('@') !== -1) {
// Agent is from Teams or Google Chat. // Agent is from Teams or Google Chat.
@ -627,11 +625,9 @@ export class WhatsappDirectLine extends GBService {
} }
private async endTransfer(id: string, locale: string, user: GuaribasUser, agent: GuaribasUser, sec: SecService) { private async endTransfer(id: string, locale: string, user: GuaribasUser, agent: GuaribasUser, sec: SecService) {
await this.sendToDeviceEx(id, Messages[this.locale].notify_end_transfer(this.min.instance.botId), locale, null); await this.sendToDeviceEx(id, Messages[this.locale].notify_end_transfer(this.min.instance.botId), locale, null);
if (user.agentSystemId.indexOf('@') !== -1) { if (user.agentSystemId.indexOf('@') !== -1) {
// Agent is from Teams. // Agent is from Teams.
await this.min.conversationalService['sendOnConversation']( await this.min.conversationalService['sendOnConversation'](
@ -639,9 +635,7 @@ export class WhatsappDirectLine extends GBService {
agent, agent,
Messages[this.locale].notify_end_transfer(this.min.instance.botId) Messages[this.locale].notify_end_transfer(this.min.instance.botId)
); );
} else { } else {
await this.sendToDeviceEx( await this.sendToDeviceEx(
user.agentSystemId, user.agentSystemId,
Messages[this.locale].notify_end_transfer(this.min.instance.botId), Messages[this.locale].notify_end_transfer(this.min.instance.botId),
@ -677,7 +671,7 @@ export class WhatsappDirectLine extends GBService {
} }
}); });
} catch (e) { } catch (e) {
GBLog .error(e); GBLog.error(e);
} }
} }
@ -696,7 +690,8 @@ export class WhatsappDirectLine extends GBService {
await this.printMessages(response.obj.activities, conversationId, from, fromName); await this.printMessages(response.obj.activities, conversationId, from, fromName);
} catch (err) { } catch (err) {
GBLog.error( GBLog.error(
`Error calling printMessages on Whatsapp channel ${err.data === undefined ? err : err.data} ${err.errObj ? err.errObj.message : '' `Error calling printMessages on Whatsapp channel ${err.data === undefined ? err : err.data} ${
err.errObj ? err.errObj.message : ''
}` }`
); );
} }
@ -730,15 +725,13 @@ export class WhatsappDirectLine extends GBService {
if (activity.attachments) { if (activity.attachments) {
await CollectionUtil.asyncForEach(activity.attachments, async attachment => { await CollectionUtil.asyncForEach(activity.attachments, async attachment => {
switch (attachment.contentType) { switch (attachment.contentType) {
case 'application/vnd.microsoft.card.hero': case 'application/vnd.microsoft.card.hero':
output += `\n${this.renderHeroCard(attachment)}`; output += `\n${this.renderHeroCard(attachment)}`;
break; break;
case 'image/png': case 'image/png':
await this.sendFileToDevice(to, attachment.contentUrl, await this.sendFileToDevice(to, attachment.contentUrl, attachment.name, attachment.name, 0);
attachment.name, attachment.name, 0);
return; return;
@ -982,11 +975,9 @@ export class WhatsappDirectLine extends GBService {
switch (provider) { switch (provider) {
case 'GeneralBots': case 'GeneralBots':
// Ignore E2E messages and status updates. // Ignore E2E messages and status updates.
if (req.type && req.type === 'e2e_notification' if ((req.type && req.type === 'e2e_notification') || req.isStatus) {
|| req.isStatus) {
return; return;
} }
@ -1092,12 +1083,24 @@ export class WhatsappDirectLine extends GBService {
// Detects if the welcome message is enabled. // Detects if the welcome message is enabled.
if (process.env.WHATSAPP_WELCOME_DISABLED !== 'true') { if (process.env.WHATSAPP_WELCOME_DISABLED === 'true') {
let minInstance = GBServer.globals.minInstances.filter(
p => p.instance.botId.toLowerCase() === botId.toLowerCase()
)[0];
// Just pass the message to the receiver.
await minInstance.whatsAppDirectLine.received(req, res);
return;
}
// Tries to find if user wants to switch bots. // Tries to find if user wants to switch bots.
let toSwitchMin = GBServer.globals.minInstances.filter( let toSwitchMin = GBServer.globals.minInstances.filter(
p => p.instance.botId.toLowerCase() === text.toLowerCase() p => p.instance.botId.toLowerCase() === text.toLowerCase()
)[0]; )[0];
if (!toSwitchMin) { if (!toSwitchMin) {
toSwitchMin = GBServer.globals.minInstances.filter(p => toSwitchMin = GBServer.globals.minInstances.filter(p =>
p.instance.activationCode ? p.instance.activationCode.toLowerCase() === text.toLowerCase() : false p.instance.activationCode ? p.instance.activationCode.toLowerCase() === text.toLowerCase() : false
@ -1147,6 +1150,8 @@ export class WhatsappDirectLine extends GBService {
// User wants to switch bots. // User wants to switch bots.
if (toSwitchMin !== undefined) { if (toSwitchMin !== undefined) {
GBLog.info(`Switching bots from ${botId} to ${toSwitchMin.botId}...`);
// So gets the new bot instance information and prepares to // So gets the new bot instance information and prepares to
// auto start dialog if any is specified. // auto start dialog if any is specified.
@ -1186,8 +1191,7 @@ export class WhatsappDirectLine extends GBService {
id, id,
`O outro Bot que você estava falando(${user.instanceId}), não está mais disponível. Agora você está falando comigo, ${activeMin.instance.title}...` `O outro Bot que você estava falando(${user.instanceId}), não está mais disponível. Agora você está falando comigo, ${activeMin.instance.title}...`
); );
} } else {
else {
if ((activeMin as any).whatsAppDirectLine) { if ((activeMin as any).whatsAppDirectLine) {
t = (activeMin as any).whatsAppDirectLine; t = (activeMin as any).whatsAppDirectLine;
} else { } else {
@ -1198,15 +1202,6 @@ export class WhatsappDirectLine extends GBService {
t.received(req, res); t.received(req, res);
} }
} }
} else {
let minInstance = GBServer.globals.minInstances.filter(
p => p.instance.botId.toLowerCase() === botId.toLowerCase()
)[0];
// Just pass the message to the receiver.
await minInstance.whatsAppDirectLine.received(req, res);
}
} catch (error) { } catch (error) {
GBLog.error(`Error on Whatsapp callback: ${error.data ? error.data : error} ${error.stack}`); GBLog.error(`Error on Whatsapp callback: ${error.data ? error.data : error} ${error.stack}`);
} }