1/*
2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development 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 */
15import http from '@ohos.net.http';
16import request from '@ohos.request';
17import webSocket from '@ohos.net.webSocket';
18import Logger from '../utils/Logger';
19import Constant from '../utils/Constant';
20
21const TAG: string = '[NetworkModel]';
22
23export default class NetworkModel {
24  private httpRequest: http.HttpRequest = http.createHttp();
25  private mWebSocket: webSocket.WebSocket = webSocket.createWebSocket();
26
27  public async request(action: string, method: http.RequestMethod, extraData: Object, token?: string): Promise<http.HttpResponse> {
28    Logger.info(TAG, `request action->${JSON.stringify(action)}, method->${JSON.stringify(method)}, extraData->${JSON.stringify(extraData)},token->${JSON.stringify(token)}`)
29    let header = {
30      'Content-Type': 'application/json',
31      'X-Access-Token': token
32    }
33    let response = await this.httpRequest.request(
34      Constant.URL + action,
35      {
36        method: method,
37        header: header,
38        extraData: extraData,
39        expectDataType: http.HttpDataType.STRING,
40        usingCache: true,
41        priority: 1,
42        connectTimeout: 60000,
43        readTimeout: 60000,
44        usingProtocol: http.HttpProtocol.HTTP1_1,
45        usingProxy: false,
46      });
47    Logger.info(TAG, `request response->${JSON.stringify(response)}`)
48    return response;
49
50  }
51
52  public uploadFile(action: string, fileName: string, callback): void {
53    Logger.info(TAG, `upload file create action = ${action}, fileName = ${fileName}`)
54    Logger.info(TAG, `upload url = ${Constant.URL + action}`)
55    let uploadTask: request.UploadTask;
56    let data: ESObject = AppStorage.get("userInfo");
57    let uploadConfig = {
58      url: Constant.URL + action,
59      header: {
60        'X-Access-Token': data?.token, 'Content-Type': 'multipart/form-data'
61      },
62      method: "POST",
63      files: [{
64        filename: fileName, name: "file", uri: `internal://cache/${fileName}`, type: "mp4"
65      }],
66      data: [{
67        name: 'biz', value: Constant.UPLOAD_URL
68      }],
69    };
70    Logger.info(TAG, 'upload uploadConfig,' + JSON.stringify(uploadConfig))
71    try {
72      Logger.info(TAG, 'upload start')
73      request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => {
74        uploadTask = data;
75        Logger.info(TAG, 'upload end 1')
76        uploadTask.on('complete', (taskState: Array<request.TaskState>) => {
77          Logger.info(TAG, 'upload complete ' + JSON.stringify(taskState))
78          callback(true)
79        });
80        Logger.info(TAG, 'upload end 2')
81      }).catch((err) => {
82        Logger.error(TAG, `Failed to request the upload. ${err}`);
83      });
84    } catch (err) {
85      Logger.error(TAG, `Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
86    }
87  }
88
89  public async onMessage(id: string, token: string, callback): Promise<void> {
90    Logger.info(TAG, `onMessage on connect begin: URL= ${Constant.ACTION_ON_MESSAGE_URL + id}`);
91
92    // 连接websocket
93    this.mWebSocket.connect(Constant.ACTION_ON_MESSAGE_URL + id, (err, value) => {
94      if (!err) {
95        Logger.info(TAG, 'onMessage Connected successfully');
96
97        // 连接成功订阅消息
98        this.mWebSocket.on('message', (err, value) => {
99          Logger.info(TAG, `onMessage on message, message:${value}`);
100          if (!err) {
101            Logger.info(TAG, 'onMessage receive successfully');
102            callback(value);
103          } else {
104            Logger.info(TAG, `onMessage receive failed. Err: ${JSON.stringify(err)}`);
105          }
106        });
107
108        // 连接成功订阅错误信息,出现错误则关闭webSocket
109        this.mWebSocket.on('error', (err) => {
110          Logger.info(TAG, `onMessage on error, error: ${JSON.stringify(err)}`);
111          this.mWebSocket.close((err, value) => {
112            if (!err) {
113              Logger.info(TAG, 'onMessage Connection closed successfully');
114            } else {
115              Logger.info(TAG, `onMessage Failed to close the connection. Err: ${JSON.stringify(err)}`);
116            }
117          });
118        });
119
120      } else {
121        Logger.info(TAG, `onMessage Connection failed. Err: ${JSON.stringify(err)}`);
122      }
123    });
124
125    Logger.info(TAG, `onMessage on connect end`);
126
127  }
128}