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 Logger from '../utils/Logger'; 17import Constant from '../utils/Constant'; 18import NetworkModel from '../model/NetworkModel'; 19import R from '../appsampled/data/R'; 20import App from '@system.app'; 21 22const TAG: string = '[ChatController]'; 23 24export default class ChatController { 25 private networkModel: NetworkModel = new NetworkModel(); 26 27 /** 28 * 发送消息 29 * @param username 30 * @param msg 31 * @returns 32 */ 33 public async sendMessage(username: string, msg: string): Promise<R> { 34 Logger.info(TAG, `sendMessage username->${username},msg->${msg}`); 35 let extraData = { 36 msgType: 'system', 37 receiver: username, 38 templateCode: 'sampled', 39 templateName: 'appsampled', 40 testData: `{ \"content\": \"${msg}\" }` 41 }; 42 Logger.info(TAG, `sendMessage extraData->${JSON.stringify(extraData)}`); 43 let responseData: ESObject = AppStorage.get("userInfo"); 44 let response = await this.networkModel.request(Constant.ACTION_SEND_MESSAGE, http.RequestMethod.POST, extraData, responseData.token); 45 // 拿到响应中服务端返回的数据 46 Logger.info(TAG, `sendMessage response.result->${JSON.stringify(response.result)}`); 47 let data = response.result.toString(); 48 // 将其转成Json数据 49 let jsonData = JSON.parse(data); 50 Logger.info(TAG, `sendMessage jsonData->${JSON.stringify(jsonData)}`); 51 // 统一的返回类型 52 let result = new R(); 53 result.setSuccess(jsonData.success); 54 result.setCode(jsonData.code); 55 result.setMessage(jsonData.message); 56 Logger.info(TAG, `sendMessage result->${JSON.stringify(result)}`); 57 return result; 58 } 59 60 61 /** 62 * 接收消息 63 * @param id 64 * @param callback 65 */ 66 public onMessage(id: string, callback) { 67 Logger.info(TAG, `onMessage begin id:${id}`); 68 let data: ESObject = AppStorage.get("userInfo"); 69 this.networkModel.onMessage(id, data?.token, (value) => { 70 Logger.info(TAG, `onMessage value: ${value}`); 71 let result = JSON.parse(value); 72 Logger.info(TAG, `onMessage result: ${result}`); 73 Logger.info(TAG, `onMessage msgTxt: ${result.msgTxt}`); 74 if (result.msgTxt) { 75 let message = JSON.parse(result.msgTxt); 76 Logger.info(TAG, `onMessage content: ${message.content}`); 77 callback(message.content) 78 } 79 }); 80 Logger.info(TAG, 'onMessage end'); 81 } 82}