diff --git a/packages/basic.gblib/README.md b/packages/basic.gblib/README.md new file mode 100644 index 00000000..161ea486 --- /dev/null +++ b/packages/basic.gblib/README.md @@ -0,0 +1,7 @@ +*This is a General Bots open core package, more information can be found on the [BotServer](https://github.com/pragmatismo-io/BotServer) repository.* + +This alpha version is using a hack in form of converter to +translate BASIC to TS and string replacements to emulate await code. +See http://jsfiddle.net/roderick/dym05hsy for more info on vb2ts, so +http://stevehanov.ca/blog/index.php?id=92 should be used to run it without +translation and enhance classic BASIC experience. diff --git a/packages/basic.gblib/index.ts b/packages/basic.gblib/index.ts new file mode 100644 index 00000000..fcfb3c4e --- /dev/null +++ b/packages/basic.gblib/index.ts @@ -0,0 +1,72 @@ +/*****************************************************************************\ +| ( )_ _ | +| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ | +| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' v `\ /'_`\ | +| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) ) | +| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' | +| | | ( )_) | | +| (_) \___/' | +| | +| General Bots Copyright (c) Pragmatismo.io. All rights reserved. | +| Licensed under the AGPL-3.0. | +| | +| According to our dual licensing model, this program can be used either | +| under the terms of the GNU Affero General Public License, version 3, | +| or under a proprietary license. | +| | +| The texts of the GNU Affero General Public License with an additional | +| permission and of our proprietary license can be found at and | +| in the LICENSE file you have received along with this program. | +| | +| This program is distributed in the hope that it will be useful, | +| but WITHOUT ANY WARRANTY, without even the implied warranty of | +| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +| GNU Affero General Public License for more details. | +| | +| "General Bots" is a registered trademark of Pragmatismo.io. | +| The licensing of the program under the AGPLv3 does not imply a | +| trademark license. Therefore any rights, title and interest in | +| our trademarks remain entirely with us. | +| | +\*****************************************************************************/ + +/** + * @fileoverview General Bots server core. + */ + +'use strict'; + +import { GBDialogStep, GBLog, GBMinInstance, IGBCoreService, IGBPackage } from 'botlib'; +import { GuaribasSchedule } from 'packages/core.gbapp/models/GBModel'; +import { Sequelize } from 'sequelize-typescript'; + + +/** + * Package for core.gbapp. + */ +export class GBBasicPackage implements IGBPackage { + public sysPackages: IGBPackage[]; + public CurrentEngineName = "guaribas-1.0.0"; + public async loadPackage(core: IGBCoreService, sequelize: Sequelize): Promise { + core.sequelize.addModels([GuaribasSchedule]); + } + + public async getDialogs(min: GBMinInstance) { + GBLog.verbose(`getDialogs called.`); + } + public async unloadPackage(core: IGBCoreService): Promise { + GBLog.verbose(`unloadPackage called.`); + } + public async unloadBot(min: GBMinInstance): Promise { + GBLog.verbose(`unloadBot called.`); + } + public async onNewSession(min: GBMinInstance, step: GBDialogStep): Promise { + GBLog.verbose(`onNewSession called.`); + } + public async onExchangeData(min: GBMinInstance, kind: string, data: any) { + GBLog.verbose(`onExchangeData called.`); + } + public async loadBot(min: GBMinInstance): Promise { + + } +} diff --git a/packages/basic.gblib/models/Model.ts b/packages/basic.gblib/models/Model.ts new file mode 100644 index 00000000..d4944305 --- /dev/null +++ b/packages/basic.gblib/models/Model.ts @@ -0,0 +1,78 @@ +/*****************************************************************************\ +| ( )_ _ | +| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ | +| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' v `\ /'_`\ | +| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) ) | +| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' | +| | | ( )_) | | +| (_) \___/' | +| | +| General Bots Copyright (c) Pragmatismo.io. All rights reserved. | +| Licensed under the AGPL-3.0. | +| | +| According to our dual licensing model, this program can be used either | +| under the terms of the GNU Affero General Public License, version 3, | +| or under a proprietary license. | +| | +| The texts of the GNU Affero General Public License with an additional | +| permission and of our proprietary license can be found at and | +| in the LICENSE file you have received along with this program. | +| | +| This program is distributed in the hope that it will be useful, | +| but WITHOUT ANY WARRANTY, without even the implied warranty of | +| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +| GNU Affero General Public License for more details. | +| | +| "General Bots" is a registered trademark of Pragmatismo.io. | +| The licensing of the program under the AGPLv3 does not imply a | +| trademark license. Therefore any rights, title and interest in | +| our trademarks remain entirely with us. | +| | +\*****************************************************************************/ + +/** + * @fileoverview General Bots server core. + */ + +'use strict'; + +import { + AutoIncrement, + BelongsTo, + Column, + CreatedAt, + DataType, + ForeignKey, + Model, + PrimaryKey, + Table, + UpdatedAt +} from 'sequelize-typescript'; + +import { GuaribasInstance } from '../../core.gbapp/models/GBModel'; + +@Table +//tslint:disable-next-line:max-classes-per-file +export class GuaribasSchedule extends Model { + + @Column + public name: string; + + @Column + public schedule: string; + + @ForeignKey(() => GuaribasInstance) + @Column + public instanceId: number; + + @BelongsTo(() => GuaribasInstance) + public instance: GuaribasInstance; + + @Column + @CreatedAt + public createdAt: Date; + + @Column + @UpdatedAt + public updatedAt: Date; +} diff --git a/packages/basic.gblib/services/DialogKeywords.ts b/packages/basic.gblib/services/DialogKeywords.ts new file mode 100644 index 00000000..32972d8b --- /dev/null +++ b/packages/basic.gblib/services/DialogKeywords.ts @@ -0,0 +1,182 @@ +/*****************************************************************************\ +| ( )_ _ | +| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ | +| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' v `\ /'_`\ | +| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) ) | +| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' | +| | | ( )_) | | +| (_) \___/' | +| | +| General Bots Copyright (c) Pragmatismo.io. All rights reserved. | +| Licensed under the AGPL-3.0. | +| | +| According to our dual licensing model, this program can be used either | +| under the terms of the GNU Affero General Public License, version 3, | +| or under a proprietary license. | +| | +| The texts of the GNU Affero General Public License with an additional | +| permission and of our proprietary license can be found at and | +| in the LICENSE file you have received along with this program. | +| | +| This program is distributed in the hope that it will be useful, | +| but WITHOUT ANY WARRANTY, without even the implied warranty of | +| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +| GNU Affero General Public License for more details. | +| | +| "General Bots" is a registered trademark of Pragmatismo.io. | +| The licensing of the program under the AGPLv3 does not imply a | +| trademark license. Therefore any rights, title and interest in | +| our trademarks remain entirely with us. | +| | +\*****************************************************************************/ + +'use strict'; + +import { TurnContext, BotAdapter } from 'botbuilder'; +import { WaterfallStepContext, WaterfallDialog } from 'botbuilder-dialogs'; +import { GBLog, GBMinInstance } from 'botlib'; +import urlJoin = require('url-join'); +import { GBDeployer } from '../../core.gbapp/services/GBDeployer'; +import { Messages } from '../strings'; +import { GBServer } from '../../../src/app'; +import { SecService } from '../../security.gbapp/services/SecService'; +import { SystemKeywords } from './SystemKeywords'; + +/** + * Base services of conversation to be called by BASIC. + */ +export class DialogKeywords { + public min: GBMinInstance; + public context: TurnContext; + public step: WaterfallStepContext; + public internalSys: SystemKeywords; + + constructor(min: GBMinInstance, deployer: GBDeployer) { + this.min = min; + this.internalSys = new SystemKeywords(min, deployer); + } + + public sys(): SystemKeywords { + return this.internalSys; + } + + public async getToday(step) { + var d = new Date(), + month = '' + (d.getMonth() + 1), + day = '' + d.getDate(), + year = d.getFullYear(); + + if (month.length < 2) month = '0' + month; + if (day.length < 2) day = '0' + day; + + const locale = step.context.activity.locale; + switch (locale) { + case 'pt-BR': + return [day, month, year].join('/'); + + case 'en-US': + return [month, day, year].join('/'); + + default: + return [year, month, day].join('/'); + } + } + + public async isAffirmative(text) { + return text.toLowerCase().match(Messages['pt-BR'].affirmative_sentences); // TODO: Dynamitize. + } + + public async exit(step) { + await step.endDialog(); + } + + public async getNow() { + const nowUTC = new Date(); + const now = new Date((typeof nowUTC === "string" ? + new Date(nowUTC) : + nowUTC).toLocaleString("en-US", { timeZone: process.env.DEFAULT_TIMEZONE })); + + return now.getHours() + ':' + now.getMinutes(); + } + + public async sendFileTo(mobile, filename, caption) { + return await this.internalSendFile(null, mobile, filename, caption); + } + + public async sendFile(step, filename, caption) { + return await this.internalSendFile(step, null, filename, caption); + } + + private async internalSendFile(step, mobile, filename, caption) { + if (filename.indexOf('.md') > -1) { + GBLog.info(`BASIC: Sending the contents of ${filename} markdown to mobile.`); + let md = await this.min.kbService.getAnswerTextByMediaName(this.min.instance.instanceId, filename); + await this.min.conversationalService.sendMarkdownToMobile(this.min, step, mobile, md); + } else { + GBLog.info(`BASIC: Sending the file ${filename} to mobile.`); + let url = urlJoin( + GBServer.globals.publicAddress, + 'kb', + `${this.min.botId}.gbai`, + `${this.min.botId}.gbkb`, + 'assets', + filename + ); + + await this.min.conversationalService.sendFile(this.min, step, mobile, url, caption); + } + } + + public async setLanguage(step, language) { + const user = await this.min.userProfile.get(step.context, {}); + + let sec = new SecService(); + user.systemUser = await sec.updateUserLocale(user.systemUser.userId, language); + + await this.min.userProfile.set(step.context, user); + } + + public async from(step) { + return step.context.activity.from.id; + } + + public async userName(step) { + return step.context.activity.from.name; + } + + public async userMobile(step) { + if (isNaN(step.context.activity.from.id)) { + return 'No mobile available.'; + } else { + return step.context.activity.from.id; + } + } + + public async showMenu(step) { + return await step.beginDialog('/menu'); + } + + public async transfer(step) { + return await step.beginDialog('/t'); + } + + public async hear(step, promise, previousResolve, kind, ...args) { + function random(low, high) { + return Math.random() * (high - low) + low; + } + const idPromise = random(0, 120000000); + this.min.cbMap[idPromise] = {}; + this.min.cbMap[idPromise].promise = promise; + + const opts = { id: idPromise, previousResolve: previousResolve, kind: kind, args }; + if (previousResolve !== undefined) { + previousResolve(opts); + } else { + await step.beginDialog('/hear', opts); + } + } + + public async talk(step, text: string) { + return await this.min.conversationalService.sendText(this.min, step, text); + } +} diff --git a/packages/core.gbapp/services/GBVMService.ts b/packages/basic.gblib/services/GBVMService.ts similarity index 98% rename from packages/core.gbapp/services/GBVMService.ts rename to packages/basic.gblib/services/GBVMService.ts index 1be185f9..031aa436 100644 --- a/packages/core.gbapp/services/GBVMService.ts +++ b/packages/basic.gblib/services/GBVMService.ts @@ -35,17 +35,17 @@ import { WaterfallDialog } from 'botbuilder-dialogs'; import { GBLog, GBMinInstance, GBService, IGBCoreService, GBDialogStep } from 'botlib'; import * as fs from 'fs'; -import { GBDeployer } from './GBDeployer'; +import { GBDeployer } from '../../core.gbapp/services/GBDeployer'; import { TSCompiler } from './TSCompiler'; import { CollectionUtil } from 'pragmatismo-io-framework'; const walkPromise = require('walk-promise'); import urlJoin = require('url-join'); -import { DialogClass } from './GBAPIService'; +import { DialogKeywords } from './DialogKeywords'; import { Messages } from '../strings'; -import { GBConversationalService } from './GBConversationalService'; +import { GBConversationalService } from '../../core.gbapp/services/GBConversationalService'; //tslint:disable-next-line:no-submodule-imports const vm = require('vm'); -const vb2ts = require('../../../../vbscript-to-typescript'); +const vb2ts = require('./vbscript-to-typescript'); const beautify = require('js-beautify').js; var textract = require('textract'); const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance(); @@ -698,7 +698,7 @@ export class GBVMService extends GBService { } public static async callVM(text: string, min: GBMinInstance, step: GBDialogStep, deployer: GBDeployer) { - const sandbox: DialogClass = new DialogClass(min, deployer); + const sandbox: DialogKeywords = new DialogKeywords(min, deployer); const context = vm.createContext(sandbox); const code = min.sandBoxMap[text]; vm.runInContext(code, context); diff --git a/packages/core.gbapp/services/GBAPIService.ts b/packages/basic.gblib/services/SystemKeywords.ts similarity index 52% rename from packages/core.gbapp/services/GBAPIService.ts rename to packages/basic.gblib/services/SystemKeywords.ts index eecd0b42..26a32f1e 100644 --- a/packages/core.gbapp/services/GBAPIService.ts +++ b/packages/basic.gblib/services/SystemKeywords.ts @@ -29,20 +29,13 @@ | our trademarks remain entirely with us. | | | \*****************************************************************************/ - 'use strict'; - -import { TurnContext, BotAdapter } from 'botbuilder'; -import { WaterfallStepContext, WaterfallDialog } from 'botbuilder-dialogs'; import { GBLog, GBMinInstance } from 'botlib'; import * as request from 'request-promise-native'; import urlJoin = require('url-join'); import { GBAdminService } from '../../admin.gbapp/services/GBAdminService'; import { AzureDeployerService } from '../../azuredeployer.gbapp/services/AzureDeployerService'; -import { GBDeployer } from './GBDeployer'; -import { CollectionUtil } from 'pragmatismo-io-framework'; -import { Messages } from '../strings'; -import { GBServer } from '../../../src/app'; +import { GBDeployer } from '../../core.gbapp/services/GBDeployer'; import { SecService } from '../../security.gbapp/services/SecService'; const request = require('request-promise-native'); const MicrosoftGraph = require('@microsoft/microsoft-graph-client'); @@ -50,12 +43,15 @@ const MicrosoftGraph = require('@microsoft/microsoft-graph-client'); /** * @fileoverview General Bots server core. */ - /** * BASIC system class for extra manipulation of bot behaviour. */ -class SysClass { +export class SystemKeywords { + + + public min: GBMinInstance; + private readonly deployer: GBDeployer; constructor(min: GBMinInstance, deployer: GBDeployer) { @@ -63,6 +59,20 @@ class SysClass { this.deployer = deployer; } + private async internalGetDriveClient() { + let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); + let siteId = process.env.STORAGE_SITE_ID; + let libraryId = process.env.STORAGE_LIBRARY; + + let client = MicrosoftGraph.Client.init({ + authProvider: done => { + done(null, token); + } + }); + const baseUrl = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}`; + return [client, baseUrl]; + } + public async getFileContents(url) { const options = { url: url, @@ -71,7 +81,7 @@ class SysClass { }; const res = await request(options); - return Buffer.from(res, 'binary').toString(); + Buffer.from(res, 'binary').toString(); } @@ -115,131 +125,86 @@ class SysClass { public async set(file: string, address: string, value: any): Promise { GBLog.info(`BASIC: Defining '${address}' in '${file}' to '${value}' (SET). `); - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - let siteId = process.env.STORAGE_SITE_ID; - let libraryId = process.env.STORAGE_LIBRARY; + let [baseUrl, client] = await this.internalGetDriveClient(); - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); const botId = this.min.instance.botId; const path = `/${botId}.gbai/${botId}.gbdata`; address = address.indexOf(':') !== -1 ? address : address + ":" + address; - let res = await client - .api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:${path}:/children`) - .get(); - - let document = res.value.filter(m => { - return m.name.toLowerCase() === file.toLowerCase(); - }); - - if (!document || document.length === 0) { - throw `File '${file}' specified on save GBasic command SET not found. Check the file extension (.xlsx) and the associated .gbdata/.gbdialog.`; - } + let document = await this.internalGetDocument(client, baseUrl, path, file); let body = { values: [[]] }; body.values[0][0] = value; let sheets = await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets` - ) + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets`) .get(); await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('${sheets.value[0].name}')/range(address='${address}')` - ) + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets('${sheets.value[0].name}')/range(address='${address}')`) .patch(body); } + private async internalGetDocument(client: any, baseUrl: any, path: string, file: string) { + let res = await client + .api(`${baseUrl}/drive/root:${path}:/children`) + .get(); + + let documents = res.value.filter(m => { + return m.name.toLowerCase() === file.toLowerCase(); + }); + + if (!documents || documents.length === 0) { + throw `File '${file}' specified on GBasic command not found. Check the .gbdata or the .gbdialog associated.`; + } + + return documents[0]; + } + public async save(file: string, ...args): Promise { GBLog.info(`BASIC: Saving '${file}' (SAVE). Args: ${args.join(',')}.`); - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - - let siteId = process.env.STORAGE_SITE_ID; - let libraryId = process.env.STORAGE_LIBRARY; - - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); + let [baseUrl, client] = await this.internalGetDriveClient(); const botId = this.min.instance.botId; const path = `/${botId}.gbai/${botId}.gbdata`; - let res = await client - .api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:${path}:/children`) + let document = await this.internalGetDocument(client, baseUrl, path, file); + let sheets = await client + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets`) .get(); - let document = res.value.filter(m => { - return m.name.toLowerCase() === file.toLowerCase(); - }); - await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('Sheet1')/range(address='A2:Z2')/insert` - ) + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets('${sheets.value[0].name}')/range(address='A2:DX2')/insert`) .post({}); - if (!document || document.length === 0) { - throw `File '${file}' specified on save GBasic command SAVE not found. Check the .gbdata or the .gbdialog associated.`; - } if (args.length > 128) { throw `File '${file}' has a SAVE call with more than 128 arguments. Check the .gbdialog associated.`; } let body = { values: [[]] }; - for (let index = 0; index < 128; index++) { body.values[0][index] = args[index]; } - - let res2 = await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('Sheet1')/range(address='A2:DX2')` - ) + await client + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets('${sheets.value[0].name}')/range(address='A2:DX2')`) .patch(body); } public async get(file: string, address: string): Promise { - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); - let siteId = process.env.STORAGE_SITE_ID; - let libraryId = process.env.STORAGE_LIBRARY; + let [baseUrl, client] = await this.internalGetDriveClient(); const botId = this.min.instance.botId; const path = `/${botId}.gbai/${botId}.gbdata`; - let res = await client - .api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:${path}:/children`) - .get(); - - // Performs validation. - - let document = res.value.filter(m => { - return m.name.toLowerCase() === file.toLowerCase(); - }); - - if (!document || document.length === 0) { - throw `File '${file}' specified on save GBasic command GET not found. Check the .gbdata or the .gbdialog associated.`; - } + let document = await this.internalGetDocument(client, baseUrl, path, file); // Creates workbook session that will be discarded. + let sheets = await client + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets`) + .get(); let results = await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('Sheet1')/range(address='${address}')` - ) + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets('${sheets.value[0].name}')/range(address='${address}')`) .get(); let val = results.text[0][0]; @@ -249,44 +214,26 @@ class SysClass { public async find(file: string, ...args): Promise { - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); - let siteId = process.env.STORAGE_SITE_ID; - let libraryId = process.env.STORAGE_LIBRARY; + let [baseUrl, client] = await this.internalGetDriveClient(); const botId = this.min.instance.botId; const path = `/${botId}.gbai/${botId}.gbdata`; - let res = await client - .api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:${path}:/children`) - .get(); + let document = await this.internalGetDocument(client, baseUrl, path, file); - // Performs validation. - - let document = res.value.filter(m => { - return m.name.toLowerCase() === file.toLowerCase(); - }); - - if (!document || document.length === 0) { - throw `File '${file}' specified on save GBasic command FIND not found. Check the .gbdata or the .gbdialog associated.`; - } if (args.length > 1) { throw `File '${file}' has a FIND call with more than 1 arguments. Check the .gbdialog associated.`; } // Creates workbook session that will be discarded. - const filter = args[0].split('='); const columnName = filter[0]; const value = filter[1]; + let sheets = await client + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets`) + .get(); + let results = await client - .api( - `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('Sheet1')/range(address='A1:Z100')` - ) + .api(`${baseUrl}/drive/items/${document.id}/workbook/worksheets('${sheets.value[0].name}')/range(address='A1:Z100')`) .get(); let columnIndex = 0; @@ -299,13 +246,11 @@ class SysClass { // As BASIC uses arrays starting with 1 (one) as index, // a ghost element is added at 0 (zero) position. - let array = []; array.push({ 'this is a base 1': 'array' }); let foundIndex = 0; for (; foundIndex < results.text.length; foundIndex++) { // Filter results action. - if (results.text[foundIndex][columnIndex].toLowerCase() === value.toLowerCase()) { let output = {}; const row = results.text[foundIndex]; @@ -330,37 +275,31 @@ class SysClass { } /** - * + * * folder = CREATE FOLDER "notes\01" - * - * + * + * * @param name Folder name containing tree separated by slash. - * - * + * + * */ public async createFolder(name: string) { - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - let siteId = process.env.STORAGE_SITE_ID; - let libraryId = process.env.STORAGE_LIBRARY; + let [baseUrl, client] = await this.internalGetDriveClient(); const botId = this.min.instance.botId; const path = urlJoin(`/${botId}.gbai/${botId}.gbdata`, name); return new Promise((resolve, reject) => { - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); const body = { "name": name, "folder": {}, "@microsoft.graph.conflictBehavior": "rename" - } - client.api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:/${path}:/children`) + }; + client + .api(`${baseUrl}/drive/root:/${path}:/children`) .post(body, (err, res) => { if (err) { - reject(err) + reject(err); } else { resolve(res); @@ -370,25 +309,19 @@ class SysClass { } /** - * + * * folder = CREATE FOLDER "notes\10" * SHARE FOLDER folder, "nome@domain.com", "E-mail message" - * + * */ public async shareFolder(folderReference, email: string, message: string) { - let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); + let [, client] = await this.internalGetDriveClient(); const driveId = folderReference.parentReference.driveId; const itemId = folderReference.id; return new Promise((resolve, reject) => { - let client = MicrosoftGraph.Client.init({ - authProvider: done => { - done(null, token); - } - }); - const body = - { + const body = { "recipients": [ { "email": email @@ -400,10 +333,11 @@ class SysClass { "roles": ["write"] }; - client.api(`https://graph.microsoft.com/v1.0/drives/${driveId}/items/${itemId}/invite`) + client + .api(`https://graph.microsoft.com/v1.0/drives/${driveId}/items/${itemId}/invite`) .post(body, (err, res) => { if (err) { - reject(err) + reject(err); } else { resolve(res); @@ -412,58 +346,36 @@ class SysClass { }); } - public async copyFile(src, dst) { + public async copyFile() { + let [] = await this.internalGetDriveClient(); - // let token = await this.min.adminService.acquireElevatedToken(this.min.instance.instanceId); - // let siteId = process.env.STORAGE_SITE_ID; - // let libraryId = process.env.STORAGE_LIBRARY; // const botId = this.min.instance.botId; // const path = urlJoin(`/${botId}.gbai/${botId}.gbdata`, name); - - // let client = MicrosoftGraph.Client.init({ - // authProvider: done => { - // done(null, token); - // } - // }); - // const body = // { // "parentReference": { driveId: gbaiDest.parentReference.driveId, id: gbaiDest.id }, // "name": `${botName}.${kind}` // } - // const packageName = `${templateName.split('.')[0]}.${kind}`; - // try { - // const src = await client.api( - // `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:/${source}`) + // const src = await client.api( // `${baseUrl}/drive/root:/${source}`) // .get(); - - // return await client.api( - // `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${src.id}/copy`) + // return await client.api( // `${baseUrl}/drive/items/${src.id}/copy`) // .post(body); - // } catch (error) { - // if (error.code === "itemNotFound") { - // } else if (error.code === "nameAlreadyExists") { - - // let src = await client.api( - // `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:/${templateName}/${packageName}:/children`) + // let src = await client.api( // `${baseUrl}/drive/root:/${templateName}/${packageName}:/children`) // .get(); // const dstName = `${botName}.gbai/${botName}.${kind}`; - // let dst = await client.api(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:/${dstName}`) + // let dst = await client.api(`${baseUrl}/drive/root:/${dstName}`) // .get(); - // await CollectionUtil.asyncForEach(src.value, async item => { - // const body = // { // "parentReference": { driveId: dst.parentReference.driveId, id: dst.id } // } - // await client.api( - // `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${templateId}/drive/items/${item.id}/copy`) + // await client.api( // `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${templateId}/drive/items/${item.id}/copy`) // .post(body); // }); // } @@ -512,7 +424,7 @@ class SysClass { /** * Generic function to call any REST API. */ - public async httpGet(url: string) { + public async getByHttp(url: string) { const options = { uri: url }; @@ -525,7 +437,7 @@ class SysClass { /** * Generic function to call any REST API by POST. */ - public async httpPost(url: string, data) { + public async postByHttp(url: string, data) { const options = { uri: url, json: true, @@ -541,174 +453,3 @@ class SysClass { return text.replace(/\D/gi, ''); } } - -/** - * Base services of conversation to be called by BASIC. - */ -export class DialogClass { - public min: GBMinInstance; - public context: TurnContext; - public step: WaterfallStepContext; - public internalSys: SysClass; - - constructor(min: GBMinInstance, deployer: GBDeployer) { - this.min = min; - this.internalSys = new SysClass(min, deployer); - } - - public static setup(bot: BotAdapter, min: GBMinInstance) { - min.dialogs.add( - new WaterfallDialog('/gbasic-email', [ - async step => { - const locale = step.context.activity.locale; - if ((step.options as any).ask) { - await min.conversationalService.sendText(min, step, Messages[locale].whats_email); - } - return await step.prompt('textPrompt', {}); - }, - async step => { - const locale = step.context.activity.locale; - - const extractEntity = text => { - return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/gi); - }; - - const value = extractEntity(step.result); - - if (value === null) { - await min.conversationalService.sendText(min, step, Messages[locale].validation_enter_valid_email); - return await step.replaceDialog('/gbasic-email', { ask: true }); - } else { - return await step.endDialog(value[0]); - } - } - ]) - ); - } - - public sys(): SysClass { - return this.internalSys; - } - - public async getToday(step) { - var d = new Date(), - month = '' + (d.getMonth() + 1), - day = '' + d.getDate(), - year = d.getFullYear(); - - if (month.length < 2) month = '0' + month; - if (day.length < 2) day = '0' + day; - - const locale = step.context.activity.locale; - switch (locale) { - case 'pt-BR': - return [day, month, year].join('/'); - - case 'en-US': - return [month, day, year].join('/'); - - default: - return [year, month, day].join('/'); - } - } - - public async isAffirmative(step, text) { - return text.toLowerCase().match(Messages['pt-BR'].affirmative_sentences); // TODO: Dynamitize. - } - - public async exit(step) { - await step.endDialog(); - } - - public async getNow(step) { - const nowUTC = new Date(); - const now = new Date((typeof nowUTC === "string" ? - new Date(nowUTC) : - nowUTC).toLocaleString("en-US", { timeZone: process.env.DEFAULT_TIMEZONE })); - - return now.getHours() + ':' + now.getMinutes(); - } - - public async sendFileTo(step, mobile, filename, caption) { - return await this.internalSendFile(null, mobile, filename, caption); - } - - public async sendFile(step, filename, caption) { - return await this.internalSendFile(step, null, filename, caption); - } - - private async internalSendFile(step, mobile, filename, caption) { - if (filename.indexOf('.md') > -1) { - GBLog.info(`BASIC: Sending the contents of ${filename} markdown to mobile.`); - let md = await this.min.kbService.getAnswerTextByMediaName(this.min.instance.instanceId, filename); - await this.min.conversationalService.sendMarkdownToMobile(this.min, step, mobile, md); - } else { - GBLog.info(`BASIC: Sending the file ${filename} to mobile.`); - let url = urlJoin( - GBServer.globals.publicAddress, - 'kb', - `${this.min.botId}.gbai`, - `${this.min.botId}.gbkb`, - 'assets', - filename - ); - - await this.min.conversationalService.sendFile(this.min, step, mobile, url, caption); - } - } - - public async setLanguage(step, language) - { - const locale = step.context.activity.locale; - const user = await this.min.userProfile.get(step.context, {}); - - let sec = new SecService(); - user.systemUser = await sec.updateUserLocale(user.systemUser.userId, language); - - await this.min.userProfile.set(step.context, user); - } - - public async getFrom(step) { - return step.context.activity.from.id; - } - - public async getUserName(step) { - return step.context.activity.from.name; - } - - public async getUserMobile(step) { - if (isNaN(step.context.activity.from.id)) { - return 'No mobile available.'; - } else { - return step.context.activity.from.id; - } - } - - public async showMenu(step) { - return await step.beginDialog('/menu'); - } - - public async transfer(step) { - return await step.beginDialog('/t'); - } - - public async hear(step, promise, previousResolve, kind, ...args) { - function random(low, high) { - return Math.random() * (high - low) + low; - } - const idPromise = random(0, 120000000); - this.min.cbMap[idPromise] = {}; - this.min.cbMap[idPromise].promise = promise; - - const opts = { id: idPromise, previousResolve: previousResolve, kind: kind, args }; - if (previousResolve !== undefined) { - previousResolve(opts); - } else { - await step.beginDialog('/hear', opts); - } - } - - public async talk(step, text: string) { - return await this.min.conversationalService.sendText(this.min, step, text); - } -} diff --git a/packages/core.gbapp/services/TSCompiler.ts b/packages/basic.gblib/services/TSCompiler.ts similarity index 100% rename from packages/core.gbapp/services/TSCompiler.ts rename to packages/basic.gblib/services/TSCompiler.ts diff --git a/vbscript-to-typescript.js b/packages/basic.gblib/services/vbscript-to-typescript.js similarity index 100% rename from vbscript-to-typescript.js rename to packages/basic.gblib/services/vbscript-to-typescript.js diff --git a/packages/basic.gblib/strings.ts b/packages/basic.gblib/strings.ts new file mode 100644 index 00000000..4bada273 --- /dev/null +++ b/packages/basic.gblib/strings.ts @@ -0,0 +1,34 @@ + +export const Messages = { + global_quit: /^(sair|sai|chega|exit|quit|finish|end|ausfahrt|verlassen)/i, + 'en-US': { + show_video: 'I will show you a video, please wait...', + good_morning: 'good morning', + good_evening: 'good evening', + good_night: 'good night', + hi: (msg) => `Hello, ${msg}.`, + very_sorry_about_error: `I'm sorry to inform that there was an error which was recorded to be solved.`, + canceled: 'Canceled. If I can be useful, let me know how', + whats_email: "What's your E-mail address?", + which_language: "Please, type the language name you would like to talk through.", + validation_enter_valid_email: "Please enter a valid e-mail." , + language_chosen: "Very good, so let's go..." , + affirmative_sentences: /^(sim|s|positivo|afirmativo|claro|evidente|sem dúvida|confirmo|confirmar|confirmado|uhum|si|y|yes|sure)/i, + + }, + 'pt-BR': { + show_video: 'Vou te mostrar um vídeo. Por favor, aguarde...', + good_morning: 'bom dia', + good_evening: 'boa tarde', + good_night: 'boa noite', + hi: (msg) => `Oi, ${msg}.`, + very_sorry_about_error: `Lamento, ocorreu um erro que já foi registrado para ser tratado.`, + canceled: 'Cancelado, avise como posso ser útil novamente.', + whats_email: "Qual seu e-mail?", + which_language: "Por favor, digite o idioma que você gostaria de usar para conversarmos.", + validation_enter_valid_email: "Por favor digite um email válido.", + language_chosen: "Muito bem, então vamos lá..." , + affirmative_sentences: /^(sim|s|positivo|afirmativo|claro|evidente|sem dúvida|confirmo|confirmar|confirmado|uhum|si|y|yes|sure)/i, + + } +}; diff --git a/packages/core.gbapp/README.md b/packages/core.gbapp/README.md index ed767e85..118e0608 100644 --- a/packages/core.gbapp/README.md +++ b/packages/core.gbapp/README.md @@ -1 +1 @@ -*This is a General Bots open core package, more information can be found on the [BotServer](https://github.com/pragmatismo-io/BotServer) repository.* +*This is a General Bots BASIC ackage, more information can be found on the [BotServer](https://github.com/GeneralBots/BotServer) repository.* diff --git a/packages/core.gbapp/index.ts b/packages/core.gbapp/index.ts index 93221f95..d66df032 100644 --- a/packages/core.gbapp/index.ts +++ b/packages/core.gbapp/index.ts @@ -44,7 +44,6 @@ import { SwitchBotDialog } from './dialogs/SwitchBot'; import { WelcomeDialog } from './dialogs/WelcomeDialog'; import { WhoAmIDialog } from './dialogs/WhoAmIDialog'; import { GuaribasChannel, GuaribasException, GuaribasInstance, GuaribasPackage } from './models/GBModel'; -import { DialogClass } from './services/GBAPIService'; /** * Package for core.gbapp. @@ -77,7 +76,6 @@ export class GBCorePackage implements IGBPackage { WelcomeDialog.setup(min.bot, min); WhoAmIDialog.setup(min.bot, min); SwitchBotDialog.setup(min.bot, min); - DialogClass.setup(min.bot, min); BroadcastDialog.setup(min.bot, min); LanguageDialog.setup(min.bot, min); } diff --git a/packages/core.gbapp/services/GBCoreService.ts b/packages/core.gbapp/services/GBCoreService.ts index b398bc64..65d4e72e 100644 --- a/packages/core.gbapp/services/GBCoreService.ts +++ b/packages/core.gbapp/services/GBCoreService.ts @@ -55,7 +55,8 @@ import { GBConfigService } from './GBConfigService'; import { GBAzureDeployerPackage } from '../../azuredeployer.gbapp'; import { GBSharePointPackage } from '../../sharepoint.gblib'; import { CollectionUtil } from 'pragmatismo-io-framework'; -import { GBVMService } from './GBVMService'; +import { GBVMService } from '../../basic.gblib/services/GBVMService'; +import { GBBasicPackage } from '../../basic.gblib'; const opn = require('opn'); const cron = require('node-cron'); @@ -166,6 +167,8 @@ export class GBCoreService implements IGBCoreService { this.sequelize = new Sequelize(database, username, password, sequelizeOptions); + // Specifies custom setup for MSFT... + if (this.dialect === 'mssql') { this.queryGenerator = this.sequelize.getQueryInterface().QueryGenerator; // tslint:disable:no-unsafe-any @@ -199,7 +202,7 @@ export class GBCoreService implements IGBCoreService { } /** - * Syncronize structure between model and tables in storage. + * Syncronizes structure between model and tables in storage. */ public async syncDatabaseStructure() { if (GBConfigService.get('STORAGE_SYNC') === 'true') { @@ -454,7 +457,8 @@ STORAGE_SYNC=true GBAnalyticsPackage, GBWhatsappPackage, GBAzureDeployerPackage, - GBSharePointPackage + GBSharePointPackage, + GBBasicPackage ], async e => { GBLog.info(`Loading sys package: ${e.name}...`); diff --git a/packages/core.gbapp/services/GBDeployer.ts b/packages/core.gbapp/services/GBDeployer.ts index f50b8109..22177b37 100644 --- a/packages/core.gbapp/services/GBDeployer.ts +++ b/packages/core.gbapp/services/GBDeployer.ts @@ -53,7 +53,7 @@ import { AzureDeployerService } from './../../azuredeployer.gbapp/services/Azure import { KBService } from './../../kb.gbapp/services/KBService'; import { GBConfigService } from './GBConfigService'; import { GBImporter } from './GBImporterService'; -import { GBVMService } from './GBVMService'; +import { GBVMService } from '../../basic.gblib/services/GBVMService'; import { CollectionUtil } from 'pragmatismo-io-framework'; const MicrosoftGraph = require('@microsoft/microsoft-graph-client'); diff --git a/packages/core.gbapp/services/GBMinService.ts b/packages/core.gbapp/services/GBMinService.ts index 62ea8c71..3efa3656 100644 --- a/packages/core.gbapp/services/GBMinService.ts +++ b/packages/core.gbapp/services/GBMinService.ts @@ -76,7 +76,7 @@ import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsServic import { WhatsappDirectLine } from '../../whatsapp.gblib/services/WhatsappDirectLine'; import fs = require('fs'); import { GuaribasConversationMessage } from '../../analytics.gblib/models'; -import { GBVMService } from './GBVMService'; +import { GBVMService } from '../../basic.gblib/services/GBVMService'; import { GBAdminService } from '../../admin.gbapp/services/GBAdminService'; import { GBConversationalService } from './GBConversationalService'; diff --git a/packages/core.gbapp/strings.ts b/packages/core.gbapp/strings.ts index 4bada273..05415fc5 100644 --- a/packages/core.gbapp/strings.ts +++ b/packages/core.gbapp/strings.ts @@ -2,33 +2,9 @@ export const Messages = { global_quit: /^(sair|sai|chega|exit|quit|finish|end|ausfahrt|verlassen)/i, 'en-US': { - show_video: 'I will show you a video, please wait...', - good_morning: 'good morning', - good_evening: 'good evening', - good_night: 'good night', - hi: (msg) => `Hello, ${msg}.`, - very_sorry_about_error: `I'm sorry to inform that there was an error which was recorded to be solved.`, - canceled: 'Canceled. If I can be useful, let me know how', - whats_email: "What's your E-mail address?", - which_language: "Please, type the language name you would like to talk through.", - validation_enter_valid_email: "Please enter a valid e-mail." , - language_chosen: "Very good, so let's go..." , - affirmative_sentences: /^(sim|s|positivo|afirmativo|claro|evidente|sem dúvida|confirmo|confirmar|confirmado|uhum|si|y|yes|sure)/i, }, 'pt-BR': { - show_video: 'Vou te mostrar um vídeo. Por favor, aguarde...', - good_morning: 'bom dia', - good_evening: 'boa tarde', - good_night: 'boa noite', - hi: (msg) => `Oi, ${msg}.`, - very_sorry_about_error: `Lamento, ocorreu um erro que já foi registrado para ser tratado.`, - canceled: 'Cancelado, avise como posso ser útil novamente.', - whats_email: "Qual seu e-mail?", - which_language: "Por favor, digite o idioma que você gostaria de usar para conversarmos.", - validation_enter_valid_email: "Por favor digite um email válido.", - language_chosen: "Muito bem, então vamos lá..." , - affirmative_sentences: /^(sim|s|positivo|afirmativo|claro|evidente|sem dúvida|confirmo|confirmar|confirmado|uhum|si|y|yes|sure)/i, - + } }; diff --git a/packages/kb.gbapp/dialogs/AskDialog.ts b/packages/kb.gbapp/dialogs/AskDialog.ts index 3275894e..c091a7d2 100644 --- a/packages/kb.gbapp/dialogs/AskDialog.ts +++ b/packages/kb.gbapp/dialogs/AskDialog.ts @@ -45,7 +45,7 @@ import { KBService } from './../services/KBService'; import { GuaribasAnswer } from '../models'; import { SecService } from '../../security.gbapp/services/SecService'; import { CollectionUtil, AzureText } from 'pragmatismo-io-framework'; -import { GBVMService } from '../../core.gbapp/services/GBVMService'; +import { GBVMService } from '../../basic.gblib/services/GBVMService'; import { GBImporter } from '../../core.gbapp/services/GBImporterService'; import { GBDeployer } from '../../core.gbapp/services/GBDeployer';