@slavmak2486/bx24ts
Version:
Library for bitrix24
519 lines (518 loc) • 19 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.baseBX24 = void 0;
const axios_1 = __importDefault(require("axios"));
const callResult_1 = require("../callResult");
const lodash_1 = require("lodash");
class baseBX24 {
constructor() {
this.cbArray = [];
this.AUTH_CONNECTOR = "";
this.CLIENT_ID = "";
this.CLIENT_SECRET = "";
this.isInit = false;
this.APP_SID = false;
this.PATH = "/rest";
this.LANG = "";
this.AUTH_ID = "";
this.REFRESH_ID = "";
this.MEMBER_ID = "";
this.PLACEMENT = "";
this.IS_ADMIN = false;
this.AUTH_EXPIRES = 0;
this.url = '';
this.timeoutCall = 0;
this.arrEvents = [];
this.logger = console;
this.isReadyVal = false;
this.userOption = {
get: (name) => {
return this.USER_OPTIONS[name];
},
set: (name, value, cb) => {
this.USER_OPTIONS[name] = value;
this.sendMessage('setUserOption', { name: name, value: value }, cb);
}
};
this.appOption = {
get: (name) => {
return this.APP_OPTIONS[name];
},
set: (name, value, cb) => {
if (this.isAdmin()) {
this.APP_OPTIONS[name] = value;
this.sendMessage('setAppOption', { name: name, value: value }, cb);
}
else {
console.error('Access denied!');
}
}
};
this.selectAccess = (title, value, cb) => {
if (typeof (value) === 'function') {
cb = value;
value = [];
}
this.sendMessage('selectAccess', { value, title }, cb);
};
this.selectUser = (title, cb) => {
if (typeof (title) === 'function') {
cb = title;
title = '';
}
this.sendMessage('selectUser', { title: title, mult: false }, cb);
};
this.selectUsers = (title, cb) => {
if (typeof (title) !== 'string') {
cb = title;
title = '';
}
this.sendMessage('selectUser', { title: title, mult: true }, cb);
};
this.selectCRM = (params, cb) => {
this.sendMessage('selectCRM', {
entityType: params.entityType,
multiple: params.multiple,
value: params.value,
}, cb);
};
this.placement = {
info: () => ({
placement: this.PLACEMENT,
options: this.PLACEMENT_OPTIONS
}),
getInterface: (cb) => {
this.sendMessage('getInterface', {}, cb);
},
call: (cmd, params, cb) => {
this.sendMessage(cmd, params, cb);
},
bindEvent: (eventName, cb) => {
this.sendMessage('placementBindEvent', { event: eventName }, cb);
}
};
this.DOMAIN = "";
this.PROTOCOL = 1;
}
getHttpString(value, prefix = '') {
if (value instanceof Date) {
return prefix + '=' + encodeURIComponent(value.toISOString());
}
else if (typeof value == 'object') {
const resultObj = [];
for (const field in value) {
resultObj.push(this.getHttpString(value[field], prefix + `${prefix != '' ? '[' : ""}${field}${prefix != '' ? ']' : ''}`));
}
return resultObj.join('&');
}
else if (prefix != '') {
return encodeURIComponent(prefix) + '=' + encodeURIComponent(value);
}
return encodeURIComponent(value);
}
setTimeoutCall(ms) {
this.timeoutCall = ms;
}
clearTimeoutCall() {
this.timeoutCall = 0;
}
isFunction(item) {
return item === null ? false : (typeof (item) == "function" || item instanceof Function);
}
addEvent(event, handler) {
this.arrEvents.push({
event: event,
handler: handler
});
}
emitEvent(event, params) {
const arrHandler = this.arrEvents.filter(el => { return el.event == event; });
for (const idx in arrHandler) {
setTimeout(() => {
arrHandler[idx].handler.call(this, params);
}, 10);
}
}
uniqid() {
const charsList = '0123456789abcdefghijklmnopqrstuvwxyz';
let s = '';
for (let i = 0; i < 32; i++)
s += charsList[Math.round(Math.random() * (charsList.length - 1))];
return s;
}
setCallback(cb) {
const cbId = this.uniqid();
if (cb) {
this.cbArray.push({ uid: cbId, cb: cb });
}
return cbId;
}
doInit() {
this.emitEvent('init', this);
}
utilReady() {
if (document.readyState === "complete") {
return this.runReady();
}
let __readyHandler;
if (document.addEventListener) {
__readyHandler = () => {
document.removeEventListener("DOMContentLoaded", __readyHandler, false);
this.runReady();
};
document.addEventListener("DOMContentLoaded", __readyHandler, false);
window.addEventListener("load", () => { this.runReady(); }, false);
}
else if (document.attachEvent) {
__readyHandler = () => {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", __readyHandler);
this.runReady();
}
};
document.attachEvent("onreadystatechange", __readyHandler);
window.attachEvent("onload", () => { this.runReady(); });
}
this.utilReady = () => null;
return null;
}
runReady() {
if (!this.isReadyVal) {
if (!document.body) {
setTimeout(this.runReady, 15);
return;
}
this.isReadyVal = true;
this.ready = (handler) => {
if (typeof handler == 'function') {
setTimeout(handler, 10);
}
};
this.emitEvent('ready');
}
return;
}
callSuccess(xhr) {
return typeof xhr.status == 'undefined' || (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status >= 400 && xhr.status < 500 || xhr.status === 1223 || xhr.status === 0;
}
call(url, config) {
return new Promise((resolve, reject) => {
const params = (0, lodash_1.cloneDeep)(config.data);
params.auth = this.AUTH_ID;
if (this.AUTH_CONNECTOR && !params.auth_connector) {
params.auth_connector = this.AUTH_CONNECTOR;
}
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: this.getHttpString(params),
url: url
};
if (this.timeoutCall) {
options.timeout = this.timeoutCall;
}
(0, axios_1.default)(options).then(res => {
const data = res.data;
const result = new callResult_1.CallResult(data, config, this, res.status);
resolve(result);
})
.catch((err) => {
var _a;
if (!((_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data)) {
reject(err);
}
else if ((0, lodash_1.get)(err, ['response', 'data', 'error'], undefined) == 'expired_token' && !url.includes('oauth.bitrix.info/oauth/token/')) {
try {
this.refreshAuth(() => {
this.call(url, config).then(resolve).catch(reject);
});
}
catch (error) {
reject(error);
}
}
else {
reject((0, lodash_1.get)(err, ['response', 'data'], err.message));
}
});
});
}
getAuth() {
return (this.isInit && this.AUTH_EXPIRES > (new Date()).valueOf())
? { access_token: this.AUTH_ID, refresh_token: this.REFRESH_ID, expires_in: this.AUTH_EXPIRES, domain: this.DOMAIN, member_id: this.MEMBER_ID }
: false;
}
callBatch(cmd, cb, haltOnError = false) {
const startCb = cb;
const startHaltOnError = haltOnError;
if (typeof cb == 'boolean') {
haltOnError = cb;
cb = undefined;
}
else {
cb = cb;
}
const comands = {};
let cnt = 0;
for (const idx in cmd) {
const row = cmd[idx];
const method = Array.isArray(row) ? row[0] : row.method;
const params = Array.isArray(row) ? row[1] : row.params;
if (method) {
cnt++;
comands[idx] = `${method}?${this.getHttpString(params)}`;
}
}
if (cnt > 0) {
const url = this.url ? `${this.url}batch.json` : `http${this.PROTOCOL ? 's' : ''}://${this.DOMAIN}${this.PATH}/batch.json`;
const params = {
cmd: comands,
halt: haltOnError ? 1 : 0
};
if (!startCb) {
if (this.AUTH_EXPIRES < (new Date()).valueOf()) {
return new Promise((resolve, reject) => {
this.refreshAuthAsync().then(() => {
this.callBatch(cmd, startHaltOnError).then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
})
.catch((error) => {
reject(error);
});
});
}
else {
return new Promise((resolve, reject) => {
this.call(url, {
method: 'batch',
data: params,
}).then(res => {
resolve(this.formatResultForBatch(res, cmd));
})
.catch(reject);
});
}
}
else if (typeof startCb == 'function') {
if (this.AUTH_EXPIRES < (new Date()).valueOf()) {
this.refreshAuthAsync().then(() => {
this.callBatch(cmd, startCb, startHaltOnError);
})
.catch(error => {
console.error(error);
});
}
else {
this.call(url, {
method: 'batch',
data: params,
callback: startCb
}).then(res => {
if (typeof cb == 'function')
cb(this.formatResultForBatch(res, cmd, cb));
})
.catch(err => {
if (err instanceof Error) {
throw err;
}
const result = this.formatResultForBatch(new callResult_1.CallResult(err, {
method: 'batch',
data: params
}, this, 500), cmd, cb);
if (typeof cb === 'function')
cb(result);
return false;
});
}
}
}
else {
return;
}
}
formatResultForBatch(res, calls, callback) {
var _a, _b, _c, _d;
const data = res.data();
const result = {};
for (const idx in calls) {
const cmd = calls[idx];
if (((_a = data === null || data === void 0 ? void 0 : data.result) === null || _a === void 0 ? void 0 : _a[idx]) !== undefined || ((_b = data === null || data === void 0 ? void 0 : data.result_error) === null || _b === void 0 ? void 0 : _b[idx]) !== undefined) {
result[idx] = new callResult_1.CallResult({
result: ((_c = data.result) === null || _c === void 0 ? void 0 : _c[idx]) || {},
error: data.result_error[idx] || undefined,
total: data.result_total[idx],
time: data.result_time[idx],
next: data.result_next[idx]
}, {
method: Array.isArray(cmd) ? cmd[0] : cmd === null || cmd === void 0 ? void 0 : cmd.method,
data: Array.isArray(cmd) ? cmd[1] : cmd === null || cmd === void 0 ? void 0 : cmd.params,
callback: callback
}, this, res.status);
}
else {
result[idx] = {
data: () => ({}),
total: () => 0,
error_description: () => JSON.stringify(res),
answer: (_d = data === null || data === void 0 ? void 0 : data.result) === null || _d === void 0 ? void 0 : _d[idx],
query: {
method: Array.isArray(cmd) ? cmd[0] : cmd === null || cmd === void 0 ? void 0 : cmd.method,
data: Array.isArray(cmd) ? cmd[1] : cmd === null || cmd === void 0 ? void 0 : cmd.params,
callback: callback
},
next: () => false,
bx24: this,
time: () => ({}),
status: res.status,
more: () => false,
error: () => JSON.stringify(res)
};
}
}
return result;
}
callMethod(method, params, cb) {
const url = this.url ? `${this.url}${method}.json` : `http${this.PROTOCOL ? 's' : ''}://${this.DOMAIN}${this.PATH}/${method}.json`;
if (!cb) {
if (this.AUTH_EXPIRES < (new Date()).valueOf()) {
return new Promise((resolve, reject) => {
try {
this.refreshAuth(() => {
var _a;
(_a = this.callMethod(method, params)) === null || _a === void 0 ? void 0 : _a.then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
}
catch (error) {
reject(error);
}
});
}
else {
return new Promise((resolve) => {
this.call(url, {
method,
data: params
}).then(res => {
resolve(res);
})
.catch(err => {
resolve(new callResult_1.CallResult(err, {
data: params,
method,
callback: cb
}, this, 500));
});
});
}
}
else {
if (this.AUTH_EXPIRES < (new Date()).valueOf()) {
this.refreshAuth(() => {
this.callMethod(method, params, cb);
});
}
else {
this.call(url, {
method,
data: params,
callback: cb
}).then(res => {
return cb(res);
})
.catch(err => {
cb(new callResult_1.CallResult({ error_description: String(err) }, {
data: params,
method,
callback: cb
}, this, 500));
});
}
}
}
isAdmin() {
return this.IS_ADMIN;
}
getLang() {
return this.LANG;
}
getDomain() {
return this.DOMAIN;
}
isReady() {
return this.isReadyVal;
}
ready(handler) {
this.addEvent('ready', handler);
}
getScrollSize() {
return {
scrollWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth),
scrollHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight)
};
}
init(callback) {
if (callback) {
this.addEvent('init', callback);
}
}
install(callback) {
if (callback) {
this.addEvent('install', callback);
}
}
callBind(event, handler, auth_type, callback) {
if (!this.isInit) {
this.init(() => {
this.callBind(event, handler, auth_type, callback);
});
}
else if (this.isAdmin()) {
const params = {
event: event || '',
handler: handler || '',
auth_type: (typeof auth_type == 'undefined') ? 0 : auth_type
};
return this.callMethod('event.bind', params, callback);
}
return false;
}
installFinish() {
this.sendMessage('setInstallFinish', {});
}
resizeWindow(width, height, cb) {
if (width > 0 && height > 0) {
this.sendMessage('resizeWindow', { width: width, height: height }, cb);
}
}
fitWindow(cb) {
this.sendMessage('resizeWindow', {
width: '100%', height: this.getScrollSize().scrollHeight
}, cb);
}
closeApplication(cb) {
this.sendMessage('closeApplication', {}, cb);
}
reloadWindow(cb) {
this.sendMessage('reloadWindow', {}, cb);
}
setTitle(title, cb) {
this.sendMessage('setTitle', { title: title }, cb);
}
scrollParentWindow(scroll, cb) {
if (scroll > 0) {
this.sendMessage('setScroll', { scroll: scroll }, cb);
}
}
}
exports.baseBX24 = baseBX24;