@slavmak2486/bx24ts 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env ADDED
@@ -0,0 +1 @@
1
+ getOptions=true
package/.eslintrc.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "env": {
3
+ "browser": true,
4
+ "es2021": true,
5
+ "node": true
6
+ },
7
+ "extends": [
8
+ "eslint:recommended",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint"
18
+ ],
19
+ "rules": {
20
+ "no-undef":"off"
21
+ }
22
+ }
package/BX24.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { baseBX24 } from "./base/BX24";
2
+ import { AuthBase } from "./types/authBase";
3
+
4
+ export class BX24 extends baseBX24{
5
+ constructor(cb?:(params:any)=>void){
6
+ super();
7
+ const q = window.name.split('|');
8
+ this.DOMAIN = q[0].replace(/:(80|443)$/, '');
9
+ this.PROTOCOL = parseInt(q[1])||0;
10
+ this.APP_SID = q[2];
11
+ if (window&&window instanceof Window){
12
+ window.addEventListener("message", (event:MessageEvent)=>{
13
+ this.runCallback(event);
14
+ });
15
+
16
+ if(!this.DOMAIN||!this.LANG||!this.AUTH_ID){
17
+ this.sendMessage('getInitData', this.defaultValueFromIframe);
18
+ }
19
+ }
20
+
21
+ this.utilReady();
22
+ if (cb){
23
+ this.init(cb);
24
+ }
25
+ }
26
+
27
+
28
+ defaultValueFromIframe(data:any){
29
+ if(!this.DOMAIN)
30
+ this.DOMAIN = data.DOMAIN;
31
+ if(!this.PATH)
32
+ this.PATH = data.PATH;
33
+ if(!this.LANG)
34
+ this.LANG = data.LANG;
35
+ if(!this.PLACEMENT)
36
+ this.PLACEMENT = data.PLACEMENT;
37
+
38
+ this.PROTOCOL = data.PROTOCOL;
39
+ this.DOMAIN = this.DOMAIN.replace(/:(80|443)$/, '');
40
+
41
+ if(data.AUTH_ID){
42
+ this.AUTH_ID = data.AUTH_ID;
43
+ this.REFRESH_ID = data.REFRESH_ID;
44
+ this.AUTH_EXPIRES = (new Date()).valueOf()+data.AUTH_EXPIRES*1000;
45
+ this.IS_ADMIN = !!data.IS_ADMIN;
46
+ this.MEMBER_ID = data.MEMBER_ID||'';
47
+ }
48
+
49
+ if(!this.USER_OPTIONS)
50
+ this.USER_OPTIONS = data.USER_OPTIONS;
51
+
52
+ if(!this.APP_OPTIONS)
53
+ this.APP_OPTIONS = data.APP_OPTIONS;
54
+
55
+ if(!this.PLACEMENT_OPTIONS)
56
+ this.PLACEMENT_OPTIONS = data.PLACEMENT_OPTIONS;
57
+
58
+ this.isInit = true;
59
+
60
+ if(data.FIRST_RUN && this.arrEvents.find(el=>{return el.event=='install'})){
61
+ this.emitEvent('install');
62
+ }
63
+ else
64
+ {
65
+ this.doInit();
66
+ }
67
+ }
68
+
69
+ runCallback(e:MessageEvent){
70
+ if(e.origin != 'http'+(this.PROTOCOL?'s':'')+'://'+this.DOMAIN)
71
+ return;
72
+
73
+ if(e.data)
74
+ {
75
+ const r = e.data.split(":");
76
+ const cmd = [r[0],r.slice(1).join(":")];
77
+ let args = [];
78
+
79
+ const findedCb=this.cbArray.find(el=>{return el.uid==cmd[0]});
80
+
81
+ if(findedCb)
82
+ {
83
+ if(findedCb)
84
+ args = JSON.parse(cmd[1]);
85
+ findedCb.cb.call(this, args);
86
+ }
87
+ }
88
+ }
89
+
90
+ refreshAuth(cb?:(params: any) => void){
91
+ this.sendMessage('refreshAuth', {}, (result:any)=>{
92
+ this.AUTH_ID=result.AUTH_ID;
93
+ this.REFRESH_ID=result.REFRESH_ID;
94
+ this.AUTH_EXPIRES=(new Date()).valueOf()+result.AUTH_EXPIRES*1000;
95
+ if (cb){
96
+ cb(this.getAuth());
97
+ }
98
+ })
99
+ }
100
+
101
+ sendMessage(cmd: string, params: any, cb?: (args:any)=>void): void{
102
+ if(this.isFunction(params))
103
+ {
104
+ cb = params; params = null;
105
+ }
106
+
107
+ cmd += ':' + (params ? JSON.stringify(params) : '')
108
+ + ':' + this.setCallback(cb)
109
+ + (this.APP_SID ? (':' + this.APP_SID) : '');
110
+
111
+ parent.postMessage(cmd, 'http'+(this.PROTOCOL?'s':'')+'://' + this.DOMAIN);
112
+ }
113
+
114
+ openApplication(cb?:(params:any)=>void, settings?:any):void;
115
+ openApplication(params?:any, cb?:(params:any)=>void, settings?:any):void{
116
+ if (!params){
117
+ params={};
118
+ }
119
+
120
+ if (settings&&typeof(settings)=='object'){
121
+ for (const item in settings){
122
+ params["bx24_" + item]=settings[item];
123
+ }
124
+ }
125
+ this.sendMessage('openApplication', params, cb);
126
+ }
127
+
128
+ openPath(path:string, cb?:(params:any)=>void):void{
129
+ this.sendMessage('openPath', {path:path}, cb);
130
+ }
131
+ }
package/BX24Dev.ts ADDED
@@ -0,0 +1,128 @@
1
+ import { BX24Server } from "./BX24Server";
2
+ import { AuthBaseServe} from "./types/authBaseServe";
3
+ import qs from 'qs';
4
+ import { set as __set } from "lodash";
5
+
6
+
7
+ export class BX24Dev extends BX24Server{
8
+ constructor(param: AuthBaseServe, cb?:()=>void){
9
+ super(param, ()=>{
10
+ this.callBatch({
11
+ getAppOption:['app.option.get', {}],
12
+ getUserOption:['user.option.get', {}]
13
+ }, ress=>{
14
+ for (const idx in ress){
15
+ const res=ress[idx];
16
+ if (res.error()){
17
+ console.error(res.error());
18
+ }
19
+ else{
20
+ if (idx=='getAppOption'){
21
+ this.APP_OPTIONS=res.data();
22
+ }
23
+ else{
24
+ this.USER_OPTIONS=res.data();
25
+ }
26
+ }
27
+ }
28
+
29
+ if (cb){
30
+ cb();
31
+ }
32
+ // this.init(cb);
33
+ })
34
+ this.getPlacementOptions();
35
+ });
36
+
37
+
38
+ }
39
+
40
+ appOption={
41
+ get: (name:string)=>{
42
+ return this.APP_OPTIONS[name];
43
+ },
44
+ set:(name:string,value:any,cb:(params:any)=>void)=>{
45
+ if (this.isAdmin()){
46
+ const params:{[key:string]:any}={};
47
+ params[name]=value;
48
+ this.callMethod('app.option.set', params, res=>{
49
+ if (res.data()===true){
50
+ this.APP_OPTIONS[name] = value;
51
+ }
52
+ if (cb){
53
+ cb(res);
54
+ }
55
+ })
56
+ }
57
+ else{
58
+ console.error('Access denied!');
59
+ }
60
+ }
61
+ }
62
+
63
+ userOption={
64
+ get:(name:string)=>{
65
+ return this.USER_OPTIONS[name];
66
+ },
67
+ set:(name:string, value:any,cb:(params:any)=>void)=>{
68
+ const params:{[key:string]:any}={};
69
+ params[name]=value;
70
+ this.callMethod('user.option.set', params, res=>{
71
+ if (res.data()===true){
72
+ this.USER_OPTIONS[name] = value;
73
+ }
74
+ if (cb){
75
+ cb(res);
76
+ }
77
+ });
78
+ }
79
+ }
80
+
81
+ private getPlacementOptions(){
82
+ const result:{[key:string]:any}={};
83
+ const url=new URL(location.href) as any;
84
+ const entrity=url.searchParams.entries();
85
+ const regexp=/\[([^\]]*)]/g;
86
+ let done=false;
87
+ while(!done){
88
+ const el=entrity.next();
89
+ done=el.done===true?true:false;
90
+ if (el.value){
91
+ let tempArrPath=Array.from(el.value[0].matchAll(regexp)) as string[];
92
+ tempArrPath=tempArrPath.map(ell=>{return ell[1]});
93
+ const base=el.value[0].split('[')[0];
94
+ __set(result, [base, ...tempArrPath], el.value[1]);
95
+ }
96
+ }
97
+
98
+ if (result.placement){
99
+ this.PLACEMENT=result.placement;
100
+ delete(result.placement);
101
+ }
102
+ else{
103
+ this.PLACEMENT='DEFAULT';
104
+ }
105
+
106
+ this.PLACEMENT_OPTIONS=result;
107
+ }
108
+
109
+ openApplication(cb?:(params:any)=>void, settings?:any):void;
110
+ openApplication(params?:any, cb?:(params:any)=>void, settings?:any):void{
111
+ if (!params){
112
+ params={};
113
+ }
114
+
115
+ if (settings&&typeof(settings)=='object'){
116
+ for (const item in settings){
117
+ params["bx24_" + item]=settings[item];
118
+ }
119
+ }
120
+
121
+
122
+ window.open(`?${qs.stringify(params)}`);
123
+ }
124
+
125
+ openPath(path:string, cb?:(params:any)=>void):void{
126
+ window.open(`${this.PROTOCOL?'https:':'http'}${this.DOMAIN}${path}`);
127
+ }
128
+ }
package/BX24Server.ts ADDED
@@ -0,0 +1,161 @@
1
+ import { baseBX24 } from "./base/BX24";
2
+ import { AuthBaseServe, logger } from "./types/authBaseServe";
3
+ import {getAuth} from './types/getAuth';
4
+ import { get as __get } from "lodash";
5
+ import { CallResult } from "./callResult";
6
+ import { BitrixEvent } from "./types/bitrixEvent";
7
+
8
+
9
+ export class BX24Server extends baseBX24{
10
+
11
+ logger:logger=console;
12
+
13
+ constructor(param: AuthBaseServe, cb?:(params:any)=>void){
14
+ super();
15
+
16
+ if (param.auth_connector)
17
+ this.AUTH_CONNECTOR=param.auth_connector;
18
+
19
+ if (param.logger)
20
+ this.logger=param.logger;
21
+
22
+ this.IS_ADMIN=param.isAdmin===false?false:true;
23
+ this.init(cb);
24
+ this.DOMAIN=param.domain;
25
+ if (param.member_id){
26
+ this.MEMBER_ID=param.member_id;
27
+ }
28
+ this.AUTH_EXPIRES=param.expires_in??0;
29
+ this.REFRESH_ID=param.refresh_token;
30
+ this.PROTOCOL=1;
31
+ this.AUTH_ID=param.access_token;
32
+
33
+
34
+ this.CLIENT_ID=param.client_id;
35
+ this.CLIENT_SECRET=param.client_secret;
36
+ this.isInit=true;
37
+
38
+ if (new Date().getTime()-5*60*1000>this.AUTH_EXPIRES && !param.noUpdateRefresh){
39
+ this.refreshAuth(()=>{
40
+ this.doInit();
41
+ });
42
+ }
43
+ else{
44
+ this.doInit();
45
+ }
46
+
47
+ }
48
+
49
+ getOfflineEvents(debug=false, clear=true):Promise<CallResult>{
50
+ return new Promise((resolve)=>{
51
+ if (debug){
52
+ this.callMethod('event.offline.list', {}, ress=>{
53
+ ress.answer.result={events:this.formatEvents(ress.answer.result)};
54
+ resolve(ress);
55
+ });
56
+ }
57
+ else{
58
+ this.callMethod('event.offline.get', {clear:clear?1:0}, ress=>{
59
+ ress.answer.result.events=this.formatEvents(ress.answer.result.events);
60
+ resolve(ress);
61
+ })
62
+ }
63
+ });
64
+ }
65
+
66
+
67
+ // arrOfflineEvents [
68
+ // {
69
+ // ID: '133245',
70
+ // TIMESTAMP_X: '2022-07-17T15:23:56+03:00',
71
+ // EVENT_NAME: 'ONTASKUPDATE',
72
+ // EVENT_DATA: {
73
+ // FIELDS_BEFORE: [Object],
74
+ // FIELDS_AFTER: [Object],
75
+ // IS_ACCESSIBLE_BEFORE: 'undefined',
76
+ // IS_ACCESSIBLE_AFTER: 'undefined'
77
+ // },
78
+ // EVENT_ADDITIONAL: { user_id: '41' },
79
+ // MESSAGE_ID: '3d1c2a472b1c775f4d80a1c5918aa3c8',
80
+ // PROCESS_ID: 'yxq61pfx5ikr7xw4csc6gsox9m3i1q8p',
81
+ // ERROR: '0'
82
+ // }
83
+ // ]
84
+ formatEvents(rawEvents:any):BitrixEvent[]{
85
+ const result:BitrixEvent[]=[];
86
+ for (const idx in rawEvents){
87
+ const tempEvent:BitrixEvent={
88
+ ID:Number(rawEvents[idx].ID),
89
+ TIMESTAMP_X:new Date(rawEvents[idx].TIMESTAMP_X),
90
+ EVENT_NAME:rawEvents[idx].EVENT_NAME
91
+ }
92
+ if (rawEvents[idx].EVENT_DATA)
93
+ tempEvent.EVENT_DATA=rawEvents[idx].EVENT_DATA;
94
+
95
+ if (rawEvents[idx].EVENT_ADDITIONAL)
96
+ tempEvent.EVENT_ADDITIONAL=rawEvents[idx].EVENT_ADDITIONAL;
97
+
98
+ if (rawEvents[idx].MESSAGE_ID)
99
+ tempEvent.MESSAGE_ID=rawEvents[idx].MESSAGE_ID;
100
+
101
+ if (rawEvents[idx].PROCESS_ID)
102
+ tempEvent.PROCESS_ID=rawEvents[idx].PROCESS_ID;
103
+
104
+ if (rawEvents[idx].ERROR)
105
+ tempEvent.ERROR=Boolean(Number(rawEvents[idx].ERROR));
106
+
107
+ result.push(tempEvent);
108
+ }
109
+ return result;
110
+ }
111
+
112
+ runCallback(e:MessageEvent){
113
+ this.logger.debug('callBack not allowed!');
114
+ }
115
+
116
+ onRefresh(cb:(params:getAuth)=>void){
117
+ this.addEvent('refreshAuth', cb);
118
+ }
119
+
120
+ refreshAuth(cb?:CallableFunction){
121
+ this.refreshAuthAsync()
122
+ .then(newAuth=>{
123
+ if (cb) cb(newAuth);
124
+ })
125
+ .catch(err=>{
126
+ throw err;
127
+ });
128
+ }
129
+
130
+ refreshAuthAsync():Promise<getAuth|false> {
131
+ return new Promise((resolve, reject) => {
132
+ this.call("https://oauth.bitrix.info/oauth/token/", {
133
+ grant_type: 'refresh_token',
134
+ client_id: this.CLIENT_ID,
135
+ client_secret: this.CLIENT_SECRET,
136
+ refresh_token: this.REFRESH_ID
137
+ })
138
+ .then(data=>{
139
+ this.AUTH_ID=data.answer.access_token;
140
+ this.REFRESH_ID=data.answer.refresh_token;
141
+ this.AUTH_EXPIRES=data.answer.expires*1000;
142
+ this.emitEvent('refreshAuth', this.getAuth());
143
+ resolve(this.getAuth());
144
+ })
145
+ .catch(err=>{
146
+ reject (err);
147
+ })
148
+ });
149
+ }
150
+
151
+
152
+
153
+ sendMessage(cmd: string, params: any, cb?: CallableFunction): void {
154
+ this.logger.log('sendMessage',{
155
+ cmd:cmd,
156
+ params:params,
157
+ cb:cb
158
+ });
159
+ if (cb) cb();
160
+ }
161
+ }
package/BatchHelper.ts ADDED
@@ -0,0 +1,58 @@
1
+ import {batchCmdElement} from './types/batchElement'
2
+
3
+ export class BatchHelper{
4
+ arrBatch:batchCmdElement[];
5
+ currBatch:batchCmdElement;
6
+
7
+ constructor(){
8
+ this.arrBatch=[];
9
+ this.currBatch={};
10
+ }
11
+
12
+ addToBatch(batchElement:batchCmdElement){
13
+ if (Object.keys(batchElement).length>50){
14
+ throw new Error("batchElement more 50");
15
+ }
16
+
17
+ if (50-Object.keys(this.currBatch).length<Object.keys(batchElement).length){
18
+ this.arrBatch.push(this.currBatch);
19
+ this.currBatch={};
20
+ }
21
+
22
+ for(const keyBatch in batchElement){
23
+ this.currBatch[keyBatch]=batchElement[keyBatch];
24
+ }
25
+
26
+ return this;
27
+ }
28
+
29
+ getArrBatches(){
30
+ if (Object.keys(this.currBatch).length>0){
31
+ this.arrBatch.push(this.currBatch);
32
+ this.currBatch={};
33
+ }
34
+
35
+ return this.arrBatch;
36
+ }
37
+
38
+ /**
39
+ * @param action - метод Bitrix24
40
+ * @param requestName - имя запроса в батче
41
+ * @param countRows - количество строк списочного метода
42
+ * @param params - дополнительные параметры
43
+ */
44
+ getBatchForLength(action:string, requestName:string, countRows:number, params = {}) {
45
+ var countBatch = Math.ceil(countRows / (50 * 50))
46
+ for (var i = 0; i < countBatch; i++) {
47
+ for (var j = 0; j < 50; j++) {
48
+ if (50 * 50 * i + j * 50 >= countRows) {
49
+ break
50
+ }
51
+ const curParams = Object.assign({start:0}, params)
52
+ curParams['start'] = 50 * 50 * i + j * 50;
53
+ this.addToBatch({[requestName + j]:[action, curParams]});
54
+ }
55
+ }
56
+ }
57
+
58
+ }