fix(basic.gblib): #227 - HEAR AS FILE and GET/SET PARAM.

This commit is contained in:
rodrigorodriguez 2023-02-01 12:23:47 -03:00
parent 33a5efa17b
commit bc5c1b0ced
2 changed files with 1406 additions and 1384 deletions

View file

@ -608,6 +608,9 @@ export class DialogKeywords {
private async setOption({pid, name, value})
{
if (this.isUserSystemParam(name)){
throw new Error(`Not possible to define ${name} as it is a reserved system param name.`);
}
const process = GBServer.globals.processes[pid];
let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
const sec = new SecService();
@ -616,6 +619,17 @@ export class DialogKeywords {
return { min, user, params };
}
private async getOption({pid, name})
{
if (this.isUserSystemParam(name)){
throw new Error(`Not possible to retrieve ${name} system param.`);
}
const process = GBServer.globals.processes[pid];
let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
const sec = new SecService();
return await sec.getParam(user, name);
}
/**
* Defines the maximum lines to scan in spreedsheets.
*
@ -811,12 +825,14 @@ export class DialogKeywords {
await sleep(DEFAULT_HEAR_POLL_INTERVAL);
}
const text = min.cbMap[userId].promise;
const answer = min.cbMap[userId].promise;
if (kind === 'file') {
GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`);
// TODO: answer.filename, answer.data.
} else if (kind === 'boolean') {
if (isIntentYes('pt-BR', text)) {
if (isIntentYes('pt-BR', answer)) {
result = true;
} else {
result = false;
@ -852,7 +868,7 @@ export class DialogKeywords {
return text.match(/\d+/gi);
};
const value = extractEntity(text);
const value = extractEntity(answer);
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um número válido.' });
@ -867,7 +883,7 @@ export class DialogKeywords {
);
};
const value = extractEntity(text);
const value = extractEntity(answer);
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite uma data no formato 12/12/2020.' });
@ -880,7 +896,7 @@ export class DialogKeywords {
return text.match(/^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/gi);
};
const value = extractEntity(text);
const value = extractEntity(answer);
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um horário no formato hh:ss.' });
@ -899,7 +915,7 @@ export class DialogKeywords {
return [];
};
const value = extractEntity(text);
const value = extractEntity(answer);
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um valor monetário.' });
@ -911,7 +927,7 @@ export class DialogKeywords {
let phoneNumber;
try {
// https://github.com/GeneralBots/BotServer/issues/307
phoneNumber = phone(text, { country: 'BRA' })[0];
phoneNumber = phone(answer, { country: 'BRA' })[0];
phoneNumber = phoneUtil.parse(phoneNumber);
} catch (error) {
await this.talk({ pid, text: Messages[locale].validation_enter_valid_mobile });
@ -936,7 +952,7 @@ export class DialogKeywords {
}
};
const value = extractEntity(text);
const value = extractEntity(answer);
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um CEP válido.' });
@ -948,7 +964,7 @@ export class DialogKeywords {
const list = args;
result = null;
await CollectionUtil.asyncForEach(list, async item => {
if (GBConversationalService.kmpSearch(text, item) != -1) {
if (GBConversationalService.kmpSearch(answer, item) != -1) {
result = item;
}
});
@ -978,8 +994,8 @@ export class DialogKeywords {
await CollectionUtil.asyncForEach(list, async item => {
if (
GBConversationalService.kmpSearch(text.toLowerCase(), item.name.toLowerCase()) != -1 ||
GBConversationalService.kmpSearch(text.toLowerCase(), item.code.toLowerCase()) != -1
GBConversationalService.kmpSearch(answer.toLowerCase(), item.name.toLowerCase()) != -1 ||
GBConversationalService.kmpSearch(answer.toLowerCase(), item.code.toLowerCase()) != -1
) {
result = item.code;
}

View file

@ -34,30 +34,30 @@
* @fileoverview General Bots server core.
*/
'use strict';
import cliProgress from 'cli-progress';
import { DialogSet, TextPrompt } from 'botbuilder-dialogs';
import express from 'express';
import SwaggerClient from 'swagger-client';
import removeRoute from 'express-remove-route';
import AuthenticationContext from 'adal-node';
import wash from 'washyourmouthoutwithsoap';
import { FacebookAdapter } from 'botbuilder-adapter-facebook';
import path from 'path';
import mkdirp from 'mkdirp';
import Fs from 'fs';
import arrayBufferToBuffer from 'arraybuffer-to-buffer';
'use strict';
import cliProgress from 'cli-progress';
import { DialogSet, TextPrompt } from 'botbuilder-dialogs';
import express from 'express';
import SwaggerClient from 'swagger-client';
import removeRoute from 'express-remove-route';
import AuthenticationContext from 'adal-node';
import wash from 'washyourmouthoutwithsoap';
import { FacebookAdapter } from 'botbuilder-adapter-facebook';
import path from 'path';
import mkdirp from 'mkdirp';
import Fs from 'fs';
import arrayBufferToBuffer from 'arraybuffer-to-buffer';
import {
import {
AutoSaveStateMiddleware,
BotFrameworkAdapter,
ConversationState,
MemoryStorage,
TurnContext,
UserState
} from 'botbuilder';
import { AttachmentPrompt, ConfirmPrompt, OAuthPrompt, WaterfallDialog } from 'botbuilder-dialogs';
import {
} from 'botbuilder';
import { AttachmentPrompt, ConfirmPrompt, OAuthPrompt, WaterfallDialog } from 'botbuilder-dialogs';
import {
GBDialogStep,
GBLog,
GBMinInstance,
@ -66,32 +66,32 @@ import {
IGBCoreService,
IGBInstance,
IGBPackage
} from 'botlib';
import { CollectionUtil } from 'pragmatismo-io-framework';
import { MicrosoftAppCredentials } from 'botframework-connector';
import { GBServer } from '../../../src/app.js';
import { GBAdminService } from '../../admin.gbapp/services/GBAdminService.js';
import { GuaribasConversationMessage } from '../../analytics.gblib/models/index.js';
import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsService.js';
import { GBVMService } from '../../basic.gblib/services/GBVMService.js';
import { AskDialogArgs } from '../../kb.gbapp/dialogs/AskDialog.js';
import { KBService } from '../../kb.gbapp/services/KBService.js';
import { SecService } from '../../security.gbapp/services/SecService.js';
import { WhatsappDirectLine } from '../../whatsapp.gblib/services/WhatsappDirectLine.js';
import { Messages } from '../strings.js';
import { GBConfigService } from './GBConfigService.js';
import { GBConversationalService } from './GBConversationalService.js';
import { GBDeployer } from './GBDeployer.js';
import urlJoin from 'url-join';
import { GoogleChatDirectLine } from '../../google-chat.gblib/services/GoogleChatDirectLine.js';
import { SystemKeywords } from '../../basic.gblib/services/SystemKeywords.js';
import * as nlp from 'node-nlp';
import Path from 'path';
} from 'botlib';
import { CollectionUtil } from 'pragmatismo-io-framework';
import { MicrosoftAppCredentials } from 'botframework-connector';
import { GBServer } from '../../../src/app.js';
import { GBAdminService } from '../../admin.gbapp/services/GBAdminService.js';
import { GuaribasConversationMessage } from '../../analytics.gblib/models/index.js';
import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsService.js';
import { GBVMService } from '../../basic.gblib/services/GBVMService.js';
import { AskDialogArgs } from '../../kb.gbapp/dialogs/AskDialog.js';
import { KBService } from '../../kb.gbapp/services/KBService.js';
import { SecService } from '../../security.gbapp/services/SecService.js';
import { WhatsappDirectLine } from '../../whatsapp.gblib/services/WhatsappDirectLine.js';
import { Messages } from '../strings.js';
import { GBConfigService } from './GBConfigService.js';
import { GBConversationalService } from './GBConversationalService.js';
import { GBDeployer } from './GBDeployer.js';
import urlJoin from 'url-join';
import { GoogleChatDirectLine } from '../../google-chat.gblib/services/GoogleChatDirectLine.js';
import { SystemKeywords } from '../../basic.gblib/services/SystemKeywords.js';
import * as nlp from 'node-nlp';
import Path from 'path';
/**
/**
* Minimal service layer for a bot and encapsulation of BOT Framework calls.
*/
export class GBMinService {
export class GBMinService {
/**
* Default General Bots User Interface package.
*/
@ -828,7 +828,6 @@ export class GBMinService {
// Get loaded user state
const member = context.activity.from;
const step = await min.dialogs.createContext(context);
step.context.activity.locale = 'pt-BR';
let firstTime = false;
@ -1064,9 +1063,9 @@ export class GBMinService {
private static async downloadAttachmentAndWrite(attachment) {
const url = attachment.contentUrl;
// https://github.com/GeneralBots/BotServer/issues/195 - '${botId}','uploads');
// TODO: https://github.com/GeneralBots/BotServer/issues/195 - '${botId}','uploads');
const localFolder = Path.join('work');
const localFileName = Path.join(localFolder, this['botId'],'uploads', attachment.name);
const localFileName = Path.join(localFolder, `${this['min'].botId}.gbai`, 'uploads', attachment.name);
let res;
if (url.startsWith('data:')) {
@ -1128,21 +1127,29 @@ export class GBMinService {
context.activity.text = context.activity.text.trim();
const user = await min.userProfile.get(context, {});
const member = context.activity.from;
let user = await sec.ensureUser(min.instance.instanceId, member.id, member.name, '', 'web', member.name, null);
const userId = user.userId;
const params = user.params ? JSON.parse(user.params) : {};
let message: GuaribasConversationMessage;
if (process.env.PRIVACY_STORE_MESSAGES === 'true') {
// Adds message to the analytics layer.
const analytics = new AnalyticsService();
if (user) {
if (!user.conversation) {
user.conversation = await analytics.createConversation(user.systemUser);
let conversation;
if (!user.conversationId) {
conversation = await analytics.createConversation(user);
user.conversationId = conversation.Id;
}
message = await analytics.createMessage(
min.instance.instanceId,
user.conversation,
user.systemUser.userId,
user.conversationId,
userId,
context.activity.text
);
}
@ -1299,13 +1306,11 @@ export class GBMinService {
'Language Detector',
GBConfigService.getBoolean('LANGUAGE_DETECTOR')
) === 'true';
const systemUser = user.systemUser;
locale = systemUser.locale;
locale = user.locale;
if (text != '' && detectLanguage && !locale) {
locale = await min.conversationalService.getLanguage(min, text);
if (systemUser.locale != locale) {
user.systemUser = await sec.updateUserLocale(systemUser.userId, locale);
await min.userProfile.set(step.context, user);
if (user.locale != locale) {
user = await sec.updateUserLocale(user.userId, locale);
}
}
@ -1341,10 +1346,10 @@ export class GBMinService {
GBLog.info(`Text>: ${text}.`);
if (user.systemUser.agentMode === 'self') {
const manualUser = await sec.getUserFromAgentSystemId(user.systemUser.userSystemId);
if (user.agentMode === 'self') {
const manualUser = await sec.getUserFromAgentSystemId(user.userSystemId);
GBLog.info(`HUMAN AGENT (${user.systemUser.userSystemId}) TO USER ${manualUser.userSystemId}: ${text}`);
GBLog.info(`HUMAN AGENT (${user.userId}) TO USER ${manualUser.userSystemId}: ${text}`);
const cmd = 'SEND FILE ';
if (text.startsWith(cmd)) {
@ -1367,8 +1372,8 @@ export class GBMinService {
);
}
} else {
if (min.cbMap[user.systemUser.userId] && min.cbMap[user.systemUser.userId].promise == '!GBHEAR') {
min.cbMap[user.systemUser.userId].promise = text;
if (min.cbMap[userId] && min.cbMap[userId].promise == '!GBHEAR') {
min.cbMap[userId].promise = text;
}
// If there is a dialog in course, continue to the next step.
@ -1406,4 +1411,5 @@ export class GBMinService {
}
}
}
}
}