• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { warn } from '../../log/Log';
17import { BurialPointRequestBody, GeneralRecordRequest, pluginUsage } from './SpStatisticsHttpBean';
18
19export class SpStatisticsHttpUtil {
20  static requestServerInfo: string = '';
21  static serverTime: number = 0;
22  static timeDiff: number = 0;
23  static retryCount: number = 0;
24  static retryMaxCount: number = 5;
25  static retryRestTimeOut: boolean = false;
26  static recordPlugin: Array<string> = [];
27  static controllersMap: Map<number, AbortController> = new Map<number, AbortController>();
28  static isInterrupt: boolean = false;
29
30  static initStatisticsServerConfig(): void {
31    if (SpStatisticsHttpUtil.requestServerInfo === '') {
32      return;
33    }
34    if (SpStatisticsHttpUtil.serverTime === 0) {
35      SpStatisticsHttpUtil.getServerTime();
36    }
37  }
38
39
40  static getServerTime(): void {
41    if (SpStatisticsHttpUtil.requestServerInfo === '') {
42      return;
43    }
44    fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/serverTime`)
45      .then((resp) => {
46        resp.text().then((it) => {
47          if (it && it.length > 0) {
48            SpStatisticsHttpUtil.serverTime = Number(it);
49            SpStatisticsHttpUtil.timeDiff = SpStatisticsHttpUtil.serverTime - Date.now();
50          }
51        });
52      })
53      .catch((e) => {});
54  }
55
56
57  static addUserVisitAction(requestUrl: string): void {
58    // @ts-ignore
59    if (window.useWb) {
60      return;
61    }
62    if (SpStatisticsHttpUtil.requestServerInfo === '') {
63      return;
64    }
65    let visitId = 0;
66    fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/${requestUrl}`, {
67      method: 'post',
68      headers: {
69        'Content-Type': 'application/json',
70      },
71    })
72      .then((resp) => {
73        resp.text().then((it) => {
74          let res = JSON.parse(it);
75          if (res && res.data) {
76            visitId = res.data.accessId;
77          }
78        });
79      })
80      .catch((err) => { });
81    setTimeout(() => {
82      fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/${requestUrl}`, {
83        method: 'post',
84        headers: {
85          'Content-Type': 'application/json',
86        },
87        body: JSON.stringify({
88          effectiveAccess: true,
89          visitId: visitId,
90        }),
91      })
92        .catch((err) => { })
93        .then((resp) => { });
94    }, 1800000);
95  }
96
97  static addOrdinaryVisitAction(requestBody: BurialPointRequestBody): void {
98    // @ts-ignore
99    if (window.useWb) {
100      return;
101    }
102    if (SpStatisticsHttpUtil.requestServerInfo === '') {
103      return;
104    }
105    requestBody.ts = SpStatisticsHttpUtil.getCorrectRequestTime();
106    if (SpStatisticsHttpUtil.serverTime === 0) {
107      return;
108    }
109    fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/record`, {
110      method: 'post',
111      headers: {
112        'Content-Type': 'application/json',
113      },
114      body: JSON.stringify(requestBody),
115    })
116      .catch((err) => {
117      })
118      .then((resp) => { });
119  }
120
121  // ai问答
122  static generalRecord(category: string, secondCat: string, thirdCat: Array<string>): void {
123    let requestBody: GeneralRecordRequest = {
124      ts: SpStatisticsHttpUtil.getCorrectRequestTime(),
125      category,
126      secondCat,
127      thirdCat
128    };
129    fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/generalRecord`, {
130      method: 'post',
131      headers: {
132        'Content-Type': 'application/json'
133      },
134      body: JSON.stringify(requestBody)
135    }).then(
136      res => { }
137    ).catch(err => {
138    });
139  }
140
141  static recordPluginUsage(): void {
142    fetch(`https://${SpStatisticsHttpUtil.requestServerInfo}/recordPluginUsage`, {
143      method: 'post',
144      headers: {
145        'Content-Type': 'application/json'
146      },
147      body: JSON.stringify({
148        eventData: {
149          plugin: SpStatisticsHttpUtil.recordPlugin
150        }
151      })
152    }).then(res => {
153    }).catch(err => {
154    });
155    SpStatisticsHttpUtil.recordPlugin = [];
156  }
157
158  static getNotice(): Promise<Response> {
159    return fetch(`https://${window.location.host}${window.location.pathname}messagePublish`);
160  }
161
162  static getCorrectRequestTime(): number {
163    if (SpStatisticsHttpUtil.serverTime === 0) {
164      SpStatisticsHttpUtil.getServerTime();
165    }
166    return Date.now() + SpStatisticsHttpUtil.timeDiff;
167  }
168
169  // ai对话接口--获取token
170  static async getAItoken(params:string): Promise<AiResponse> {
171    let controller = new AbortController();
172    let response: AiResponse = {
173      status: 0,
174      data: ''
175    };
176    setTimeout(() => {
177      controller.abort();
178    }, 60000);
179    let res = await window.fetch(`https://${window.location.host}/${params}`, {
180      method: 'post',
181      signal: controller.signal,
182      headers: {
183        'Content-Type': 'application/json'
184      }
185    }).then(async res => {
186      response.status = res.status;
187      if (res.status === 200) {
188        let resp = await res.text();
189        let resj = await JSON.parse(resp);
190        response.data = resj.token;
191      }
192    }).catch(err => {
193      response.status = 700;
194    });
195    return response;
196  }
197
198  // ai对话接口--问答
199  // @ts-ignore
200  static askAi(requestBody, params: string): Promise<AiResponse> {
201    return new Promise((resolve, reject) => {
202      let controller = new AbortController();
203      let date = Date.now();
204      if (!SpStatisticsHttpUtil.controllersMap.has(date)) {
205        SpStatisticsHttpUtil.controllersMap.set(date, controller);
206      }
207      let response: AiResponse = {
208        status: 0,
209        data: '',
210        time: date,
211      };
212      setTimeout(() => {
213        controller.abort();
214      }, 60000);
215      window.fetch(`https://${window.location.host}/${params}`, {
216        method: 'post',
217        signal: controller.signal,
218        headers: {
219          'Content-Type': 'application/json',
220          'Authorization': 'Bearer app-6mUvoj5WO5hRaMVLBzV0oCVl'
221        },
222        body: JSON.stringify(requestBody)
223      }).then(async res => {
224        response.status = res.status;
225        if (res.status === 200) {
226          let resp = await res.text();
227          let resj = await JSON.parse(resp);
228          response.data = resj.event && resj.event === 'message' ? resj.answer : '服务器异常,请稍后再试';
229        }
230        else {
231          response.data = '服务器请求失败';
232        }
233        resolve(response);
234      }).catch((err) => {
235        if (err.toString().indexOf('AbortError') > -1) {
236          response.data = '请求超时,已中断!';
237          response.status = 504;
238        } else {
239          response.data = '请求错误';
240        }
241        reject(response);
242      });
243    });
244  }
245}
246
247export class AiResponse {
248  status: number = 0;
249  data: string = '';
250  time?: number = 0;
251}
252