shared.js 10.6 KB
const fs = require("fs");
const url = require("url");
const axios = require("axios");
const moment = require("moment");
const strings = require("string");
const dataset = require("./dataset");
const sys = require('child_process');
const { exec } = require('child_process');

const cct_api = 'http://cct.r-broker.ru/api/';
const cct_key = 'y8Bzq1C0vIwhcrl98emy04JauUlWd7glhvUo2TcWBSkdMYzrKS'
              + 'KhQNMuoU_NecQJVNLIgRA4eeDTX4QFDA6np1VI0ctrmYJkcIQK'
              + 'muMgCjKzqHVSzZ2-n_0vefeFZPCMZJz4NO8xgrPwQ1OWgn_ACt'
              + 'be9DWhSR-yi_-u2k2NcF3Heg193PSKvov9QPlShLtq_UzdQfmb'
              + 'C9uS1-bukZFdFyQ9M6mO8Qnlyzm95ouQPODwqieKjiXIFkXUIW';

const file_sender = '../../htdocs/uploadgd/up.php';

const api_hook_url = 'https://ai.r-broker.ru/api/api.php';
const api_hook_key = 'kd56h4jfhj54f62hjf6d8YgjL9';
const api_hook = api_hook_url + '?key=' + api_hook_key;

const mobile_codes = dataset.mobile_codes();

function empty (value) {
  if (value === undefined) return true;
  if (value === null) return true;
  const str = strings(value);
  if (str == "") return true;
  if (str.trim() == "") return true;
  return false;
}

async function cct_api_service (service, api_request) {
  let post_data = JSON.stringify(api_request);
  let headers = {
    "Language": "ru-RU",
    "Authorization": "Bearer " + cct_key,
    "Content-Type": "application/json; charset=utf-8"
  };
  let config = { headers: headers };
  let result = await axios.post(cct_api + service, post_data, config);
  let wrong_data = { status: 'error', result: 'axios crashed' };
  if (result.data === null) return wrong_data
  if (result.data === undefined) return wrong_data;
  return result.data;
}

module.exports = exports = {

  empty (value) {
    return empty (value);
  },

  async ai_api_hook (action, web_hook_data) {
    let api_hook_action = api_hook + '&action=' + action;
    let post_data = new url.URLSearchParams(web_hook_data);
    let result = {};
    let wrong_data = { status: 'error', detail: 'axios crashed' };
    try {
      result = await axios.post(api_hook_action, post_data);
    } catch (err) {
      wrong_data.detail = JSON.stringify(err, undefined, 2);
      result.data = wrong_data;
    }
    if (empty(result.data)) return wrong_data
    return result.data;
  },

  get_part_of_the_day() {
    ts = Date.now();
    let date_ob = new Date(ts);
    hours = date_ob.getHours();
    if (hours < 4) return 'night';
    if (hours < 12) return 'morning';
    if (hours < 16) return 'day';
    if (hours < 24) return 'evening';
    return 'night';
  },

  human_format(abonent_phone) {
    let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
    var size = clean_phone.length;
    var human_phone = "";
    if (size < 4) return clean_phone;
    if (size == 11) {
      prefix = clean_phone.substring(0, 1);
      if (prefix == 8) human_phone = prefix; else human_phone = "+" + prefix;
      human_phone = human_phone + " (" + clean_phone.substring(1, 4);
      human_phone = human_phone + ") " + clean_phone.substring(4, 7);
      human_phone = human_phone + "-" + clean_phone.substring(7, 9);
      human_phone = human_phone + "-" + clean_phone.substring(9, 11);
      return human_phone;
    }
    if (size == 10) {
      human_phone = "+7";
      human_phone = human_phone + " (" + clean_phone.substring(0, 3);
      human_phone = human_phone + ") " + clean_phone.substring(3, 6);
      human_phone = human_phone + "-" + clean_phone.substring(6, 8);
      human_phone = human_phone + "-" + clean_phone.substring(8, 10);
      return human_phone;
    }
    const cuts = [ 2, 2, 3, 3 ];
    const divs = [ "-", "-", ") ", "(" ];
    let phone = clean_phone;
    for (var i = 0; i < 4; i ++) {
      if (size > cuts[i]) {
        size -= cuts[i];
        part = phone.substring(size, size + cuts[i]);
        human_phone = divs[i] + part + human_phone;
        phone = phone.substring(0, size);
      } else {
        var div = "";
        if (divs[i] == "(") div = divs[i];
        return div + phone + human_phone;
      }
    }
    return "+" + phone + " " + human_phone;
  },

  last_four_digits(abonent_phone) {
    let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
    var size = clean_phone.length;
    let last_four = "";
    if (size > 3) {
      last_four = clean_phone.substring(size - 2, size);
      size -= 2;
      return clean_phone.substring(size - 2, size) + "-" + last_four;
    }
    return clean_phone;
  },

  async cct_numbers_from_text (text) {
    const service = 'markers-data';
    request = {
      debug: false,
      input: "text",
      channel: "client",
      distance: { "min": 0.166667, "mid": 0.166667, "max": 0.166667 },
      language: "russian",
      text: text,
      triggers: [
        { name: "numbers", markers: [ { type: "number" } ] }
      ]
    };

    const response = await cct_api_service(service, request);

    let result = "";
    if (response.status !== "success") return result;
    for (trigger of response.result) {
      if (trigger.state === "on") {
        if (trigger.name === "numbers") {
          for (i in trigger.details) {
            found = trigger.details[i];
            for (j in found) {
              element = found[j];
              result = result + " " + element.value;
            }
          }
        }
      }
    }
    result = result.replace( /^\s+/, '' );
    return result;
  },

  async cct_dates_from_text (text) {
    const service = 'markers-data';
    request = {
      debug: false,
      input: "text",
      channel: "client",
      distance: { "min": 0.166667, "mid": 0.166667, "max": 0.166667 },
      language: "russian",
      text: text,
      triggers: [
        { name: "dates", markers: [ { type: "date time" } ] }
      ]
    };

    const response = await cct_api_service(service, request);

    let result = "";
    if (response.status !== "success") return result;
    for (trigger of response.result) {
      if (trigger.state === "on") {
        if (trigger.name === "dates") {
          for (i in trigger.details) {
            found = trigger.details[i];
            for (j in found) {
              element = found[j];
              pattern = element.pattern??"";
              if ((pattern === "%date%") && (result === ""))
                result = element.value;
            }
          }
        }
      }
    }

    if (result === "") return result;
    moment.locale("ru");
    result = moment(result, "YYYY-MM-DD").format("DD.MM.YYYY");
    return result;
  },

  renew_last_log_file(last_text_file) {
    let sysCommand = 'cat ' + last_text_file + ' >log.txt';
    sys.exec(sysCommand, (error, stdout, stderr) => {
      if (error) {
        console.error(`error: ${error.message}`);
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`);
      }
      // console.log(`stdout:\n${stdout}`);
    });
  },

  send_to_google_disk(file_name, file_mime) {
    let proc = sys.spawnSync('php', [ file_sender, file_name, file_mime ]);

    let exit_code = proc.status;
    let look_stdout = proc.stdout.toString();

    let check_error = proc.error;
    let look_stderr = proc.stderr.toString();

    if (check_error)
      console.log("error: \n" + JSON.stringify(check_error, undefined, 2));
    if (look_stderr) console.log("stderr: \n" + look_stderr);
    if (look_stdout) console.log("stdout: \n" + look_stdout);
  },

  is_mobile_code(abonent_phone) {
    let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
    var size = clean_phone.length;
    let phone_code = "";

    if (size > 6) {
      phone_code = clean_phone.substring(1, 4);
      }
    return (mobile_codes.indexOf(phone_code)!=-1);

  },

  pid_name() {
    pidName = process.pid;
    if (pidName < 10) pidName = '0000' + pidName;
    if (pidName < 100) pidName = '000' + pidName;
    if (pidName < 1000) pidName = '00' + pidName;
    if (pidName < 10000) pidName = '0' + pidName;
    return pidName;
  },
  sendTelegram(events_owner, preset_template_id, args)
  {

    var cmd = `php /servers/constructor/htdocs/api/telegram-send.php `;
    var tmp_json = args['json'];
    var phone_number = args['phone'];
    var find = '\"';
    var re = new RegExp(find, 'g');
    tmp_json = JSON.stringify(tmp_json).replace(re, "\\\"");
    tmp_json = "\"" + tmp_json + "\"";
    cmd+= `${events_owner} ${preset_template_id} ${phone_number} empty empty empty ${tmp_json}`;
    exec(cmd);
    return true;
  },
  //функция отправки сообщений в канал
  sendTelegramChannel(events_owner, args)
  {
    var cmd = `php /servers/constructor/htdocs/api/telegram-channel-sender.php ${events_owner} ${args['phone']} ${args['channel_type']}`;
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        console.error(`error: ${error.message}`);
        return;
      }
    
      if (stderr) {
        console.error(`stderr: ${stderr}`);
        return;
      }
    
      console.log(`stdout:\n${stdout}`);
    });
    return true;
  },
  make_unique_app(app_suffix) {

    let app_suffix_file = './threads/' + app_suffix + '/app.dashaapp'
    if (fs.existsSync(app_suffix_file)) return './threads/' + app_suffix;

    let proc = sys.spawnSync('cp', [ '-rfp', './app', './threads/' + app_suffix ]);

    let exit_code = proc.status;
    let exit_data = proc.stdout.toString();

    let check_error = proc.error;
    let look_stderr = proc.stderr.toString();

    if (check_error) {
      console.log('error: ' + JSON.stringify(check_error, undefined, 2));
      return './app';
    }
    if (look_stderr) {
      console.log('stderr: ' + look_stderr);
      return './app';
    }
    app_data = fs.readFileSync('app/app.dashaapp');
    app_info = JSON.parse(app_data);
    let app_name = app_info.name + '-' + app_suffix;
    app_info.name = app_name;
    fs.writeFileSync(app_suffix_file, JSON.stringify(app_info, undefined, 2));
    return './threads/' + app_suffix;
  },

  drop_unique_app(app_suffix) {

    let proc = sys.spawnSync('rm', [ '-rf', './threads/' + app_suffix ]);

    let exit_code = proc.status;
    let exit_data = proc.stdout.toString();

    let check_error = proc.error;
    let look_stderr = proc.stderr.toString();

    if (check_error) {
      console.log('error: ' + JSON.stringify(check_error, undefined, 2));
      return false;
    }
    if (look_stderr) {
      console.log('stderr: ' + look_stderr);
      return false;
    }
    return true;
  },

  get_conversation_info(app, conv) {
    app_data = fs.readFileSync('app/app.dashaapp');
    app_info = JSON.parse(app_data);
    let app_name = app_info.name;
    app_name_full = app.applicationName;
    app_id = app.applicationId;
    job_id = conv._jobId;
    return {
      app_name: app_name,
      app_name_full: app_name_full,
      app_id: app_id,
      job_id: job_id
    };
  }

};