/*****************************************************************************\
|                                               ( )_  _                       |
|    _ _    _ __   _ _    __    ___ ___     _ _ | ,_)(_)  ___   ___     _     |
|   ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| |  | |/',__)/' 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';
Object.defineProperty(exports, "__esModule", { value: true });
exports.GBAdminService = void 0;
const adal_node_1 = require("adal-node");
const urlJoin = require("url-join");
const AzureDeployerService_1 = require("../../azuredeployer.gbapp/services/AzureDeployerService");
const GBModel_1 = require("../../core.gbapp/models/GBModel");
const GBConfigService_1 = require("../../core.gbapp/services/GBConfigService");
const GBDeployer_1 = require("../../core.gbapp/services/GBDeployer");
const GBImporterService_1 = require("../../core.gbapp/services/GBImporterService");
const SharePointService_1 = require("../../sharepoint.gblib/services/SharePointService");
const AdminModel_1 = require("../models/AdminModel");
const Path = require('path');
const msRestAzure = require('ms-rest-azure');
const PasswordGenerator = require('strict-password-generator').default;
const crypto = require("crypto");
/**
 * Services for server administration.
 */
class GBAdminService {
    constructor(core) {
        this.core = core;
    }
    static generateUuid() {
        return msRestAzure.generateUuid();
    }
    static getNodeVersion() {
        const packageJson = urlJoin(process.cwd(), 'package.json');
        // tslint:disable-next-line: non-literal-require
        const pjson = require(packageJson);
        return pjson.engines.node.replace('=', '');
    }
    static async getADALTokenFromUsername(username, password) {
        const credentials = await GBAdminService.getADALCredentialsFromUsername(username, password);
        return credentials.tokenCache._entries[0].accessToken;
    }
    static async getADALCredentialsFromUsername(username, password) {
        return await msRestAzure.loginWithUsernamePassword(username, password);
    }
    static getMobileCode() {
        const passwordGenerator = new PasswordGenerator();
        const options = {
            upperCaseAlpha: false,
            lowerCaseAlpha: false,
            number: true,
            specialCharacter: false,
            minimumLength: 6,
            maximumLength: 6
        };
        return passwordGenerator.generatePassword(options);
    }
    static getRndPassword() {
        const passwordGenerator = new PasswordGenerator();
        const options = {
            upperCaseAlpha: true,
            lowerCaseAlpha: true,
            number: true,
            specialCharacter: true,
            minimumLength: 14,
            maximumLength: 14
        };
        let password = passwordGenerator.generatePassword(options);
        password = password.replace(/[\@\[\=\:\;\?\"\'\#]/gi, '1');
        return password;
    }
    static getRndReadableIdentifier() {
        const passwordGenerator = new PasswordGenerator();
        const options = {
            upperCaseAlpha: false,
            lowerCaseAlpha: true,
            number: false,
            specialCharacter: false,
            minimumLength: 14,
            maximumLength: 14
        };
        return passwordGenerator.generatePassword(options);
    }
    static getNumberIdentifier() {
        const passwordGenerator = new PasswordGenerator();
        const options = {
            upperCaseAlpha: false,
            lowerCaseAlpha: false,
            number: true,
            specialCharacter: false,
            minimumLength: 14,
            maximumLength: 14
        };
        return passwordGenerator.generatePassword(options);
    }
    /**
     * @see https://stackoverflow.com/a/52171480
     */
    static getHash(str, seed = 0) {
        let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
        for (let i = 0, ch; i < str.length; i++) {
            ch = str.charCodeAt(i);
            h1 = Math.imul(h1 ^ ch, 2654435761);
            h2 = Math.imul(h2 ^ ch, 1597334677);
        }
        h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
        h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
        return 4294967296 * (2097151 & h2) + (h1 >>> 0);
    }
    static async undeployPackageCommand(text, min) {
        const packageName = text.split(' ')[1];
        const importer = new GBImporterService_1.GBImporter(min.core);
        const deployer = new GBDeployer_1.GBDeployer(min.core, importer);
        const localFolder = Path.join('work', `${min.instance.botId}.gbai`, Path.basename(packageName));
        await deployer.undeployPackageFromLocalPath(min.instance, localFolder);
    }
    static isSharePointPath(path) {
        return path.indexOf('sharepoint.com') !== -1;
    }
    static async deployPackageCommand(min, text, deployer) {
        const packageName = text.split(' ')[1];
        if (!this.isSharePointPath(packageName)) {
            const additionalPath = GBConfigService_1.GBConfigService.get('ADDITIONAL_DEPLOY_PATH');
            if (additionalPath === undefined) {
                throw new Error('ADDITIONAL_DEPLOY_PATH is not set and deployPackage was called.');
            }
            await deployer.deployPackage(min, urlJoin(additionalPath, packageName));
        }
        else {
            const siteName = text.split(' ')[1];
            const folderName = text.split(' ')[2];
            const s = new SharePointService_1.GBSharePointService();
            const localFolder = Path.join('work', `${min.instance.botId}.gbai`, Path.basename(folderName));
            // .gbot packages are handled using storage API, so no download
            // of local resources is required.
            await deployer['downloadFolder'](min, Path.join('work', `${min.instance.botId}.gbai`), Path.basename(folderName));
            await deployer.deployPackage(min, localFolder);
        }
    }
    static async rebuildIndexPackageCommand(min, deployer) {
        await deployer.rebuildIndex(min.instance, new AzureDeployerService_1.AzureDeployerService(deployer).getKBSearchSchema(min.instance.searchIndex));
    }
    static async syncBotServerCommand(min, deployer) {
        const serverName = `${min.instance.botId}-server`;
        const service = await AzureDeployerService_1.AzureDeployerService.createInstance(deployer);
        service.syncBotServerRepository(min.instance.botId, serverName);
    }
    async setValue(instanceId, key, value) {
        const options = { where: {} };
        options.where = { key: key };
        let admin = await AdminModel_1.GuaribasAdmin.findOne(options);
        if (admin === null) {
            admin = new AdminModel_1.GuaribasAdmin();
            admin.key = key;
        }
        admin.value = value;
        admin.instanceId = instanceId;
        await admin.save();
    }
    async updateSecurityInfo(instanceId, authenticatorTenant, authenticatorAuthorityHostUrl) {
        const options = { where: {} };
        options.where = { instanceId: instanceId };
        const item = await GBModel_1.GuaribasInstance.findOne(options);
        item.authenticatorTenant = authenticatorTenant;
        item.authenticatorAuthorityHostUrl = authenticatorAuthorityHostUrl;
        return item.save();
    }
    async getValue(instanceId, key) {
        const options = { where: {} };
        options.where = { key: key, instanceId: instanceId };
        const obj = await AdminModel_1.GuaribasAdmin.findOne(options);
        return obj.value;
    }
    async acquireElevatedToken(instanceId) {
        // TODO: Use boot bot as base for authentication.
        const botId = GBConfigService_1.GBConfigService.get('BOT_ID');
        instanceId = (await this.core.loadInstanceByBotId(botId)).instanceId;
        return new Promise(async (resolve, reject) => {
            const instance = await this.core.loadInstanceById(instanceId);
            const expiresOn = new Date(await this.getValue(instanceId, 'expiresOn'));
            if (expiresOn.getTime() > new Date().getTime()) {
                const accessToken = await this.getValue(instanceId, 'accessToken');
                resolve(accessToken);
            }
            else {
                const authorizationUrl = urlJoin(instance.authenticatorAuthorityHostUrl, instance.authenticatorTenant, '/oauth2/authorize');
                const refreshToken = await this.getValue(instanceId, 'refreshToken');
                const resource = 'https://graph.microsoft.com';
                const authenticationContext = new adal_node_1.AuthenticationContext(authorizationUrl);
                authenticationContext.acquireTokenWithRefreshToken(refreshToken, instance.marketplaceId, instance.marketplacePassword, resource, async (err, res) => {
                    if (err !== null) {
                        reject(err);
                    }
                    else {
                        const token = res;
                        try {
                            await this.setValue(instanceId, 'accessToken', token.accessToken);
                            await this.setValue(instanceId, 'refreshToken', token.refreshToken);
                            await this.setValue(instanceId, 'expiresOn', token.expiresOn.toString());
                            resolve(token.accessToken);
                        }
                        catch (error) {
                            reject(err);
                        }
                    }
                });
            }
        });
    }
    async publish(min, packageName, republish) { }
}
exports.GBAdminService = GBAdminService;
GBAdminService.GB_PROMPT = 'GeneralBots: ';
GBAdminService.masterBotInstanceId = 0;
GBAdminService.StrongRegex = new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*+_-])(?=.{8,})');
//# sourceMappingURL=GBAdminService.js.map