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