diff --git a/AppScope/app.json5 b/AppScope/app.json5 index d3e032a..fa0d9e9 100644 --- a/AppScope/app.json5 +++ b/AppScope/app.json5 @@ -3,7 +3,7 @@ "bundleName": "com.ohos.mms", "vendor": "example", "versionCode": 1000000, - "versionName": "1.0.4.012", + "versionName": "1.0.4.013", "icon": "$media:smsmms", "label": "$string:app_name", "distributedNotificationEnabled": true diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 index f8f0340..e4c72a9 100644 --- a/entry/build-profile.json5 +++ b/entry/build-profile.json5 @@ -1,6 +1,11 @@ { "apiType": 'stageMode', "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/base/Worker.ts" + ] + } }, "targets": [ { diff --git a/entry/src/main/ets/Application/MyAbilityStage.ts b/entry/src/main/ets/Application/MyAbilityStage.ts index 9d79558..3d56549 100644 --- a/entry/src/main/ets/Application/MyAbilityStage.ts +++ b/entry/src/main/ets/Application/MyAbilityStage.ts @@ -1,13 +1,13 @@ -import AbilityStage from "@ohos.app.ability.UIAbility" -import notification from "@ohos.notificationManager"; -import HiLog from "../utils/HiLog"; +import AbilityStage from '@ohos.app.ability.UIAbility' +import notification from '@ohos.notificationManager'; + +import HiLog from '../utils/HiLog'; const TAG = "MyAbilityStage" export default class MyAbilityStage extends AbilityStage { onCreate() { HiLog.i(TAG, "AbilityStage onCreate"); - globalThis.AbilityStageConstant = this.context; notification.setNotificationEnable({ bundle: "com.ohos.mms" }, true, (err, data) => { diff --git a/entry/src/main/ets/MainAbility/MainAbility.ts b/entry/src/main/ets/MainAbility/MainAbility.ts index 050e104..638a168 100644 --- a/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/entry/src/main/ets/MainAbility/MainAbility.ts @@ -3,7 +3,6 @@ import Window from '@ohos.window' import HiLog from "../utils/HiLog"; import MmsPreferences from "../utils/MmsPreferences"; -import MmsDatabaseHelper from "../utils/MmsDatabaseHelper"; import WorkFactory, { WorkerType } from "../workers/WorkFactory"; import simCardService from "../service/SimCardService"; @@ -11,11 +10,9 @@ const TAG = "app"; export default class MainAbility extends Ability { onCreate(want, launchParam) { - HiLog.i(TAG, "Ability onCreate com.ohos.mms version: 1.0.0.38"); + HiLog.i(TAG, "Ability onCreate com.ohos.mms version: 1.0.0.41"); globalThis.mmsContext = this.context; globalThis.abilityWant = want; - globalThis.MmsDatabaseHelper = new MmsDatabaseHelper(); - globalThis.MmsDatabaseHelper.createTable(); globalThis.needToUpdate = true; MmsPreferences.getInstance().initPreferences(); globalThis.DataWorker = WorkFactory.getWorker(WorkerType.DataWorker); diff --git a/entry/src/main/ets/StaticSubscriber/MmsStaticSubscriber.ts b/entry/src/main/ets/StaticSubscriber/MmsStaticSubscriber.ts index da96003..9c06a0d 100644 --- a/entry/src/main/ets/StaticSubscriber/MmsStaticSubscriber.ts +++ b/entry/src/main/ets/StaticSubscriber/MmsStaticSubscriber.ts @@ -13,91 +13,86 @@ * limitations under the License. */ import commonEvent from "@ohos.commonEventManager"; -import common from "../data/commonData"; -import mmsTable from "../data/tableData"; -import telephoneUtils from "../utils/TelephoneUtil"; -import HiLog from "../utils/HiLog"; -import particleAbility from "@ohos.ability.particleAbility"; -import MmsDatabaseHelper from "../utils/MmsDatabaseHelper"; -import ohosDataAbility from "@ohos.data.dataAbility"; import telSim from "@ohos.telephony.sms"; -import ohosDataRdb from "@ohos.data.rdb"; -import commonService from "../service/CommonService"; import http from "@ohos.net.http"; -import NotificationService from "../service/NotificationService"; -import LooseObject from "../data/LooseObject" -import dataShare from "@ohos.data.dataShare"; -import dataSharePredicates from "@ohos.data.dataSharePredicates"; -import messageService from "../service/ConversationListService"; -const TAG = 'MmsStaticSubscriber' -// database instance object -var rdbStore = undefined; +import common from '../data/commonData'; +import telephoneUtils from '../utils/TelephoneUtil'; +import HiLog from '../utils/HiLog'; +import commonService from '../service/CommonService'; +import ConversationService from '../service/ConversationService'; +import NotificationService from '../service/NotificationService'; +import LooseObject from '../data/LooseObject' +import ConversationListService from '../service/ConversationListService'; +import ContactService from '../service/ContactsService'; + +const TAG: string = 'MmsStaticSubscriber' var StaticSubscriberExtensionAbility = globalThis.requireNapi('application.StaticSubscriberExtensionAbility'); export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbility { - onReceiveEvent(data) { - HiLog.i(TAG, 'onRecevieEvent, event:' ); - // Initializing the Database - this.initRdb(data) + public onReceiveEvent(data): void { + HiLog.i(TAG, 'onReceiveEvent, event:' ); + if (data.event === common.string.SUBSCRIBER_EVENT) { + this.dealSmsReceiveData(data, this.context); + } else { + this.dealMmsReceiveData(data, this.context); + } } - async dealSmsReceiveData(data) { - let netType = data.parameters.isCdma ? "3gpp2" : "3gpp"; + public async dealSmsReceiveData(data, context): Promise { + let netType: string = data.parameters.isCdma ? "3gpp2" : "3gpp"; // Synchronize wait operation let promisesAll = []; data.parameters.pdus.forEach(pdu => { let promise = telSim.createMessage(this.convertStrArray(pdu), netType); promisesAll.push(promise); }); - let result: LooseObject = {}; - let createMessagePromise = Promise.all(promisesAll) - createMessagePromise.then((shortMsgList) => { + let createMessagePromise = Promise.all(promisesAll); + createMessagePromise.then(shortMsgList => { result.code = common.int.SUCCESS; result.telephone = telephoneUtils.formatTelephone(shortMsgList[0].visibleRawAddress); - result.content = ''; + result.content = common.string.EMPTY_STR; shortMsgList.forEach(shortMessage => { result.content += shortMessage.visibleMessageBody; - }) - }).catch((err) => { - HiLog.e(TAG, "dealSmsReceiveData, err: " + JSON.stringify(err.message)); + }); + }).catch(error => { + HiLog.e(TAG, "dealSmsReceiveData, error: " + JSON.stringify(error)); result.code = common.int.FAILURE; }); await createMessagePromise; - let actionData = { - slotId: data.parameters.slotId, - telephone: result.telephone, - content: result.content, - isMms: false, - mmsSource: [] - } + let actionData: LooseObject = {}; + actionData.slotId = data.parameters.slotId; + actionData.telephone = result.telephone; + actionData.content = result.content; + actionData.isMms = false; + actionData.mmsSource = []; this.insertMessageDetailBy(actionData, res => { - this.sendNotification(result.telephone, res.initDatas[0].id, result.content); + this.sendNotification(result.telephone, res.initDatas[0].id, result.content, context); this.publishData(result.telephone, result.content); - }); + }, context); } - dealMmsReceiveData(data) { + public dealMmsReceiveData(data, context): void { let result = JSON.parse(data.data); this.saveAttachment(result.mmsSource); - let content = commonService.getMmsContent(result.mmsSource); + let content: string = commonService.getMmsContent(result.mmsSource); let actionData: LooseObject = {}; actionData.telephone = result.telephone; actionData.content = content; actionData.isMms = true; actionData.mmsSource = result.mmsSource; - actionData.slotId = data.slotId; + actionData.slotId = data.parameters.slotId; this.insertMessageDetailBy(actionData, res => { let notificationContent = this.getNotificationContent(result.mmsSource, content); - this.sendNotification(result.telephone, res.initDatas[0].id, notificationContent); + this.sendNotification(result.telephone, res.initDatas[0].id, notificationContent, context); this.publishData(result.telephone, result.content); - }); + }, context); } - saveAttachment(mmsSource) { + public saveAttachment(mmsSource): void { for (let item of mmsSource) { let baseUrl = item.msgUriPath; let httpRequest = http.createHttp(); @@ -117,24 +112,24 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit } } - getNotificationContent(mmsSource, themeContent) { - let content = common.string.EMPTY_STR; + public getNotificationContent(mmsSource, themeContent): string { + let content: string = common.string.EMPTY_STR; if (mmsSource.length === 1) { let item = mmsSource[0]; switch (item.msgType) { - // Subject + // Subject case 0: content = themeContent; break; - // Pictures + // Pictures case 1: content = "(picture)" + themeContent; break; - // Video + // Video case 2: content = "(video)" + themeContent; break; - // Audio + // Audio case 3: content = "(audio)" + themeContent; break; @@ -145,17 +140,16 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit return content; } - // Insert Received Data - insertMessageDetailBy(param, callback) { - let sendResults = []; - let sendResult = { - slotId: param.slotId, - telephone: param.telephone, - content: param.content, - sendStatus: 0 - } + public insertMessageDetailBy(param, callback, context): void { + let sendResults: Array = []; + let sendResult: LooseObject = {}; + sendResult.slotId = param.slotId; + sendResult.telephone = param.telephone; + sendResult.content = param.content; + sendResult.sendStatus = common.int.SEND_MESSAGE_SUCCESS; sendResults.push(sendResult); - let hasAttachment = commonService.judgeIsAttachment(param.mmsSource); + + let hasAttachment: boolean = commonService.judgeIsAttachment(param.mmsSource); let actionData: LooseObject = {}; actionData.slotId = param.slotId; actionData.sendResults = sendResults; @@ -165,14 +159,14 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit actionData.isMms = param.isMms; actionData.mmsSource = param.mmsSource; actionData.hasAttachment = hasAttachment; - this.insertSessionAndDetail(actionData, callback); + ConversationService.getInstance().insertSessionAndDetail(actionData, callback, context); } - convertStrArray(sourceStr) { - let wby = sourceStr; - let length = wby.length; - let isDouble = (length % 2) == 0; - let halfSize = parseInt('' + length / 2); + public convertStrArray(sourceStr): Array { + let wby: string = sourceStr; + let length: number = wby.length; + let isDouble: boolean = (length % 2) == 0; + let halfSize: number = parseInt('' + length / 2); HiLog.i(TAG, "convertStrArray, length=" + length + ", isDouble=" + isDouble); if (isDouble) { let number0xArray = new Array(halfSize); @@ -200,417 +194,7 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit } } - // Initializing the Database - async initRdb(data) { - HiLog.i(TAG, "initRdb, createRdbStore start: " ); - // Creating a Database - rdbStore = await ohosDataRdb.getRdbStore(globalThis.AbilityStageConstant, - { name: mmsTable.DB.MMSSMS.config.name }, mmsTable.DB.MMSSMS.version); - // Creating Database Tables - await rdbStore.executeSql(mmsTable.table.session, null); - - if (data.event === common.string.SUBSCRIBER_EVENT) { - this.dealSmsReceiveData(data); - } else { - // MMS message receiving - this.dealMmsReceiveData(data); - } - - } - - insertSessionAndDetail(actionData, callback) { - let sendResults = actionData.sendResults; - let isReceive = actionData.isReceive; - if (sendResults.length == 0) { - return; - } - let value = this.dealSendResults(sendResults); - - // Check whether a session list has been created. - this.querySessionByTelephone(value.telephone, res => { - HiLog.i(TAG, " insertSessionAndDetail, querySessionByTelephone code=" + res.code); - let response = res.response; - HiLog.i(TAG, " insertSessionAndDetail, querySessionByTelephone response.id=" + response.id); - if (res.code == common.int.SUCCESS && response.id <= 0) { - this.insertNoExitingSession(isReceive, value, actionData, callback); - } else { - this.insertExitingSession(response, value, actionData, callback); - } - }); - } - - insertNoExitingSession(isReceive, value, actionData, callback) { - let unreadCount = 0; - if (isReceive) { - unreadCount = 1; - } - let valueBucket = { - "telephone": value.telephone, - "content": value.content, - "contacts_num": value.contractsNum, - "sms_type": value.smsType, - "unread_count": unreadCount, - "sending_status": value.sendStatus, - "has_draft": 0, - "time": value.timestamp, - "message_count": 1, - "has_mms": actionData.isMms ? 1 : 0, - "has_attachment": actionData.hasAttachment ? 1 : 0 - } - this.insertSession(valueBucket, res => { - // Invoke the SMS database to insert SMS messages. - this.dealInsertMessageDetail(value, actionData, res.rowId, initDatas => { - let result = { - rowId: res.rowId, - initDatas: initDatas - } - callback(result); - }); - }); - } - - insertExitingSession(response, param, actionData, callback) { - let sessionId = response.id; - // Invoke the SMS database to insert SMS messages. - let threadIds = [sessionId]; - let time = new Date(); - let unreadCount = 0; - if (actionData.isReceive) { - unreadCount = response.unreadCount; - unreadCount = unreadCount + 1; - } - let messageCount = response.messageCount; - messageCount = messageCount + 1; - let valueBucket = { - "content": param.content, - "unread_count": unreadCount, - "time": time.getTime(), - "sending_status": param.sendStatus, - "message_count": messageCount, - "has_mms": actionData.isMms ? 1 : 0, - "has_draft": 0, - "has_attachment": actionData.hasAttachment ? 1 : 0 - }; - this.updateById(threadIds, valueBucket, res => { - // Invoke the SMS database to insert SMS messages. - this.dealInsertMessageDetail(param, actionData, sessionId, initDatas => { - let result = { - rowId: sessionId, - initDatas: initDatas - } - callback(result); - }); - }); - } - - querySessionByTelephone(telephone, callback) { - let result: LooseObject = {}; - let queryPromise = this.querySessionByTelephoneRdb(telephone); - Promise.all([queryPromise]).then((res) => { - result.code = common.int.SUCCESS; - result.response = res[0]; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "querySessionByTelephone, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - } - - // Obtains the session list based on the mobile number. - async querySessionByTelephoneRdb(telephone) { - // Creating a query condition object - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - // If this parameter is left blank, all list data is queried. - if (telephone) { - await predicates.equalTo(mmsTable.sessionField.telephone, telephone); - } - // Obtain the result set. - let resultSet = await rdbStore.query(predicates); - // Obtain the first entry. - resultSet.goToFirstRow(); - let result: LooseObject = {}; - result.id = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.id))); - result.time = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.time))); - result.telephone = await resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.telephone)); - result.content = await resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.content)); - result.contactsNum = - await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.contactsNum))); - result.smsType = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.smsType))); - result.unreadCount = - await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.unreadCount))); - result.sendStatus = - await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.sendStatus))); - result.hasDraft = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasDraft))); - result.messageCount = - await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.messageCount))); - return result; - } - - // insert - insertSession(valueBucket, callback) { - this.insertSessionRdb(valueBucket, callback); - } - - insertSessionRdb(valueBucket, callback) { - HiLog.i(TAG, "insert session rdb 123"); - let insertPromise = rdbStore.insert(MmsDatabaseHelper.TABLE.SESSION, valueBucket); - let result: LooseObject = {}; - insertPromise.then((ret) => { - HiLog.i(TAG, "insert session rdb rowId: " + ret); - result.code = common.int.SUCCESS; - result.rowId = ret; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "insert session rdb error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - } - - /** - * New data - */ - async insert(tableName, valueBucket) { - let promise = await rdbStore.insert(tableName, valueBucket); - let rowId = 0; - promise.then((ret) => { - rowId = ret; - HiLog.i(TAG, "insert, first success: " + rowId); - }).catch((err) => { - HiLog.e(TAG, "insert, err: " + JSON.stringify(err.message)); - }) - await promise; - return rowId; - } - - dealInsertMessageDetail(param, actionData, threadId, callback) { - // Get the largest groupId - this.queryMaxGroupId(actionData, res => { - let maxGroupId = res == common.string.EMPTY_STR ? 0 : parseInt(res); - maxGroupId = maxGroupId + 1; - this.insertMessageDetailByGroupId(param, threadId, maxGroupId, actionData, callback); - }); - } - - insertMessageDetailByGroupId(param, threadId, maxGroupId, actionData, callback) { - let initDatas = []; - let count = 0; - let sendResults = actionData.sendResults; - sendResults.forEach(sendResult => { - let insertDetail = { - slotId: actionData.slotId, - receiverNumber: common.string.EMPTY_STR, - senderNumber: common.string.EMPTY_STR, - smsType: param.smsType, - content: param.content, - sendStatus: 0, - sessionType: 0, - threadId: threadId, - isSender: actionData.isSender, - groupId: maxGroupId, - mmsSource: actionData.mmsSource, - isMms: actionData.isMms, - isRead: -1 - }; - if (actionData.isReceive) { - insertDetail.receiverNumber = actionData.ownNumber; - insertDetail.senderNumber = sendResult.telephone; - insertDetail.isRead = 0; - } - this.insertMessageDetail(insertDetail, result => { - count++; - HiLog.i(TAG, "insertMessageDetailByGroupId, result: " + result); - let initData = { - id: result, - telephone: sendResult.telephone - }; - initDatas.push(initData); - if (count == sendResults.length) { - callback(initDatas); - } - }); - }) - } - - dealSendResults(sendResults) { - let contractsNum = sendResults.length; - let telephone = common.string.EMPTY_STR; - let content = common.string.EMPTY_STR; - // Sending succeeded. - let sendStatus = 0; - for (let sendResult of sendResults) { - telephone = telephone + sendResult.telephone + common.string.COMMA; - content = sendResult.content; - sendStatus = sendResult.sendStatus; - } - telephone = telephone.substring(0, telephone.length - 1); - let smsType = 0; - if (contractsNum == 1 && telephoneUtils.judgeIsInfoMsg(telephone)) { - smsType = 1; - } - let timestamp = new Date().getTime(); - let result: LooseObject = {}; - result.contractsNum = contractsNum; - result.telephone = telephoneUtils.dealTelephoneSort(telephone); - result.content = content; - result.sendStatus = sendStatus; - result.smsType = smsType; - result.timestamp = timestamp; - return result; - } - - insertMessageDetail(value, callback) { - let actionData: LooseObject = {}; - let time = new Date(); - let timeStr = time.getTime() + common.string.EMPTY_STR; - var stringValue = { - "slot_id": common.int.SIM_ONE, - "receiver_number": value.receiverNumber, - "sender_number": value.senderNumber, - "start_time": timeStr, - "end_time": timeStr, - "msg_type": value.isMms ? "1" : "0", - "sms_type": value.smsType, - "msg_title": value.content, - "msg_content": value.content, - "msg_state": value.sendStatus, - "operator_service_number": common.string.EMPTY_STR, - "msg_code": common.string.EMPTY_STR, - "session_id": value.threadId, - "is_lock": "0", - "is_read": value.isRead, - "is_collect": "0", - "session_type": value.sessionType, - "is_subsection": "0", - "is_sender": value.isSender, - "is_send_report": 0, - "group_id": value.groupId - }; - if (value.slotId != null) { - stringValue.slot_id = value.slotId; - } - actionData.stringValue = stringValue; - this.insertMessageDetailRdb(actionData, msgId => { - HiLog.i(TAG, "insertMessageDetail, msgId: " + msgId); - if (value.isMms) { - value.msgId = msgId; - this.batchInsertMmsPart(value); - } - callback(msgId); - }); - } - - batchInsertMmsPart(value) { - let bacthmsParts = []; - for (let source of value.mmsSource) { - let stringValue = { - "msg_id": value.msgId, - "group_id": value.groupId, - "type": source.msgType, - "location_path": source.msgUriPath, - "content": source.content, - "recording_time": source.time, - "part_size": source.fileSize - }; - bacthmsParts.push(stringValue); - } - for (let stringValue of bacthmsParts) { - this.insertMmsPart(stringValue); - } - } - - async insertMmsPart(stringValue) { - let dataAbilityHelper = await dataShare.createDataShareHelper(this.context, common.string.URI_MESSAGE_LOG); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MMS_PART; - dataAbilityHelper.insert(managerUri, stringValue).then(data => { - }).catch(error => { - HiLog.e(TAG, "insertMmsPart, fail: " + JSON.stringify(error.meaasge)); - }); - } - - // Inserting a single SMS message - async insertMessageDetailRdb(actionData, callback) { - // Obtains the DataAbilityHelper object. - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - let dataAbilityHelper = await dataShare.createDataShareHelper(this.context, common.string.URI_MESSAGE_LOG); - let promise = dataAbilityHelper.insert(managerUri, actionData.stringValue); - await promise.then(data => { - callback(data); - }).catch(error => { - HiLog.e(TAG, "insertMessageDetailRdb, fail: " + JSON.stringify(error.message)); - }); - } - - /** - * Update data based on the primary key ID. - * @param threadIds Session ID - * @return - */ - async updateById(threadIds, valueBucket, callback) { - HiLog.i(TAG, "updateById, threadIds: " + JSON.stringify(threadIds)); - if (threadIds.length != 0) { - for (let threadId of threadIds) { - // Creating a query condition object - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - await predicates.equalTo(mmsTable.sessionField.id, threadId); - this.update(predicates, valueBucket, res => { - callback(res); - }); - } - - } - } - - /** - * Update Interface - * @param predicates Update Condition - * @param predicates Update Value - * @return - */ - async update(predicates, valueBucket, callback) { - let changedRows = await rdbStore.update(valueBucket, predicates); - callback(changedRows); - } - - /** - * Query the maximum group ID. - * @param actionData - * @param callBack - * @return - */ - queryMaxGroupId(actionData, callBack) { - this.queryMaxGroupIdDb(actionData, res => { - HiLog.i(TAG, "queryMaxGroupId, callback"); - callBack(res.maxGroupId); - }); - } - - // Get the largest groupId - async queryMaxGroupIdDb(actionData, callback) { - let dataAbilityHelper = await dataShare.createDataShareHelper(this.context, common.string.URI_MESSAGE_LOG); - let resultColumns = [ - "maxGroupId" - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MAX_GROUP; - dataAbilityHelper.query(managerUri, condition, resultColumns).then( resultSet => { - let result: LooseObject = {}; - if (resultSet != undefined) { - if (resultSet.goToLastRow()) { - result.maxGroupId = resultSet.getString(0); - } - } - callback(result); - }).catch(error => { - HiLog.e(TAG, "queryMaxGroupIdDb, error: " + JSON.stringify(error.message)); - }); - } - - /** - * commonEvent publish data - */ - publishData(telephone, content) { + public publishData(telephone, content): void { HiLog.i(TAG, "publishData, start"); let actionData = { telephone: telephone, @@ -625,47 +209,48 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit }); } - async sendNotification(telephone, msgId, content) { - let telephones = [telephone]; - this.queryContactDataByTelephone(telephones, async (contracts) => { + public sendNotification(telephone, msgId, content, context): void { + let condition: LooseObject = {}; + condition.telephones = [telephone]; + ContactService.getInstance().queryContactDataByCondition(condition, res => { HiLog.i(TAG, "sendNotification, callback"); - let actionData = this.dealContactParams(contracts, telephone); + if (res.code == common.int.FAILURE) { + return; + } + let contacts: Array = res.abilityResult; + let actionData: LooseObject = this.dealContactParams(contacts, telephone); if (content.length > 15) { content = content.substring(0, 15) + "..."; } - let title = telephone; - if(contracts.length > 0) { - title = contracts[0].displayName + let title: string = telephone; + if(contacts.length > 0) { + title = contacts[0].displayName } - let message = { - title: title, - text: content, + let message: LooseObject = { + "title": title, + "text": content, }; actionData.message = message; actionData.msgId = msgId; actionData.unreadTotal = 0; - let params: LooseObject = { - mmsContext: this.context - }; - messageService.statisticalData(params, function (res) { + NotificationService.getInstance().sendNotify(actionData); + ConversationListService.getInstance().statisticalData(res => { if (res.code == common.int.SUCCESS) { - actionData.unreadTotal= res.response.totalListCount; - HiLog.i(TAG, "sendNotification, callback actionData"); + NotificationService.getInstance().setBadgeNumber(Number(res.response.totalListCount)); } - NotificationService.getInstance().sendNotify(actionData); - }); - }); + }, context); + }, context); } - dealContactParams(contracts, telephone) { + public dealContactParams(contacts, telephone): LooseObject { let actionData: LooseObject = {}; - let params = []; - if (contracts.length == 0) { + let params: Array = []; + if (contacts.length == 0) { params.push({ telephone: telephone, }); } else { - let contact = contracts[0]; + let contact: LooseObject = contacts[0]; params.push({ contactsName: contact.displayName, telephone: telephone, @@ -675,35 +260,4 @@ export default class MmsStaticSubscriber extends StaticSubscriberExtensionAbilit actionData.contactObjects = JSON.stringify(params); return actionData; } - - async queryContactDataByTelephone(telephones, callback) { - let resultColumns = [ - mmsTable.contactDataColumns.detailInfo, - mmsTable.contactDataColumns.displayName, - ]; - let contactDataAbilityHelper = - await dataShare.createDataShareHelper(this.context, common.string.URI_ROW_CONTACTS); - let condition = new dataSharePredicates.DataSharePredicates(); - let contactDataUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; - condition.in(mmsTable.contactDataColumns.detailInfo, telephones); - condition.and(); - condition.equalTo(mmsTable.contactDataColumns.typeId, "5"); - contactDataAbilityHelper.query(contactDataUri, condition, resultColumns).then(resultSet => { - let contracts = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let contract = { - detailInfo: resultSet.getString(0), - displayName: resultSet.getString(1) - }; - contracts.push(contract); - } - } - callback(contracts); - }).catch(error => { - HiLog.e(TAG, "queryContactDataByTelephone error: " + JSON.stringify(error.message)); - }); - } - - } diff --git a/entry/src/main/ets/data/commonData.ets b/entry/src/main/ets/data/commonData.ets index 042580e..0619897 100644 --- a/entry/src/main/ets/data/commonData.ets +++ b/entry/src/main/ets/data/commonData.ets @@ -105,9 +105,9 @@ export default { // abilityName ABILITY_NAME: "com.ohos.mms.MainAbility", // BundleName of a contact. - CONTRACT_BUNDLE_NAME: "com.ohos.contacts", + CONTACT_BUNDLE_NAME: "com.ohos.contacts", // contact AbilityName - CONTRACT_ABILITY_NAME: "com.ohos.contacts.MainAbility", + CONTACT_ABILITY_NAME: "com.ohos.contacts.MainAbility", // Public entity COMMON_ENTITIES: "entity.system.home", // Processing succeeded. @@ -168,8 +168,10 @@ export default { CONTACT_URI: "/contacts/contact", // SMS database URI_MESSAGE_LOG: "datashare:///com.ohos.smsmmsability", - // Querying SMs + // sms_mms_info table URI_MESSAGE_INFO_TABLE: "/sms_mms/sms_mms_info", + // session table + URI_MESSAGE_SESSION_TABLE: "/sms_mms/session", // Statistic URI_MESSAGE_UNREAD_COUNT: "/sms_mms/sms_mms_info/unread_total", // Get the largest groupID @@ -206,7 +208,7 @@ export default { // UNICOM UNICOM: "China Unicom", }, - contractPage: { + contactPage: { // Go to New Contact PAGE_FLAG_SAVE_CONTACT: "page_flag_save_contact", // Edit Before Call @@ -281,5 +283,69 @@ export default { PPT_IMAGE_HEIGHT: 220, DISTANCE: 20, TOTAL_HEIGHT: 650 - } + }, + RUN_IN_WORKER_METHOD: { + // Contacts + queryContactDataByCondition: "queryContactDataByCondition", + queryContactDataSizeByCondition: "queryContactDataSizeByCondition", + queryContactByCondition: "queryContactByCondition", + queryContactSizeByCondition: "queryContactSizeByCondition", + queryRawContactSizeByCondition: "queryRawContactSizeByCondition", + queryContactViewByCondition: "queryContactViewByCondition", + // detail + insertSmsMmsInfo: "insertSmsMmsInfo", + deleteSmsMmsInfoByCondition: "deleteSmsMmsInfoByCondition", + updateSmsMmsInfoByCondition: "updateSmsMmsInfoByCondition", + querySmsMmsInfoByCondition: "querySmsMmsInfoByCondition", + querySmsMmsInfoSizeByCondition: "querySmsMmsInfoSizeByCondition", + queryMaxGroupId: "queryMaxGroupId", + statisticalData: "statisticalData", + // list + insertSession: "insertSession", + deleteSessionByCondition: "deleteSessionByCondition", + updateSessionByCondition: "updateSessionByCondition", + querySessionByCondition: "querySessionByCondition", + querySessionSizeByCondition: "querySessionSizeByCondition" + }, + sms_type: { + COMMON: 0, + NOTICE: 1 + }, + is_read: { + UN_READ: 0, + READ: 1 + }, + session_type: { + COMMON: 0, + BROADCAST: 1, + GROUP_SEND: 2 + }, + is_lock: { + NO: 0, + YES: 1 + }, + is_collect: { + NOT_FAVORITE: 0, + FAVORITE: 1 + }, + is_send_report: { + NO: 0, + YES: 1 + }, + is_sender: { + NO: 0, + YES: 1 + }, + has_draft: { + NO: 0, + HAVE: 1 + }, + has_mms: { + NO: 0, + HAVE: 1 + }, + has_attachment: { + NO: 0, + HAVE: 1 + }, } \ No newline at end of file diff --git a/entry/src/main/ets/data/tableData.ets b/entry/src/main/ets/data/tableData.ets index 65f99ce..852a1c3 100644 --- a/entry/src/main/ets/data/tableData.ets +++ b/entry/src/main/ets/data/tableData.ets @@ -13,33 +13,6 @@ * limitations under the License. */ export default { - DB: { - MMSSMS: { - config: { - name: "mmssms.db" - }, - version: 1 - } - }, - table: { - // Session table - session: - "CREATE TABLE IF NOT EXISTS session (" + - "id INTEGER PRIMARY KEY AUTOINCREMENT, " + - "time INTEGER DEFAULT 0, " + - "telephone TEXT, " + - "content TEXT, " + - "contacts_num INTEGER DEFAULT 0, " + - "sms_type INTEGER DEFAULT 0, " + - "unread_count INTEGER DEFAULT 0, " + - "sending_status INTEGER DEFAULT 0, " + - "has_draft INTEGER DEFAULT 0," + - "has_lock INTEGER DEFAULT 0," + - "message_count INTEGER DEFAULT 0," + - "has_mms INTEGER DEFAULT 0," + - "has_attachment INTEGER DEFAULT 0" + - ");", - }, // Name of the field corresponding to the session list sessionField: { id: "id", //session Table id integer @@ -72,7 +45,7 @@ export default { operatorServiceNumber: "operator_service_number", //Operator service number TEXT msgCode: "msg_code", //Message Code integer isLock: "is_lock", //Locked 0-No,1-Yes integer - isRead: "is_read", // Read or Not 0-Read,1-Unread integer + isRead: "is_read", // Read or Not isCollect: "is_collect", //Favorites 0-Not favorited,1-Favorites integer sessionType: "session_type", //Session Type 0 - Common 1 - broadcast 2 - Group Sending integer retryNumber: "retry_number", //Retry Times integer diff --git a/entry/src/main/ets/model/BaseModel.ets b/entry/src/main/ets/model/BaseModel.ets index ae6061e..a68a42a 100644 --- a/entry/src/main/ets/model/BaseModel.ets +++ b/entry/src/main/ets/model/BaseModel.ets @@ -15,16 +15,16 @@ import LooseObject from "../data/LooseObject"; export default class BaseModel { - encapsulateReturnResult(code, abilityResult) { - var result: LooseObject = {}; - result.code = code; - result.abilityResult = abilityResult; - return result; - } + public encapsulateReturnResult(code, abilityResult): LooseObject { + let result: LooseObject = {}; + result.code = code; + result.abilityResult = abilityResult; + return result; + } - encapsulateReturnCode(code) { - var result: LooseObject = {}; - result.code = code; - return result; - } + public encapsulateReturnCode(code): LooseObject { + let result: LooseObject = {}; + result.code = code; + return result; + } } \ No newline at end of file diff --git a/entry/src/main/ets/model/ContactsModel.ets b/entry/src/main/ets/model/ContactsModel.ets index 66f8bbc..b468442 100644 --- a/entry/src/main/ets/model/ContactsModel.ets +++ b/entry/src/main/ets/model/ContactsModel.ets @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import dataShare from "@ohos.data.dataShare"; +import dataSharePredicates from "@ohos.data.dataSharePredicates"; import BaseModel from "./BaseModel"; import common from "../data/commonData"; @@ -19,160 +21,205 @@ import HiLog from "../utils/HiLog"; import mmsTable from "../data/tableData"; import LooseObject from "../data/LooseObject" -import dataShare from "@ohos.data.dataShare"; -import dataSharePredicates from "@ohos.data.dataSharePredicates"; - const TAG = "ContactsModel"; export default class ContactsModel extends BaseModel { - async queryContactDataByIds(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.contactDataColumns.detailInfo, - mmsTable.contactDataColumns.displayName, - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let contactDataUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; - condition.in(mmsTable.contactDataColumns.contactId, actionData.contractIds); - condition.and(); - condition.equalTo(mmsTable.contactDataColumns.typeId, "5"); - condition.and(); - condition.equalTo(mmsTable.contactDataColumns.hasDelete, "0"); - dataHelper.query(contactDataUri, condition, resultColumns).then(resultSet => { - callback(this.dealResultSet(resultSet)); - }).catch(error => { - HiLog.e(TAG, "queryContactDataByIds, error: " + JSON.stringify(error.message)); - }); - } - - async queryContactDataByTelephone(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.contactDataColumns.detailInfo, - mmsTable.contactDataColumns.displayName, - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let contactDataUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; - condition.in(mmsTable.contactDataColumns.detailInfo, actionData.telephones); - condition.and(); - condition.equalTo(mmsTable.contactDataColumns.typeId, "5"); - condition.and(); - condition.equalTo(mmsTable.contactDataColumns.hasDelete, "0"); - dataHelper.query(contactDataUri, condition, resultColumns).then(resultSet => { - callback(this.dealResultSet(resultSet)); - }).catch(error => { - HiLog.e(TAG, "queryContactDataByTelephone, error: " + JSON.stringify(error.message)); - callback([]); - }); - } - - dealResultSet(resultSet) { - let contracts = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let contract: LooseObject = {}; - contract.detailInfo = resultSet.getString(0); - contract.displayName = resultSet.getString(1); - contracts.push(contract); - } + public async queryContactDataByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryContactDataCondition(actionData); + let contactDataUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; + dataHelper.query(contactDataUri, condition, this.buildContactDataTablePartColumns()).then(resultSet => { + let resultList: Array = []; + if (resultSet.rowCount > 0) { + while (resultSet.goToNextRow()) { + resultList.push(this.buildContactDataResult(resultSet)); } - return contracts; - } + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryContactDataByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - async queryContact(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.contactColumns.id - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let rawContactUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_URI; - let offset = (actionData.page - 1) * actionData.limit; - condition.limit(actionData.limit, offset).orderByDesc(mmsTable.contactColumns.lastestContactedTime); - dataHelper.query(rawContactUri, condition, resultColumns).then(resultSet => { - let rawContactIds = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - rawContactIds.push(resultSet.getString(0)); - } - } - callback(rawContactIds); - }).catch(error => { - HiLog.e(TAG, "queryContact, error: " + JSON.stringify(error.message)); - }); - } + public async queryContactDataSizeByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryContactDataCondition(actionData); + let contactDataUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; + dataHelper.query(contactDataUri, condition, this.buildContactDataTablePartColumns()).then(resultSet => { + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultSet.rowCount)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryContactDataSizeByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - async countContact(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.contactColumns.id - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let rawContactUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_URI; - condition.orderByDesc(mmsTable.contactColumns.lastestContactedTime); - dataHelper.query(rawContactUri, condition, resultColumns).then(resultSet => { - let count = 0; - if (resultSet != undefined) { - count = resultSet.rowCount; - } - callback(count); - }).catch(error => { - HiLog.e(TAG, "countContact, error: " + JSON.stringify(error.message)); - }); - } + public async queryContactByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryContactCondition(actionData); + let contactUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_URI; + dataHelper.query(contactUri, condition, this.buildContactTablePartColumns()).then(resultSet => { + let resultList: Array = []; + if (resultSet.rowCount > 0) { + while (resultSet.goToNextRow()) { + resultList.push(this.buildContactResult(resultSet)); + } + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryContactByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - async searchContracts(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.searchContactView.detailInfo, - mmsTable.searchContactView.displayName - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let searchContactsUri = common.string.URI_ROW_CONTACTS + common.string.CONTACT_SEARCHE; - condition.equalTo(mmsTable.searchContactView.contentType, "phone") - .beginWrap() - .contains(mmsTable.searchContactView.displayName, actionData.telephone) - .or() - .contains(mmsTable.searchContactView.detailInfo, actionData.telephone) - .endWrap(); - dataHelper.query(searchContactsUri, condition, resultColumns).then(resultSet => { - let contracts = this.dealResultSet(resultSet); - callback(this.encapsulateReturnResult(common.int.SUCCESS, contracts)); - }).catch(error => { - HiLog.e(TAG, "searchContracts, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } + public async queryContactSizeByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryContactCondition(actionData); + let contactUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_URI; + dataHelper.query(contactUri, condition, this.buildContactTablePartColumns()).then(resultSet => { + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultSet.rowCount)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryContactSizeByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - /** - * Querying business card data - * - * @param actionData query parameters - * @callback callback - * @param context - */ - async queryProfile(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_ROW_CONTACTS); - let resultColumns = [ - mmsTable.contactDataColumns.id, - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let contactDataUri = common.string.URI_ROW_CONTACTS + common.string.PROFILE_DATA_URI; - dataHelper.query(contactDataUri, condition, resultColumns).then(resultSet => { - let count = 0; - if (resultSet != undefined) { - count = resultSet.rowCount; - HiLog.i(TAG, "queryProfile, goToNextRow: " + count); - resultSet.close(); - } - callback(count); - }).catch(error => { - HiLog.e(TAG, "queryProfile, error: " + JSON.stringify(error.message)); - }); + public async queryRawContactSizeByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryRawContactCondition(actionData); + let rawContactUri: string = common.string.URI_ROW_CONTACTS + common.string.PROFILE_DATA_URI; + dataHelper.query(rawContactUri, condition, this.buildRawContactTablePartColumns()).then(resultSet => { + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultSet.rowCount)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryRawContactSizeByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } + + public async queryContactViewByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_ROW_CONTACTS); + let condition: dataSharePredicates.DataSharePredicates = this.buildQueryContactViewCondition(actionData); + let searchContactViewUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_SEARCHE; + dataHelper.query(searchContactViewUri, condition, this.buildRawContactViewPartColumns()).then(resultSet => { + let resultList: Array = []; + if (resultSet.rowCount > 0) { + while (resultSet.goToNextRow()) { + resultList.push(this.buildContactViewResult(resultSet)); + } + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryContactViewByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } + + private buildContactDataTablePartColumns(): Array { + // part of contact_data table columns + return [ + mmsTable.contactDataColumns.detailInfo, + mmsTable.contactDataColumns.displayName, + ]; + } + + private buildContactTablePartColumns(): Array { + // part of contact table columns + return [ + mmsTable.contactColumns.id + ]; + } + + private buildRawContactTablePartColumns(): Array { + // part of raw_contact table columns + return [ + mmsTable.contactDataColumns.id + ]; + } + + private buildRawContactViewPartColumns(): Array { + // part of contact view table columns + return [ + mmsTable.searchContactView.detailInfo, + mmsTable.searchContactView.displayName + ]; + } + + private buildContactDataResult(resultSet): LooseObject { + let result: LooseObject = {}; + result.detailInfo = resultSet.getString(resultSet.getColumnIndex(mmsTable.contactDataColumns.detailInfo)); + result.displayName = resultSet.getString(resultSet.getColumnIndex(mmsTable.contactDataColumns.displayName)); + return result; + } + + private buildContactResult(resultSet): LooseObject { + let result: LooseObject = {}; + result.id = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.contactColumns.id))); + return result; + } + + private buildContactViewResult(resultSet): LooseObject { + let result: LooseObject = {}; + result.detailInfo = resultSet.getString(resultSet.getColumnIndex(mmsTable.contactDataColumns.detailInfo)); + result.displayName = resultSet.getString(resultSet.getColumnIndex(mmsTable.contactDataColumns.displayName)); + return result; + } + + private buildQueryContactDataCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + condition.equalTo(mmsTable.contactDataColumns.typeId, "5"); + if (actionData.hasDelete != null) { + condition.and().equalTo(mmsTable.contactDataColumns.hasDelete, actionData.hasDelete); } + if (actionData.contactIds != null && actionData.contactIds.length > 0) { + condition.and().in(mmsTable.contactDataColumns.contactId, actionData.contactIds); + } + if (actionData.telephones != null && actionData.telephones.length > 0) { + condition.and().in(mmsTable.contactDataColumns.detailInfo, actionData.telephones); + } + return condition; + } + + private buildQueryContactCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + condition.isNotNull(mmsTable.contactColumns.id); + if (actionData.page != null && actionData.limit != null) { + let offset: number = (actionData.page - 1) * actionData.limit; + condition.and().limit(actionData.limit, offset); + } + if (actionData.telephone != null) { + condition.and() + .equalTo(mmsTable.searchContactView.contentType, "phone") + .beginWrap() + .contains(mmsTable.searchContactView.displayName, actionData.telephone) + .or() + .contains(mmsTable.searchContactView.detailInfo, actionData.telephone) + .endWrap(); + } + if (actionData.orderByTimeDesc != null) { + condition.orderByDesc(mmsTable.contactColumns.lastestContactedTime); + } + return condition; + } + + private buildQueryRawContactCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + return condition; + } + + private buildQueryContactViewCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + condition.equalTo(mmsTable.searchContactView.contentType, "phone") + .beginWrap() + .contains(mmsTable.searchContactView.displayName, actionData.telephone) + .or() + .contains(mmsTable.searchContactView.detailInfo, actionData.telephone) + .endWrap(); + return condition; + } } \ No newline at end of file diff --git a/entry/src/main/ets/model/ConversationListModel.ets b/entry/src/main/ets/model/ConversationListModel.ets index 0a0e607..f8f41ca 100644 --- a/entry/src/main/ets/model/ConversationListModel.ets +++ b/entry/src/main/ets/model/ConversationListModel.ets @@ -13,201 +13,171 @@ * limitations under the License. */ -import BaseModel from "./BaseModel"; -import common from "../data/commonData"; -import mmsTable from "../data/tableData"; -import HiLog from "../utils/HiLog"; -import LooseObject from "../data/LooseObject" -import MmsDatabaseHelper from "../utils/MmsDatabaseHelper"; -import ohosDataRdb from "@ohos.data.rdb"; +import dataShare from '@ohos.data.dataShare'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import dataShare from "@ohos.data.dataShare"; -import dataSharePredicates from "@ohos.data.dataSharePredicates"; +import BaseModel from './BaseModel'; +import common from '../data/commonData'; +import mmsTable from '../data/tableData'; +import HiLog from '../utils/HiLog'; +import LooseObject from '../data/LooseObject'; +import StringUtil from '../utils/StringUtil'; const TAG = "ConversationListModel"; export default class ConversationListModel extends BaseModel { - async querySessionList(actionData) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - let numberType = actionData.numberType; - if (numberType != null) { - await predicates.equalTo(mmsTable.sessionField.smsType, numberType); - } - await predicates.orderByDesc(mmsTable.sessionField.time); - await predicates.limitAs(actionData.limit); - let offset = actionData.page < 3 ? (actionData.page - 1) * 50 : (actionData.page - 2) * 100 + 50; - await predicates.offsetAs(offset); - let resultSet = await globalThis.MmsDatabaseHelper.query(predicates); - let sessionList = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let item = await this.buildResultSet(resultSet); - sessionList.push(item); - } - } - let result = { - response: sessionList, - } - return result; + public async insertSession(valueBucket, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_SESSION_TABLE; + dataHelper.insert(managerUri, valueBucket).then(data => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, data)); + } + }).catch(error => { + HiLog.e(TAG, "insertSession fail, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } + + public async deleteSessionByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySessionCondition(actionData); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_SESSION_TABLE; + dataHelper.delete(managerUri, condition).then(data => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, data)); + } + }).catch(error => { + HiLog.e(TAG, "deleteSessionByCondition, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } + + public async updateSessionByCondition(actionData, valueBucket, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySessionCondition(actionData); + if (valueBucket == null) { + HiLog.e(TAG, "updateSessionByCondition fail, valueBucket is null!"); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } } + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_SESSION_TABLE; + dataHelper.update(managerUri, condition, valueBucket).then(data => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, data)); + } + }).catch(error => { + HiLog.e(TAG, "updateSessionByCondition fail, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } - async querySessionByTelephone(telephone) { - HiLog.i(TAG, "query session by telephone") - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - if (telephone) { - await predicates.equalTo(mmsTable.sessionField.telephone, telephone); - } - - let resultSet = await globalThis.MmsDatabaseHelper.query(predicates); - if(resultSet === null) { - return null; + public async querySessionByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySessionCondition(actionData); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_SESSION_TABLE; + dataHelper.query(managerUri, condition, this.buildSessionTableColumns()).then(resultSet => { + let resultList: Array = []; + if (resultSet.rowCount > 0) { + while (resultSet.goToNextRow()) { + resultList.push(this.buildSessionResult(resultSet)); } + } else { resultSet.goToFirstRow(); - let result = await this.buildResultSet(resultSet); - return result; - } + resultList.push(this.buildSessionResult(resultSet)); + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "querySessionByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - async querySessionById(threadId) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - if (threadId) { - await predicates.equalTo(mmsTable.sessionField.id, threadId); - } - let resultSet = await globalThis.MmsDatabaseHelper.query(predicates); - resultSet.goToFirstRow(); - let result = await this.buildResultSet(resultSet); - return result; - } + public async querySessionSizeByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySessionCondition(actionData); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_SESSION_TABLE; + dataHelper.query(managerUri, condition, this.buildSessionTableColumns()).then(resultSet => { + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultSet.rowCount)); + }).catch(error => { + HiLog.e(TAG, "querySessionSizeByCondition, fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - async searchSessionByTelephone(telephone, numberType) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - if (telephone != common.string.EMPTY_STR) { - await predicates.like(mmsTable.sessionField.telephone, "%" + telephone + "%"); - } - if (numberType != null) { - await predicates.equalTo(mmsTable.sessionField.smsType, numberType); - } - let resultSet = await globalThis.MmsDatabaseHelper.query(predicates); - let sessionList = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let item = await this.buildResultSet(resultSet); - sessionList.push(item); - } - } - return sessionList; + private buildQuerySessionCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + condition.isNotNull(mmsTable.sessionField.id); + if (actionData.smsType != null) { + condition.and().equalTo(mmsTable.sessionField.smsType, actionData.smsType); } + if (actionData.telephone != null) { + condition.and().equalTo(mmsTable.sessionField.telephone, actionData.telephone); + } + if (actionData.telephone_like != null) { + condition.and().like(mmsTable.sessionField.telephone, "%" + actionData.telephone_like + "%"); + } + if (actionData.threadId != null) { + condition.and().equalTo(mmsTable.sessionField.id, actionData.threadId); + } + if (actionData.threadIds != null && actionData.threadIds.length > 0) { + condition.and().in(mmsTable.sessionField.id, actionData.threadIds); + } + if (actionData.unreadCount_greaterThan != null) { + condition.and().greaterThan(mmsTable.sessionField.unreadCount, actionData.unreadCount_greaterThan); + } + if (actionData.orderByTimeDesc) { + condition.orderByDesc(mmsTable.sessionField.time); + } + if (actionData.page != null && actionData.limit != null) { + condition.limit(actionData.limit, StringUtil.getOffsetForSession(actionData.page)); + } + return condition; + } - async buildResultSet(resultSet) { - let result: LooseObject = {}; - result.id = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.id))); - result.time = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.time))); - result.hasDraft = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasDraft))); - result.smsType = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.smsType))); - result.telephone = await resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.telephone)); - result.content = await resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.content)); - result.contactsNum = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.contactsNum))); - result.unreadCount = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.unreadCount))); - result.messageCount = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.messageCount))); - result.hasMms = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasMms))); - result.sendStatus = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.sendStatus))); - result.hasAttachment = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasAttachment))); - result.hasLock = await Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasLock))); - result.telephoneFormat = result.telephone; - return result; - } + private buildSessionResult(resultSet): LooseObject { + let result: LooseObject = {}; + result.id = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.id))); + result.time = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.time))); + result.telephone = resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.telephone)); + result.content = resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.content)); + result.contactsNum = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.contactsNum))); + result.smsType = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.smsType))); + result.unreadCount = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.unreadCount))); + result.sendStatus = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.sendStatus))); + result.hasDraft = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasDraft))); + result.hasLock = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasLock))); + result.messageCount = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.messageCount))); + result.hasMms = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasMms))); + result.hasAttachment = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.sessionField.hasAttachment))); + result.telephoneFormat = result.telephone; + return result; + } - async countSessionList(actionData) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - let numberType = actionData.numberType; - if (numberType != null) { - await predicates.equalTo(mmsTable.sessionField.smsType, numberType); - } - let resultSet = await globalThis.MmsDatabaseHelper.query(predicates); - let count = resultSet.rowCount; - let result = { - total: count, - } - return result; - } - - async statisticalData(actionData, callback) { - let mmsContext; - if (actionData.mmsContext) { - mmsContext = actionData.mmsContext; - } else { - mmsContext = globalThis.mmsContext; - } - let resultColumns = [ - "totalListCount", - "unreadCount", - "unreadTotalOfInfo" - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_UNREAD_COUNT; - let dataShareHelper = await dataShare.createDataShareHelper(mmsContext, common.string.URI_MESSAGE_LOG); - dataShareHelper.query(managerUri, condition, resultColumns, (err, resultSet) => { - let result: LooseObject = {}; - if (resultSet != undefined) { - if (resultSet.goToLastRow()) { - result.totalListCount = resultSet.getString(0); - result.unreadCount = resultSet.getString(1); - result.unreadTotalOfInfo = resultSet.getString(2); - } - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, result)); - }); - } - - async markAllAsRead(threadIds, valueBucket) { - HiLog.i(TAG, "markAllAsRead, threadIds:" + JSON.stringify(threadIds)); - this.updateById(threadIds, valueBucket); - } - - async markAllToRead(smsType) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - predicates.equalTo(mmsTable.sessionField.smsType, smsType); - predicates.greaterThan(mmsTable.sessionField.unreadCount, 0); - let valueBucket = { - "unread_count": 0 - }; - globalThis.MmsDatabaseHelper.update(predicates, valueBucket); - } - - async updateById(threadIds, valueBucket) { - HiLog.i(TAG, ", updateById, threadIds: " + JSON.stringify(threadIds)) - if (threadIds.length != 0) { - for (let threadId of threadIds) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - await predicates.equalTo(mmsTable.sessionField.id, threadId); - globalThis.MmsDatabaseHelper.update(predicates, valueBucket); - HiLog.d(TAG, ", update session TAB end") - } - } - } - - async deleteMessageById(threadIds) { - HiLog.i(TAG, "deleteMessageById, threadIds: " + JSON.stringify(threadIds)); - if (threadIds.length != 0) { - for (let threadId of threadIds) { - let predicates = new ohosDataRdb.RdbPredicates(MmsDatabaseHelper.TABLE.SESSION); - await predicates.equalTo(mmsTable.sessionField.id, threadId); - globalThis.MmsDatabaseHelper.deleteItem(predicates); - HiLog.d(TAG, ", delete session TAB end") - } - } - } - - insertSession(valueBucket, callback) { - let insertPromise = globalThis.MmsDatabaseHelper.insert(MmsDatabaseHelper.TABLE.SESSION, valueBucket); - let result: LooseObject = {}; - insertPromise.then((ret) => { - result.code = common.int.SUCCESS; - result.rowId = ret; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "insertSession, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - } + private buildSessionTableColumns(): Array { + let sessionTableColumns: Array = [ + mmsTable.sessionField.id, + mmsTable.sessionField.time, + mmsTable.sessionField.telephone, + mmsTable.sessionField.content, + mmsTable.sessionField.contactsNum, + mmsTable.sessionField.smsType, + mmsTable.sessionField.unreadCount, + mmsTable.sessionField.sendStatus, + mmsTable.sessionField.hasDraft, + mmsTable.sessionField.hasLock, + mmsTable.sessionField.messageCount, + mmsTable.sessionField.hasMms, + mmsTable.sessionField.hasAttachment + ]; + return sessionTableColumns; + } } \ No newline at end of file diff --git a/entry/src/main/ets/model/ConversationModel.ets b/entry/src/main/ets/model/ConversationModel.ets index 3f93840..ddb9d07 100644 --- a/entry/src/main/ets/model/ConversationModel.ets +++ b/entry/src/main/ets/model/ConversationModel.ets @@ -13,594 +13,242 @@ * limitations under the License. */ -import BaseModel from "./BaseModel"; -import MorkDataModel from "./MorkDataModel"; -import common from "../data/commonData"; -import mmsTable from "../data/tableData"; -import HiLog from "../utils/HiLog" -import LooseObject from "../data/LooseObject" -import dataShare from "@ohos.data.dataShare"; -import dataSharePredicates from "@ohos.data.dataSharePredicates"; +import dataShare from '@ohos.data.dataShare'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +import BaseModel from './BaseModel'; +import common from '../data/commonData'; +import mmsTable from '../data/tableData'; +import HiLog from '../utils/HiLog'; +import LooseObject from '../data/LooseObject'; const TAG = "ConversationModel"; -let morkDataModel = new MorkDataModel(); export default class ConversationModel extends BaseModel { - async queryMessageDetail(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var resultColumns = this.buildResultColumns(); - let condition = this.buildQueryCondition(actionData); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - let resultList = []; - if( !resultSet.goToFirstRow() ) { - callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); - return; - } - if (resultSet != undefined) { - do { - let result: LooseObject = {}; - this.dealBaseColumnsData(result, resultSet); - result.operatorServiceNumber = resultSet.getString(resultSet.getColumnIndex("operator_service_number")); - result.msgCode = resultSet.getString(resultSet.getColumnIndex("msg_code")); - result.isLock = resultSet.getString(resultSet.getColumnIndex("is_lock")); - result.isRead = resultSet.getString(resultSet.getColumnIndex("is_read")); - result.isCollect = resultSet.getString(resultSet.getColumnIndex("is_collect")); - result.sessionType = resultSet.getString(resultSet.getColumnIndex("session_type")); - result.retryNumber = resultSet.getString(resultSet.getColumnIndex("retry_number")); - result.isSubsection = resultSet.getString(resultSet.getColumnIndex("is_subsection")); - result.sessionId = resultSet.getString(resultSet.getColumnIndex("session_id")); - result.groupId = resultSet.getString(resultSet.getColumnIndex("group_id")); - result.isSender = resultSet.getString(resultSet.getColumnIndex("is_sender")); - result.isSendReport = resultSet.getString(resultSet.getColumnIndex("is_send_report")); - resultList.push(result); - } while (resultSet.goToNextRow()) - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); - }).catch(error => { - HiLog.e(TAG, "queryMessageDetail, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } + public async insertSmsMmsInfo(valueBucket, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; + dataHelper.insert(managerUri, valueBucket).then(res => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, res)); + } + }).catch(error => { + HiLog.e(TAG, "insertSmsMmsInfo fail, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } - buildQueryCondition(actionData) { - let condition = new dataSharePredicates.DataSharePredicates(); - if (actionData.isDraft != null && actionData.isDraft) { - condition.equalTo(mmsTable.messageInfo.groupId, actionData.groupId); - condition.equalTo(mmsTable.messageInfo.msgState, actionData.sendStatus); + public async deleteSmsMmsInfoByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySmsMmsInfoCondition(actionData); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; + dataHelper.delete(managerUri, condition).then(res => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, res)); + } + }).catch(error => { + HiLog.e(TAG, "deleteSmsMmsInfoByCondition fail, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } + + public async updateSmsMmsInfoByCondition(actionData, valueBucket, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySmsMmsInfoCondition(actionData); + let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; + dataHelper.update(managerUri, condition, valueBucket).then(res => { + if (callback) { + callback(this.encapsulateReturnResult(common.int.SUCCESS, res)); + } + }).catch(error => { + HiLog.e(TAG, "updateSmsMmsInfoByCondition fail, error: " + JSON.stringify(error)); + if (callback) { + callback(this.encapsulateReturnCode(common.int.FAILURE)); + } + }); + } + + public async querySmsMmsInfoByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySmsMmsInfoCondition(actionData); + let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; + dataHelper.query(managerUri, condition, this.buildSmsMmsInfoTableColumns()).then(resultSet => { + let resultList: Array = []; + if (resultSet.rowCount > 0) { + while (resultSet.goToNextRow()) { + resultList.push(this.buildSmsMmsInfoResult(resultSet)); } - if (actionData.threadId != null) { - let sessionId = actionData.threadId + common.string.EMPTY_STR; - condition.equalTo(mmsTable.messageInfo.sessionId, sessionId); + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "querySmsMmsInfoByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } + + public async querySmsMmsInfoSizeByCondition(actionData, callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let condition: dataSharePredicates.DataSharePredicates = this.buildQuerySmsMmsInfoCondition(actionData); + let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; + dataHelper.query(managerUri, condition, this.buildSmsMmsInfoTableColumns()).then(resultSet => { + callback(this.encapsulateReturnResult(common.int.SUCCESS, resultSet.rowCount)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "querySmsMmsInfoSizeByCondition fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } + + public async queryMaxGroupId(callback, context): Promise { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let resultColumns: Array = ["maxGroupId"]; + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MAX_GROUP; + dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { + let maxGroupId: number = 0; + if (resultSet.rowCount > 0) { + if (resultSet.goToLastRow()) { + maxGroupId = (resultSet.getString(0) == common.string.EMPTY_STR) ? 0 : Number(resultSet.getString(0)); + HiLog.i(TAG, "queryMaxGroupId, maxGroupId: " + maxGroupId); } - if (actionData.threadIds != null && actionData.threadIds.length > 0) { - let sessionIds = this.groupIdToString(actionData.threadIds); - condition.in(mmsTable.messageInfo.sessionId, sessionIds); + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, maxGroupId)); + resultSet.close(); + }).catch(error => { + HiLog.e(TAG, "queryMaxGroupId fail, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } + + public async statisticalData(callback, context) { + let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG); + let resultColumns: Array = [ + "totalListCount", + "unreadCount", + "unreadTotalOfInfo" + ]; + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let managerUri: string = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_UNREAD_COUNT; + dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { + let result: LooseObject = { + "totalListCount": 0, + "unreadCount": 0, + "unreadTotalOfInfo": 0 + }; + if (resultSet.rowCount > 0) { + if (resultSet.goToLastRow()) { + result.totalListCount = Number(resultSet.getString(0)); + result.unreadCount = Number(resultSet.getString(1)); + result.unreadTotalOfInfo = Number(resultSet.getString(2)); } - if (actionData.msgIds != null && actionData.msgIds.length != 0) { - condition.in(mmsTable.messageInfo.msgId, actionData.msgIds); - } - if (actionData.hasLock != null) { - condition.equalTo(mmsTable.messageInfo.isLock, actionData.hasLock); - } - if (actionData.hasRead != null) { - condition.equalTo(mmsTable.messageInfo.isRead, actionData.hasRead); - } - return condition; - } + } + callback(this.encapsulateReturnResult(common.int.SUCCESS, result)); + }).catch(error => { + HiLog.e(TAG, "statisticalData, error: " + JSON.stringify(error)); + callback(this.encapsulateReturnCode(common.int.FAILURE)); + }); + } - buildBaseColumns() { - var resultColumns = [ - mmsTable.messageInfo.msgId, - mmsTable.messageInfo.slotId, - // Recipient Mobile Number - mmsTable.messageInfo.receiverNumber, - mmsTable.messageInfo.senderNumber, - mmsTable.messageInfo.startTime, - mmsTable.messageInfo.endTime, - mmsTable.messageInfo.msgType, - // sms = 0,mms, - mmsTable.messageInfo.smsType, - // 0: normal; 1: notification - mmsTable.messageInfo.msgTitle, - mmsTable.messageInfo.msgContent, - mmsTable.messageInfo.msgState - ]; - return resultColumns; + private buildQuerySmsMmsInfoCondition(actionData): dataSharePredicates.DataSharePredicates { + let condition: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + condition.isNotNull(mmsTable.messageInfo.msgId) + if (actionData.threadId != null) { + let sessionId: string = actionData.threadId + common.string.EMPTY_STR; + condition.and().equalTo(mmsTable.messageInfo.sessionId, sessionId); } + if (actionData.hasLock != null) { + condition.and().equalTo(mmsTable.messageInfo.isLock, actionData.hasLock); + } + if (actionData.hasRead != null) { + condition.and().equalTo(mmsTable.messageInfo.isRead, actionData.hasRead); + } + if (actionData.smsType != null) { + condition.and().equalTo(mmsTable.messageInfo.smsType, actionData.smsType); + } + if (actionData.msgId != null) { + condition.and().equalTo(mmsTable.messageInfo.msgId, actionData.msgId); + } + if (actionData.isDraft != null && actionData.isDraft) { + condition.and().equalTo(mmsTable.messageInfo.groupId, actionData.groupId); + condition.and().equalTo(mmsTable.messageInfo.msgState, actionData.sendStatus); + } + if (actionData.threadIds != null && actionData.threadIds.length > 0) { + condition.and().in(mmsTable.messageInfo.sessionId, actionData.threadIds); + } + if (actionData.msgIds != null && actionData.msgIds.length > 0) { + condition.and().in(mmsTable.messageInfo.msgId, actionData.msgIds); + } + if (actionData.groupIds != null && actionData.groupIds.length > 0) { + condition.and().in(mmsTable.messageInfo.groupId, actionData.groupIds); + } + if (actionData.groupId != null) { + condition.and().equalTo(mmsTable.messageInfo.groupId, actionData.groupId); + } + return condition; + } - buildResultColumns() { - let basicColumns = this.buildBaseColumns(); - var resultColumns = [ - mmsTable.messageInfo.operatorServiceNumber, - mmsTable.messageInfo.msgCode, - mmsTable.messageInfo.isLock, - mmsTable.messageInfo.isRead, - mmsTable.messageInfo.isCollect, - mmsTable.messageInfo.sessionType, - // 0: common; 1: broadcast; 2: group-send - mmsTable.messageInfo.retryNumber, - // Number of resending times - mmsTable.messageInfo.isSubsection, - mmsTable.messageInfo.sessionId, - mmsTable.messageInfo.groupId, - mmsTable.messageInfo.isSender, - mmsTable.messageInfo.isSendReport, - ]; - return basicColumns.concat(resultColumns); - } + private buildSmsMmsInfoTableColumns(): Array { + let resultColumns: Array = [ + mmsTable.messageInfo.msgId, + mmsTable.messageInfo.slotId, + mmsTable.messageInfo.receiverNumber, + mmsTable.messageInfo.senderNumber, + mmsTable.messageInfo.startTime, + mmsTable.messageInfo.endTime, + mmsTable.messageInfo.msgType, + mmsTable.messageInfo.smsType, + mmsTable.messageInfo.msgTitle, + mmsTable.messageInfo.msgContent, + mmsTable.messageInfo.msgState, - async searchSmsMessageByContent(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var resultColumns = this.buildSearchResultColumns(); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.like(mmsTable.messageInfo.msgContent, "%" + actionData.content + "%"); - condition.equalTo(mmsTable.messageInfo.msgType, 0); - if (actionData.numberType != null) { - condition.equalTo(mmsTable.messageInfo.smsType, actionData.numberType); - } - let resultList = []; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let result: LooseObject = {}; - this.dealBaseColumnsData(result, resultSet); - result.isCollect = resultSet.getString(resultSet.getColumnIndex("is_collect")); - result.sessionId = resultSet.getString(resultSet.getColumnIndex("session_id")); - result.groupId = resultSet.getString(resultSet.getColumnIndex("group_id")); - result.isSender = resultSet.getString(resultSet.getColumnIndex("is_sender")); - resultList.push(result); - } - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); - }).catch(error => { - HiLog.e(TAG, "searchSmsMessageByContent, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } + mmsTable.messageInfo.operatorServiceNumber, + mmsTable.messageInfo.msgCode, + mmsTable.messageInfo.isLock, + mmsTable.messageInfo.isRead, + mmsTable.messageInfo.isCollect, + mmsTable.messageInfo.sessionType, + mmsTable.messageInfo.retryNumber, + mmsTable.messageInfo.isSubsection, + mmsTable.messageInfo.sessionId, + mmsTable.messageInfo.groupId, + mmsTable.messageInfo.isSender, + mmsTable.messageInfo.isSendReport + ]; + return resultColumns; + } - buildSearchResultColumns() { - let basicColumns = this.buildBaseColumns(); - var resultColumns = [ - mmsTable.messageInfo.isCollect, - mmsTable.messageInfo.sessionId, - mmsTable.messageInfo.groupId, - mmsTable.messageInfo.isSender - ]; - return basicColumns.concat(resultColumns); - } + private buildSmsMmsInfoResult(resultSet): LooseObject { + let result: LooseObject = {}; + result.msgId = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgId))); + result.slotId = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.slotId))); + result.receiverNumber = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.receiverNumber)); + result.senderNumber = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.senderNumber)); + result.startTime = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.startTime)); + result.endTime = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.endTime)); + result.msgType = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgType))); + result.smsType = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.smsType))); + result.msgTitle = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgTitle)); + result.msgContent = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgContent)); + result.msgState = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgState))); - dealBaseColumnsData(result, resultSet) { - result.msgId = resultSet.getString(resultSet.getColumnIndex("msg_id")); - result.slotId = resultSet.getString(resultSet.getColumnIndex("slot_id")); - result.receiverNumber = resultSet.getString(resultSet.getColumnIndex("receiver_number")); - result.senderNumber = resultSet.getString(resultSet.getColumnIndex("sender_number")); - result.startTime = resultSet.getString(resultSet.getColumnIndex("start_time")); - result.endTime = resultSet.getString(resultSet.getColumnIndex("end_time")); - result.msgType = resultSet.getString(resultSet.getColumnIndex("msg_type")); - result.smsType = resultSet.getString(resultSet.getColumnIndex("sms_type")); - result.msgTitle = resultSet.getString(resultSet.getColumnIndex("msg_title")); - result.msgContent = resultSet.getString(resultSet.getColumnIndex("msg_content")); - result.msgState = resultSet.getString(resultSet.getColumnIndex("msg_state")); - } - - async insertMessageDetail(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.insert(managerUri, actionData.stringValue).then(data => { - callback(this.encapsulateReturnResult(common.int.SUCCESS, data)); - }).catch(error => { - HiLog.e(TAG, "insertMessageDetail, fail: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async updateLock(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var groupIds = this.groupIdToString(actionData.groupIds); - var condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.groupId, groupIds); - var stringValue = { - "is_lock": actionData.hasLock, - }; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.update(managerUri, condition, stringValue).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "updateLock, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - groupIdToString(groupIds) { - let ids = []; - groupIds.forEach(item => { - ids.push(item + ''); - }); - return ids; - } - - async updateCollect(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var groupIds = this.groupIdToString(actionData.groupIds); - var condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.groupId, groupIds); - var stringValue = { - "is_collect": actionData.hasCollect, - }; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.update(managerUri, condition, stringValue).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "updateCollect, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async deleteMessageByIds(actionData, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var msgIds = actionData.msgIds; - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.msgId, msgIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.delete(managerUri, condition); - } - - async deleteMessageByGroupIds(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var groupIds = this.groupIdToString(actionData.groupIds); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.groupId, groupIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.delete(managerUri, condition).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "deleteMessageByGroupIds, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async deleteMessageBySessionIds(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let threadIds = []; - for (let id of actionData.threadIds) { - let threadId = id + common.string.EMPTY_STR; - threadIds.push(threadId); - } - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.sessionId, threadIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.delete(managerUri, condition).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "deleteMessageBySessionIds, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async deleteMessageBySessionIdsAndLock(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let threadIds = this.groupIdToString(actionData.threadIds); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.equalTo(mmsTable.messageInfo.isLock, actionData.hasLock); - condition.in(mmsTable.messageInfo.sessionId, threadIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.delete(managerUri, condition).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "deleteMessageBySessionIdsAndLock, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async updateById(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var msgId = actionData.msgId; - let condition = new dataSharePredicates.DataSharePredicates(); - condition.equalTo(mmsTable.messageInfo.msgId, msgId); - var stringValue = { - "msg_state": actionData.sendStatus, - }; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.update(managerUri, condition, stringValue).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "updateById, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async markAllAsRead(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let threadIds = []; - for (let id of actionData.threadIds) { - let threadId = id + common.string.EMPTY_STR; - threadIds.push(threadId); - } - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.messageInfo.sessionId, threadIds); - var stringValue = { - "is_read": actionData.hasRead - }; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.update(managerUri, condition, stringValue).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "markAllAsRead, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async markAllToRead(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.equalTo(mmsTable.messageInfo.isRead, 0); - condition.equalTo(mmsTable.messageInfo.smsType, actionData.smsType); - var stringValue = { - "is_read": actionData.hasRead - }; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.update(managerUri, condition, stringValue).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "markAllToRead, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async queryMaxGroupId(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let resultColumns = [ - "maxGroupId" - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MAX_GROUP; - dataHelper.query(managerUri, condition, resultColumns, (err, resultSet) => { - HiLog.i(TAG, "queryMaxGroupId, query callback"); - let result: LooseObject = {}; - if (resultSet != undefined) { - if (resultSet.goToLastRow()) { - result.maxGroupId = resultSet.getString(0); - HiLog.d(TAG, "queryMaxGroupId, maxGroupId=" + result.maxGroupId); - } - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, result)); - }); - } - - saveImage(actionData, callback) { - var savedImageInfo = morkDataModel.saveImage(); - callback(this.encapsulateReturnResult(common.int.SUCCESS, savedImageInfo)); - } - - gotoShare(actionData, callback) { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - } - - queryFromGallery(actionData, callback) { - var pictureListFromGallery = morkDataModel.queryFromGallery(); - callback(this.encapsulateReturnResult(common.int.SUCCESS, pictureListFromGallery)); - } - - dealContractsTransmit(actionData, callback) { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - } - - async queryMessageThirty(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let timestamp = new Date().getTime(); - let lastTime = timestamp - 2592000000; - let resultColumns = [ - mmsTable.messageInfo.msgId, - mmsTable.messageInfo.sessionId - ]; - let condition = new dataSharePredicates.DataSharePredicates(); - condition.lessThan(mmsTable.messageInfo.endTime, lastTime); - condition.equalTo(mmsTable.messageInfo.smsType, actionData.numberType); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then((resultSet) => { - let mmsList = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let item: LooseObject = {}; - item.msgId = resultSet.getString(0); - item.sessionId = resultSet.getString(1); - mmsList.push(item); - } - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, mmsList)); - }).catch((err) => { - HiLog.e(TAG, "queryMessageThirty, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async statisticsUnreadNotify(actionData, callback, context?) { - let mmsContext = context ? context : globalThis.mmsContext; - if (actionData.mmsContext) { - mmsContext = actionData.mmsContext; - } - let dataHelper = await dataShare.createDataShareHelper(mmsContext, common.string.URI_MESSAGE_LOG); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.equalTo(mmsTable.messageInfo.isRead, 0); - condition.equalTo(mmsTable.messageInfo.smsType, 1); - let resultColumns = [ - mmsTable.messageInfo.msgId - ]; - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then((resultSet) => { - let count = 0; - if (resultSet != undefined) { - count = resultSet.rowCount; - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, count)); - }).catch((err) => { - HiLog.e(TAG, "statisticsUnreadNotify, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async searchMmsPartByContent(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let resultColumns = this.buildMmsPartResultColumns(); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.like(mmsTable.mmsPart.content, "%" + actionData.content + "%"); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MMS_PART; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - let resultList = this.dealMmsPartResult(resultSet); - callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); - }).catch(error => { - HiLog.e(TAG, "searchMmsPartByContent, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async queryMmsPart(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var resultColumns = this.buildMmsPartResultColumns(); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.mmsPart.msgId, actionData.msgIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MMS_PART; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - let resultList = this.dealMmsPartResult(resultSet); - callback(this.encapsulateReturnResult(common.int.SUCCESS, resultList)); - }).catch(error => { - HiLog.e(TAG, "queryMmsPart, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - buildMmsPartResultColumns() { - let resultColumns = [ - mmsTable.mmsPart.msgId, - mmsTable.mmsPart.groupId, - mmsTable.mmsPart.type, - mmsTable.mmsPart.locationPath, - mmsTable.mmsPart.content, - mmsTable.mmsPart.recordingTime, - mmsTable.mmsPart.partSize, - mmsTable.mmsPart.state - ]; - return resultColumns; - } - - dealMmsPartResult(resultSet) { - let resultList = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let result: LooseObject = {}; - result.msgId = resultSet.getString(0); - result.groupId = resultSet.getString(1); - result.type = resultSet.getString(2); - result.locationPath = resultSet.getString(3); - result.content = resultSet.getString(4); - result.recordingTime = resultSet.getString(5); - result.fileSize = resultSet.getString(6); - result.messageType = resultSet.getString(7); - resultList.push(result); - } - } - return resultList; - } - - async deleteMmsPartByGroupIds(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let groupIds = this.groupIdToString(actionData.groupIds); - let condition = new dataSharePredicates.DataSharePredicates(); - condition.in(mmsTable.mmsPart.groupId, groupIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MMS_PART; - dataHelper.delete(managerUri, condition).then((data) => { - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - }).catch((err) => { - HiLog.e(TAG, "deleteMmsPartByGroupIds, err: " + JSON.stringify(err.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async batchInsertMmsPart(actionData, callback, context?) { - for (let stringValue of actionData.batchMmsParts) { - this.insertMmsPart(actionData, stringValue, res => { - }, context); - } - callback(this.encapsulateReturnCode(common.int.SUCCESS)); - } - - async insertMmsPart(actionData, stringValue, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_MMS_PART; - dataHelper.insert(managerUri, stringValue).then(data => { - callback(this.encapsulateReturnResult(data, common.int.SUCCESS)); - }).catch(error => { - HiLog.e(TAG, "insertMmsPart, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async queryMessageLockBySessionId(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var resultColumns = [mmsTable.messageInfo.isLock]; - let condition = new dataSharePredicates.DataSharePredicates(); - let sessionId = actionData.threadId + common.string.EMPTY_STR; - condition.equalTo(mmsTable.messageInfo.sessionId, sessionId); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - let lockStatus = []; - if (resultSet != undefined) { - while (resultSet.goToNextRow()) { - let result: LooseObject = {}; - result.isLock = resultSet.getString(0); - lockStatus.push(result); - } - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, lockStatus)); - }).catch(error => { - HiLog.e(TAG, "queryMessageLockBySessionId, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } - - async queryGroupIdBySessionId(actionData, callback, context?) { - let dataHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, - common.string.URI_MESSAGE_LOG); - var resultColumns = [mmsTable.messageInfo.groupId]; - let condition = new dataSharePredicates.DataSharePredicates(); - let threadIds = this.groupIdToString(actionData.threadIds); - condition.in(mmsTable.messageInfo.sessionId, threadIds); - let managerUri = common.string.URI_MESSAGE_LOG + common.string.URI_MESSAGE_INFO_TABLE; - dataHelper.query(managerUri, condition, resultColumns).then(resultSet => { - let groupIds = []; - if (resultSet != undefined) { - resultSet.goToFirstRow(); - do { - let groupId = resultSet.getString(0); - groupIds.push(groupId); - } while (resultSet.goToNextRow()); - } - callback(this.encapsulateReturnResult(common.int.SUCCESS, groupIds)); - }).catch(error => { - HiLog.e(TAG, "queryGroupIdBySessionId, error: " + JSON.stringify(error.message)); - callback(this.encapsulateReturnCode(common.int.FAILURE)); - }); - } + result.operatorServiceNumber = resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.operatorServiceNumber)); + result.msgCode = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.msgCode))); + result.isLock = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isLock))); + result.isRead = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isRead))); + result.isCollect = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isCollect))); + result.sessionType = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.sessionType))); + result.retryNumber = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.retryNumber))); + result.isSubsection = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isSubsection))); + result.sessionId = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.sessionId))); + result.groupId = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.groupId))); + result.isSender = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isSender))); + result.isSendReport = Number(resultSet.getString(resultSet.getColumnIndex(mmsTable.messageInfo.isSendReport))); + return result; + } } \ No newline at end of file diff --git a/entry/src/main/ets/model/SettingsModel.ets b/entry/src/main/ets/model/SettingsModel.ets index 6fc7226..239001a 100644 --- a/entry/src/main/ets/model/SettingsModel.ets +++ b/entry/src/main/ets/model/SettingsModel.ets @@ -41,10 +41,10 @@ export default class SettingModel extends BaseModel { getAdvancedPageSwitchValue(callback) { let result: LooseObject = { - deliveryReportSwitch: false, - autoRetrieveMmsSwitch: false, - recallMessageSwitch: false, - autoDeleteInfoSwitch: false + "deliveryReportSwitch": false, + "autoRetrieveMmsSwitch": false, + "recallMessageSwitch": false, + "autoDeleteInfoSwitch": false }; result.deliveryReportSwitch = MmsPreferences.getInstance().getValueOfDeliveryReportSwitch(); result.autoRetrieveMmsSwitch = MmsPreferences.getInstance().getValueOfAutoRetrieveMmsSwitch(); diff --git a/entry/src/main/ets/model/TransmitMsgDataSource.ets b/entry/src/main/ets/model/TransmitMsgDataSource.ets index a517927..2a41ad0 100644 --- a/entry/src/main/ets/model/TransmitMsgDataSource.ets +++ b/entry/src/main/ets/model/TransmitMsgDataSource.ets @@ -22,7 +22,6 @@ export default class TransmitMsgDataSource extends BaseDataSource { private mmsList: Array = []; public totalCount(): number { - HiLog.i(TAG, "totalCount is %s", this.mmsList.length); return this.mmsList.length; } diff --git a/entry/src/main/ets/pages/conversation/conversation.ets b/entry/src/main/ets/pages/conversation/conversation.ets index 3ef5ceb..ff407a6 100644 --- a/entry/src/main/ets/pages/conversation/conversation.ets +++ b/entry/src/main/ets/pages/conversation/conversation.ets @@ -98,6 +98,7 @@ export struct Conversation { }); emitter.on(simCardService.SLOTID_CHANGE_EVENT, () => { this.slotId = MmsPreferences.getInstance().getSelectedSlotId(); + console.log("receive SLOTID_CHANGE_EVENT, this.slotId: " + this.slotId); }); } @@ -243,14 +244,14 @@ export struct Conversation { .fontColor($r("sys.color.ohos_id_color_text_primary")) .fontWeight(FontWeight.Medium) } else { - Text(this.mConversationCtrl.strContactsName) + Text(this.mConversationCtrl.strContactsName.replace(/\s*/g,"")) .maxLines(1) .textOverflow({ overflow: TextOverflow.Ellipsis }) .fontSize(20) .fontColor($r("sys.color.ohos_id_color_text_primary")) .fontWeight(FontWeight.Medium) .lineHeight(28) - if (this.mConversationCtrl.strContactsName !== + if (this.mConversationCtrl.strContactsName.replace(/\s*/g,"") !== this.mConversationCtrl.strContactsNumberFormat) { Text(this.mConversationCtrl.strContactsNumberFormat) .maxLines(1) @@ -791,7 +792,7 @@ export struct Conversation { this.dialogController.open() this.mConversationCtrl.isSelectStatus = !this.mConversationCtrl.isSelectStatus this.mConversationCtrl.isMessageCheckAll = false - this.mConversationCtrl.cancleCheckedAll() + this.mConversationCtrl.cancelCheckedAll() }) if (this.mConversationCtrl.hasReport) { @@ -935,7 +936,6 @@ struct bubbleText { build() { Row() { Text(this.content) - .onDragStart(() => {}) .fontSize(16) .lineHeight(21) .padding({ left: 12, right: 12, top: 8, bottom: 8 }) diff --git a/entry/src/main/ets/pages/conversation/conversationController.ets b/entry/src/main/ets/pages/conversation/conversationController.ets index dc72937..5536a0b 100644 --- a/entry/src/main/ets/pages/conversation/conversationController.ets +++ b/entry/src/main/ets/pages/conversation/conversationController.ets @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,13 +14,14 @@ */ import router from "@system.router"; import Prompt from "@system.prompt"; -import commonEvent from "@ohos.commonEvent"; import emitter from '@ohos.events.emitter'; + import HiLog from "../../utils/HiLog" import common from "../../data/commonData" import commonEvent from "@ohos.commonEventManager"; -import conversationService from "../../service/ConversationService"; -import conversationListService from "../../service/ConversationListService"; +import ContactsService from '../../service/ContactsService'; +import ConversationService from "../../service/ConversationService"; +import ConversationListService from "../../service/ConversationListService"; import LooseObject from "../../data/LooseObject" import commonService from "../../service/CommonService"; import settingService from "../../service/SettingService"; @@ -144,8 +144,8 @@ export default class ConversationController { slideDistance: number = 0; // Start point coordinate of the slide slideStartPoint: LooseObject = { - x: 0, - y: 0 + "x": 0, + "y": 0 }; // Whether to slide up isTabSlideUp: number = 0; @@ -183,7 +183,7 @@ export default class ConversationController { // Deleting a Details Page hasDetailDelete: boolean = false; // Whether a contact exists - hasExitContract: boolean = false; + hasExitContact: boolean = false; // Create a page for fetching and sending. isNewRecallMessagesFlag: boolean = false; // Recording animation @@ -239,7 +239,7 @@ export default class ConversationController { this.initRouterData(); this.initData(); if (this.hasDouble) { - this.initNewPageContracts(); + this.initNewPageContacts(); this.hasDouble = false; } // Obtains the actual data. You do not need to query the data when creating new data. @@ -248,10 +248,11 @@ export default class ConversationController { }); this.scroller.scrollToIndex(this.mmsList.length - 1) } - NotificationService.getInstance().cancelMessageNotify({ - threadIds: this.threadId, - hasRead: 0 - }, res => {}); + let actionData: LooseObject = {}; + actionData.threadId = this.threadId; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + NotificationService.getInstance().updateBadgeNumber(); } onShow() { @@ -274,7 +275,7 @@ export default class ConversationController { } initData() { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip2", + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip2", this.selectDeleteMsgCount ); this.tabTextList = [ @@ -320,8 +321,8 @@ export default class ConversationController { this.mmsList = []; } - initNewPageContracts() { - let transmitContracts = []; + initNewPageContacts() { + let transmitContacts = []; if (this.strContactsNumber) { let contactsNames = this.strContactsName.split(","); let telephones = this.strContactsNumber.split(","); @@ -338,10 +339,10 @@ export default class ConversationController { } item.headImage = common.string.EMPTY_STR; item.select = false; - transmitContracts.push(item); + transmitContacts.push(item); } } - this.commonCtrl.paramContact.transmitContracts = transmitContracts; + this.commonCtrl.paramContact.transmitContacts = transmitContacts; this.commonCtrl.paramContact.isSelectContact = false; this.commonCtrl.paramContact.isNewRecallMessagesFlag = false; } @@ -360,7 +361,7 @@ export default class ConversationController { this.draftContent = routerParams.draftContent == undefined ? '' : routerParams.draftContent; this.searchContent = routerParams.searchContent == undefined ? '' : routerParams.searchContent; this.isNewMsg = routerParams.isNewMsg == undefined ? false : routerParams.isNewMsg; - this.portraitColor = AvatarColor.background.Color[Math.abs(parseInt(this.threadId, 10)) % 6]; + this.portraitColor = AvatarColor.background.Color[Math.abs(this.threadId) % 6]; this.photoFirstNameDeal(this.strContactsName); this.dealSpecialPhoneNumber(); } @@ -395,7 +396,7 @@ export default class ConversationController { titleBarCancel() { // Cancel button - this.cancleCheckedAll(); + this.cancelCheckedAll(); this.setSelectStatus(false); } @@ -403,7 +404,7 @@ export default class ConversationController { if (this.isSelectStatus) { // Multi-choice status this.isSelectStatus = false; - this.cancleCheckedAll(); + this.cancelCheckedAll(); return true; } let source = this.getMmsSource(); @@ -419,30 +420,29 @@ export default class ConversationController { if (this.isNewMsg && this.isDraft) { if ((this.selectContacts.length == 0 && this.receiveContactValue == common.string.EMPTY_STR) || (this.textValue == common.string.EMPTY_STR && source.length == 0)) { - conversationListService.deleteMessageBySessionId([this.threadId]); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().deleteSessionByCondition(condition, null, null); this.deleteDraftData(); } } - let hasReport = settingService.judgeIsDeliveryReport(this.isEditMms); - let hasAttachment = commonService.judgeIsAttachment(source); let actionData: LooseObject = {}; - actionData = { - slotId: MmsPreferences.getInstance().getSendMessageSlotId(), - threadId: this.threadId, - receiveContactValue: common.string.EMPTY_STR, - selectContacts: [], - content: this.textValue, - isReceive: false, - ownNumber: common.string.EMPTY_STR, - isSender: 0, - hasDraft: 1, - hasReport: hasReport, - isMms: this.isEditMms, - mmsSource: source, - groupId: this.draftGroupId, - messageType: this.messageType, - hasAttachment: hasAttachment - } + actionData.slotId = this.slotId; + actionData.threadId = this.threadId; + actionData.receiveContactValue = common.string.EMPTY_STR; + actionData.selectContacts = []; + actionData.content = this.textValue; + actionData.isReceive = false; + actionData.ownNumber = common.string.EMPTY_STR; + actionData.isSender = common.is_sender.NO; + actionData.hasDraft = common.has_draft.HAVE; + actionData.hasReport = settingService.judgeIsDeliveryReport(this.isEditMms); + actionData.isMms = this.isEditMms; + actionData.mmsSource = source; + actionData.groupId = this.draftGroupId; + actionData.messageType = this.messageType; + actionData.hasAttachment = commonService.judgeIsAttachment(source); + actionData.isDraft = this.isDraft; // The draft does not exist or the draft needs to be updated. The draft data on the new page needs to be saved. if (this.textValue != common.string.EMPTY_STR || source.length !== 0) { actionData.isNewMsg = this.isNewMsg; @@ -450,7 +450,7 @@ export default class ConversationController { // If the selected contact is not empty if (this.selectContacts.length > 0) { actionData.selectContacts = this.selectContacts; - conversationListService.insertSessionDraft(actionData, callback); + ConversationListService.getInstance().insertSessionDraft(actionData, callback, null); } // If the recipient input field is not empty else if (this.receiveContactValue != common.string.EMPTY_STR) { @@ -458,11 +458,13 @@ export default class ConversationController { // If the number entered in the text box is invalid, the system does not save the draft when the // Back key is pressed. if (this.isPhoneNumber(this.receiveContactValue)) { - conversationListService.insertSessionDraft(actionData, callback); + ConversationListService.getInstance().insertSessionDraft(actionData, callback, null); } else if (this.isDraft) { // If the current draft is in draft state and the entered number is invalid, the current draft // is deleted. - conversationListService.deleteMessageBySessionId([this.threadId]); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().deleteSessionByCondition(condition, null, null); this.deleteDraftData(); callback(); } else { @@ -474,7 +476,7 @@ export default class ConversationController { } else { // This is not a new scenario. actionData.telephone = this.strContactsNumber; - conversationListService.insertSessionDraft(actionData, callback); + ConversationListService.getInstance().insertSessionDraft(actionData, callback, null); } } else if (!this.isNewMsg && this.isDraft) { // If a draft exists, perform the following operations: @@ -488,31 +490,29 @@ export default class ConversationController { // When the draft logic is set, the text content is empty and the page is not created, the session list data needs // to be updated. dealSessionDraft(source) { + let valueBucket: LooseObject = { + "content": common.string.EMPTY_STR, + "has_draft": common.has_draft.NO, + "time": new Date().getTime(), + "has_mms": common.has_mms.NO, + "has_attachment": common.has_attachment.NO + } // Query the last content in the list - let length = this.mmsList.length; - let item = this.mmsList[length - 1]; - // Updating list data - let threadIds = [this.threadId]; - let time = new Date(); - let content = item.content; - let hasAttachment = false; - if (item.isMsm) { - content = commonService.getMmsContent(item.mms); - hasAttachment = commonService.judgeIsAttachment(source); + let length: number = this.mmsList.length; + if (length > 0) { + let item: LooseObject = this.mmsList[length - 1]; + valueBucket.content = item.content; + valueBucket.has_mms = item.isMsm ? common.has_mms.HAVE : common.has_mms.NO; + valueBucket.has_attachment = item.isMsm ? common.has_attachment.HAVE : common.has_attachment.NO; } - let valueBucket = { - "content": item.content, - "has_draft": 0, - "time": time.getTime(), - "has_mms": item.isMsm ? 1 : 0, - "has_attachment": hasAttachment ? 1 : 0 - } - conversationListService.updateById(threadIds, valueBucket); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().updateSessionByCondition(condition, valueBucket, null, null); this.deleteDraftData(); this.isDraft = false; } - cancleCheckedAll() { + cancelCheckedAll() { for (let element of this.mmsList) { element.isCbChecked = false; } @@ -679,7 +679,7 @@ export default class ConversationController { this.strContactsName = routerParams.strContactsName; this.strContactsNumber = routerParams.strContactsNumber; this.strContactsNumberFormat = routerParams.strContactsNumberFormat; - this.initNewPageContracts(); + this.initNewPageContacts(); } } @@ -701,7 +701,7 @@ export default class ConversationController { } generalTransmitSend() { - let transmitSource = router.getParams().transmitSource; + let transmitSource: Array = >router.getParams().transmitSource; let isSource = router.getParams().isContainerOriginSource; this.canSendMessage = false; for (let element of transmitSource) { @@ -731,12 +731,12 @@ export default class ConversationController { this.isSendStatus = true; // Initialize the data to be sent. this.initSendSms(content, msgUriPath, isMms, mmsSource); - let actionData: LooseObject = { - slotId: MmsPreferences.getInstance().getSendMessageSlotId(), - destinationHost: this.strContactsNumber, - content: content, - isEditMms: isMms - }; + this.slotId = MmsPreferences.getInstance().getSendMessageSlotId(); + let actionData: LooseObject = {}; + actionData.slotId = this.slotId; + actionData.destinationHost = this.strContactsNumber; + actionData.content = content; + actionData.isEditMms = isMms; this.dealNewRecallMessagesFlag(this.mmsList); HiLog.i(TAG, 'sendSms send start'); // Cancel Sending and Normal Sending Methods @@ -794,7 +794,7 @@ export default class ConversationController { fillmmsEditListTemp(msgUriPath, isMsm) { let mmsEditListTemp = []; if (this.recallMessagesFlag && isMsm) { - let item = {}; + let item: LooseObject = {}; item.type = common.MSG_ITEM_TYPE.IMAGE; item.uriPath = msgUriPath; mmsEditListTemp.push(item); @@ -862,7 +862,7 @@ export default class ConversationController { // Delete a dialog box. deleteDialogShow() { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip1"); + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip1"); let item = this.mmsList[this.mmsIndex]; item.isShowMsgLongMenu = false HiLog.i(TAG, "deleteDialogShow, isShowMsgLongMenu=" + item.isShowMsgLongMenu); @@ -981,14 +981,14 @@ export default class ConversationController { groupIds.push(item.groupId); } this.isSelectLockMsg = false; - this.cancleCheckedAll(); + this.cancelCheckedAll(); if (groupIds.length > 0) { this.deleteMessageByGroupIds(groupIds); // Check whether the length of the deleted list is 0. if (this.mmsList.length === 0 && this.textValue === common.string.EMPTY_STR) { - router.back(); globalThis.needToUpdate = true; this.deleteMessageById(this.threadId); + router.back(); } else { this.updateSessionLock(false); this.updateLastItemContent(); @@ -997,12 +997,15 @@ export default class ConversationController { // After the deletion is complete, check whether all data is deleted. } - deleteMessageByGroupIds(groupIds) { - let actionData = { - groupIds: groupIds, - }; + deleteMessageByGroupIds(groupIds): void { + let actionData: LooseObject = {}; + if (groupIds.length == 1) { + actionData.groupId = groupIds[0]; + } else { + actionData.groupIds = groupIds; + } // Invoke the database deletion method. - conversationService.deleteMessageByGroupIds(actionData); + ConversationService.getInstance().deleteSmsMmsInfoByCondition(actionData, null, null); } // Updates the lock status of the session list. @@ -1025,16 +1028,17 @@ export default class ConversationController { return; } } - // If it is locked, update the status to locked. - conversationListService.updateById(threadIds, valueBucket); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().updateSessionByCondition(condition, valueBucket, null, null); } updateLastItemContent() { - let actionData = { - mmsList: this.mmsList, - threadId: this.threadId, + let actionData: LooseObject = { + "mmsList": this.mmsList, + "threadId": this.threadId, }; - conversationListService.updateLastItemContent(actionData); + ConversationListService.getInstance().updateLastItemContent(actionData, null, null); } deleteMessageById(threadId) { @@ -1043,7 +1047,7 @@ export default class ConversationController { let actionData = { threadIds: threadIds, }; - conversationListService.deleteMessageById(actionData); + ConversationListService.getInstance().deleteMessageById(actionData, null, null); } clickGroupDelete() { @@ -1051,28 +1055,26 @@ export default class ConversationController { return; } if (this.selectDeleteMsgCount == 1) { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip1"); + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip1"); } else if (this.selectDeleteMsgCount == this.mmsList.length) { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip3"); + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip3"); } else { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip2", this.selectDeleteMsgCount); + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip2", this.selectDeleteMsgCount); } this.hasLockMsg = (this.mmsList.some((element, index) => element.isCbChecked && element.isLock)); } // Check whether a contact exists. judgeContactExists() { - let telephones = [this.strContactsNumber]; - let actionData = { - telephones: telephones - }; - conversationService.judgeContactExists(actionData, result => { - this.hasExitContract = result; - }); + let actionData: LooseObject = {}; + actionData.telephones = [this.strContactsNumber]; + ContactsService.getInstance().judgeContactExist(actionData, result => { + this.hasExitContact = result; + }, globalThis.mmsContext); if (this.strContactsName == common.string.EMPTY_STR) { - this.hasExitContract = false; + this.hasExitContact = false; } else { - this.hasExitContract = true; + this.hasExitContact = true; } } @@ -1092,7 +1094,7 @@ export default class ConversationController { actionData.threadId = threadId; } actionData.contactsNum = this.contactsNum; - conversationService.queryMessageDetail(actionData, result => { + ConversationService.getInstance().queryMessageDetail(actionData, result => { if (result.code == common.int.SUCCESS) { this.initIsShowMsgLongMenu(result); this.dealMessageDetailTime(result); @@ -1108,7 +1110,7 @@ export default class ConversationController { this.setDraft(); } this.deleteDraftData(); - }); + }, null); if (callback) { callback(); } @@ -1236,7 +1238,7 @@ export default class ConversationController { } dealDraftData(item) { - this.isDraft = true; +// this.isDraft = true; this.draftContent = item.content; this.draftGroupId = item.groupId; if (item.isMsm) { @@ -1256,20 +1258,18 @@ export default class ConversationController { } updateDetail(threadId, sendResult) { - let sendResults = []; + let sendResults: Array = []; sendResults.push(sendResult); - let actionData = { - sendResults: sendResults, - threadId: threadId - } - conversationService.updateSessionAndDetail(actionData); - let sendStatus = sendResult.sendStatus - let deliveryReportSwitch = MmsPreferences.getInstance().getValueOfDeliveryReportSwitch(); - HiLog.i(TAG, "updateDetail, sendStatus=" + sendStatus + ", deliveryReportSwitch=" + deliveryReportSwitch) + let actionData: LooseObject = {}; + actionData.sendResults = sendResults; + actionData.threadId = threadId; + ConversationService.getInstance().updateSessionAndDetail(actionData); + let sendStatus: number = sendResult.sendStatus; + let deliveryReportSwitch: string = MmsPreferences.getInstance().getValueOfDeliveryReportSwitch(); + HiLog.i(TAG, "updateDetail, sendStatus=" + sendStatus + ", deliveryReportSwitch=" + deliveryReportSwitch); if ((deliveryReportSwitch == common.DELIVERY_REPORTS.SMS_AND_MMS || - deliveryReportSwitch == common.DELIVERY_REPORTS.SMS) && - sendStatus == common.int.SEND_MESSAGE_SUCCESS) { - let msg = this.strContactsNumber + " 已收到消息!" + deliveryReportSwitch == common.DELIVERY_REPORTS.SMS) && sendStatus == common.int.SEND_MESSAGE_SUCCESS) { + let msg: string = this.strContactsNumber + " 已收到消息!" this.showToast(msg) } } @@ -1333,7 +1333,7 @@ export default class ConversationController { }); } - getSendMessageId(initDatas, telephone) { + getSendMessageId(initDatas, telephone): number { for (let initData of initDatas) { if (initData.telephone == telephone) { return initData.id; @@ -1354,15 +1354,15 @@ export default class ConversationController { let content: string = actionData.content; for (let i = 0; i < sendNumbers.length; i++) { let params: LooseObject = { - slotId: actionData.slotId, - destinationHost: sendNumbers[i], - content: content, + "slotId": actionData.slotId, + "destinationHost": sendNumbers[i], + "content": content, }; - let id = this.getSendMessageId(initDatas, sendNumbers[i]); + let id: number = this.getSendMessageId(initDatas, sendNumbers[i]); let sendResult: LooseObject = { - id: id, - telephone: sendNumbers[i], - content: content, + "id": id, + "telephone": sendNumbers[i], + "content": content, } if (!item.isMsm) { this.dealSmsSendResult(params, item, sendResult); @@ -1377,30 +1377,27 @@ export default class ConversationController { let insertSendResults: Array = []; for (let i = 0; i < sendNumbers.length; i++) { let sendResult: LooseObject = { - slotId: actionData.slotId, - telephone: sendNumbers[i], - content: actionData.content, - sendStatus: common.int.SEND_MESSAGE_SENDING + "slotId": actionData.slotId, + "telephone": sendNumbers[i], + "content": actionData.content, + "sendStatus": common.int.SEND_MESSAGE_SENDING } if (item.isMsm) { sendResult.content = commonService.getMmsContent(item.mmsSource); } insertSendResults.push(sendResult); } - let hasReport: number = settingService.judgeIsDeliveryReport(item.isMsm) ? 1 : 0; - let hasAttachment: boolean = commonService.judgeIsAttachment(item.mmsSource); - let actionData_: LooseObject = { - sendResults: insertSendResults, - isReceive: false, - ownNumber: common.string.EMPTY_STR, - isSender: 0, - hasDraft: this.isDraft, - hasReport: hasReport, - isMms: item.isMsm, - mmsSource: item.mmsSource, - hasAttachment: hasAttachment - } - conversationService.insertSessionAndDetail(actionData_, callback); + let actionData_: LooseObject = {}; + actionData_.sendResults = insertSendResults; + actionData_.isReceive = false; + actionData_.ownNumber = common.string.EMPTY_STR; + actionData_.isSender = common.is_sender.NO; + actionData_.hasDraft = this.isDraft; + actionData_.hasReport = settingService.judgeIsDeliveryReport(item.isMsm) ? 1 : 0; + actionData_.isMms = item.isMsm; + actionData_.mmsSource = item.mmsSource; + actionData_.hasAttachment = commonService.judgeIsAttachment(item.mmsSource); + ConversationService.getInstance().insertSessionAndDetail(actionData_, callback, globalThis.mmsContext); } changeReceiveContactValue(value) { @@ -1696,10 +1693,12 @@ export default class ConversationController { // Processing the sent result if (this.threadId != result.rowId) { // When modifying the recipient information, click Send and delete the session before the modification. - conversationListService.deleteMessageBySessionId([this.threadId]); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().deleteSessionByCondition(condition, null, null); } this.threadId = result.rowId; - this.portraitColor = AvatarColor.background.Color[Math.abs(parseInt(this.threadId, 10)) % 6]; + this.portraitColor = AvatarColor.background.Color[Math.abs(this.threadId) % 6]; item.groupId = result.groupId; item.id = result.initDatas[0].id; this.refresh = !this.refresh @@ -1749,18 +1748,16 @@ export default class ConversationController { sendDataRefresh() { this.isSendStatus = true; - // Send Text + this.slotId = MmsPreferences.getInstance().getSendMessageSlotId(); if (this.textValue != common.string.EMPTY_STR || this.mmsEditList.length != 0 || this.textareaDatasource.length != 0) { this.initSendItem(); } - this.slotId = MmsPreferences.getInstance().getSendMessageSlotId(); - let actionData: LooseObject = { - slotId: this.slotId, - destinationHost: this.strContactsNumber, - content: this.textValue, - isEditMms: this.isEditMms - }; + let actionData: LooseObject = {}; + actionData.slotId = this.slotId; + actionData.destinationHost = this.strContactsNumber; + actionData.content = this.textValue; + actionData.isEditMms = this.isEditMms; // Real SMS Sending this.sendInterval(actionData, this.mmsList); this.textValue = common.string.EMPTY_STR; @@ -1828,23 +1825,26 @@ export default class ConversationController { if (telephone == common.string.EMPTY_STR) { return; } - let number = telephoneUtil.dealTelephoneSort(telephone); - conversationListService.querySessionByTelephone(number, res => { - HiLog.i(TAG, "queryOldMessageList, querySessionByTelephone res.response.id: " + res.response.id) + let number: string = telephoneUtil.dealTelephoneSort(telephone); + ConversationListService.getInstance().querySessionByTelephone(number, res => { + HiLog.i(TAG, "queryOldMessageList, querySessionByTelephone res.response.id: " + res.response.id); if (res.code == common.int.SUCCESS && res.response.id > 0) { if (this.threadId != res.response.id) { // When modifying the recipient information, click Send and delete the session before the // modification. - conversationListService.deleteMessageBySessionId([this.threadId]); + let condition: LooseObject = {}; + condition.threadId = this.threadId; + ConversationListService.getInstance().deleteSessionByCondition(condition, null, null); } + this.isDraft = res.response.hasDraft; this.threadId = res.response.id; - this.portraitColor = AvatarColor.background.Color[Math.abs(parseInt(this.threadId, 10)) % 6]; + this.portraitColor = AvatarColor.background.Color[Math.abs(this.threadId) % 6]; this.queryMessageDetail(telephone, res.response.id, callback); - this.scroller.scrollToIndex(this.mmsList.length - 1) + this.scroller.scrollToIndex(this.mmsList.length - 1); } else { callback(); } - }); + }, null); } initNewSelectContacts(selectContacts) { @@ -1999,19 +1999,16 @@ export default class ConversationController { this.queryMessageDetail(this.strContactsNumber, this.threadId, () => { }); this.scroller.scrollToIndex(this.mmsList.length - 1); - let valueBucket: LooseObject = { - "unread_count": 0, - }; - let actionData: LooseObject = { - threadIds: [this.threadId], - hasRead: 0, - valueBucket: valueBucket - }; - NotificationService.getInstance().cancelMessageNotify(actionData, res => { - actionData.hasRead = 1; - conversationListService.markAllAsRead(actionData); - }); - this.notifySlotIdChange(this.mmsList[this.mmsList.length - 1]); + let actionData: LooseObject = {}; + actionData.threadId = this.threadId; + actionData.hasRead = common.is_read.UN_READ; + ConversationListService.getInstance().markAllToRead(actionData); + NotificationService.getInstance().cancelMessageNotify(actionData); + NotificationService.getInstance().updateBadgeNumber(); + let lastItem: LooseObject = this.mmsList[this.mmsList.length - 1]; + if (lastItem != null && lastItem.subId != null) { + this.notifySlotIdChange(lastItem.subId); + } }, 500); } @@ -2024,15 +2021,10 @@ export default class ConversationController { } } - notifySlotIdChange(item: LooseObject): void { - if (item == null || item.subId == null) { - HiLog.w(TAG, "notifySlotIdChange, get item.subId error!"); - return; - } - let slotId: number = item.subId; - if (MmsPreferences.getInstance().haveMultiSimCardReady() - && MmsPreferences.getInstance().getSelectedSlotId() != slotId) { + notifySlotIdChange(slotId: number): void { + if (MmsPreferences.getInstance().getSelectedSlotId() != slotId) { MmsPreferences.getInstance().setValueToMap(common.string.KEY_OF_SELECTED_SLOTID, slotId); + HiLog.i(TAG, "notifySlotIdChange, emit slotId: " + slotId); emitter.emit(simCardService.SLOTID_CHANGE_EVENT, { data: { "slotId": slotId @@ -2059,7 +2051,7 @@ export default class ConversationController { break; case 3: // lock - this.lock(); + //this.lock(); break; case 4: // Show Details @@ -2067,7 +2059,7 @@ export default class ConversationController { break; case 5: // Unlock - this.unlock(); + //this.unlock(); break; case 6: // View Reports @@ -2095,11 +2087,9 @@ export default class ConversationController { share() { for (let i = 0; i < this.mmsList.length; i++) { if (this.mmsList[i].isCbChecked == true) { - var actionData: LooseObject = {}; + let actionData: LooseObject = {}; actionData.content = this.mmsList[i].content; - conversationService.gotoShare(actionData, function (data) { - HiLog.i(TAG, "share, gotoShare callback"); - }); + ConversationService.getInstance().gotoShare(actionData, null, null); } } } @@ -2111,44 +2101,6 @@ export default class ConversationController { }) } - lock() { - this.updateLock(true); - } - - unlock() { - this.updateLock(false); - } - - updateLock(isLock) { - // Select Content Lock - let groupIds = []; - for (let element of this.mmsList) { - if (element.isCbChecked) { - element.isLock = isLock; - groupIds.push(element.groupId); - } - } - let hasLock = isLock ? 1 : 0; - let actionData: LooseObject = {}; - actionData = { - groupIds: groupIds, - hasLock: hasLock - }; - let that = this; - conversationService.updateLock(actionData, function (result) { - if (result.code == common.int.SUCCESS) { - // Multi-Select Status Off - that.isSelectStatus = false; - that.cancleCheckedAll(); - HiLog.i(TAG, "updateLock, Success"); - } else { - HiLog.w(TAG, "updateLock, failed"); - } - }); - // Update Lock Status - this.updateSessionLock(isLock); - } - showDetails() { for (let index = 0; index < this.mmsList.length; index++) { if (this.mmsList[index].isCbChecked == true) { @@ -2187,11 +2139,11 @@ export default class ConversationController { saveImage() { var actionData: LooseObject = {}; - actionData.threadId = this.mmsList[this.mmsIndex].threadId; - actionData.pduId = this.mmsList[this.mmsIndex].pduId; - conversationService.saveImage(actionData, result => { + actionData.threadId = this.mmsList[this.mmsIndex]?.threadId; + actionData.pduId = this.mmsList[this.mmsIndex]?.pduId; + ConversationService.getInstance().saveImage(actionData, result => { this.showToast(result); - }); + }, null); } showVcarDetail(mmsIndex) { @@ -2201,7 +2153,7 @@ export default class ConversationController { exitMultiselect() { // Exit the multi-selection state. this.isSelectStatus = false; - this.cancleCheckedAll(); + this.cancelCheckedAll(); } longPressMore(e) { @@ -2212,7 +2164,7 @@ export default class ConversationController { break; case 1: // New Contact - this.createNewContract(this.strContactsNumber); + this.createNewContact(this.strContactsNumber); break; case 2: // Save to Existing Contacts @@ -2238,7 +2190,7 @@ export default class ConversationController { // Delete deleteDetail() { if (this.mmsList.length == 1) { - this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_tip3"); + this.strMsgDeleteDialogTip = $r("app.string.msg_delete_dialog_con_tip3"); } else { this.hasDetailDelete = false; this.isSelectStatus = true; @@ -2246,36 +2198,36 @@ export default class ConversationController { } // New Contact - createNewContract(number) { + createNewContact(number) { var actionData: LooseObject = {}; actionData.phoneNumber = number; - actionData.pageFlag = common.contractPage.PAGE_FLAG_SAVE_CONTACT; - this.jumpToContract(actionData); + actionData.pageFlag = common.contactPage.PAGE_FLAG_SAVE_CONTACT; + this.jumpToContact(actionData); } // Edit Before Call callEditor(number) { var actionData: LooseObject = {}; actionData.phoneNumber = number; - actionData.pageFlag = common.contractPage.PAGE_FLAG_EDIT_BEFORE_CALLING; - this.jumpToContract(actionData); + actionData.pageFlag = common.contactPage.PAGE_FLAG_EDIT_BEFORE_CALLING; + this.jumpToContact(actionData); } // Save to Existing Contacts existingContact(number) { var actionData: LooseObject = {}; actionData.phoneNumber = number; - actionData.pageFlag = common.contractPage.PAGE_FLAG_SAVE_EXIST_CONTACT; - this.jumpToContract(actionData); + actionData.pageFlag = common.contactPage.PAGE_FLAG_SAVE_EXIST_CONTACT; + this.jumpToContact(actionData); } // Switching to the Contacts app - jumpToContract(actionData) { - let str = commonService.commonContractParam(actionData); + jumpToContact(actionData) { + let str = commonService.commonContactParam(actionData); globalThis.mmsContext.startAbility(str).then((data) => { - HiLog.i(TAG, "jumpToContract, startAbility Success"); + HiLog.i(TAG, "jumpToContact, startAbility Success"); }).catch((error) => { - HiLog.e(TAG, "jumpToContract, failed. Cause: " + JSON.stringify(error.message)); + HiLog.e(TAG, "jumpToContact, failed. Cause: " + JSON.stringify(error.message)); }) } @@ -2283,9 +2235,9 @@ export default class ConversationController { titleBarAvatar() { var actionData = { phoneNumber: this.strContactsNumber, - pageFlag: common.contractPage.PAGE_FLAG_CONTACT_DETAILS + pageFlag: common.contactPage.PAGE_FLAG_CONTACT_DETAILS }; - this.jumpToContract(actionData); + this.jumpToContact(actionData); } clickCall() { @@ -2319,6 +2271,9 @@ export default class ConversationController { let telephone = common.string.EMPTY_STR; this.textValue = common.string.EMPTY_STR; this.setCanSendMessage(selectContacts, receiveContactValue) + if(receiveContactValue != this.strContactsName && router.getParams().isDraft == undefined) { + this.isDraft = false; + } if (hasBlur && receiveContactValue != common.string.EMPTY_STR) { let index = -1; for (let i = 0; i < selectContacts.length; i++) { @@ -2366,7 +2321,8 @@ export default class ConversationController { telephone = telephone.substring(0, telephone.length - 1); } if (!hasBlur && telephone != "") { - this.queryOldMessageList(telephone, null); + this.queryOldMessageList(telephone, () => { + }); } } diff --git a/entry/src/main/ets/pages/conversationlist/conversationListController.ets b/entry/src/main/ets/pages/conversationlist/conversationListController.ets index 00afdad..7afc61f 100644 --- a/entry/src/main/ets/pages/conversationlist/conversationListController.ets +++ b/entry/src/main/ets/pages/conversationlist/conversationListController.ets @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,26 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import common from "../../data/commonData" import router from "@system.router"; import commonEvent from "@ohos.commonEventManager"; +import dataShare from "@ohos.data.dataShare"; + +import common from "../../data/commonData" import DateUtil from "../../utils/DateUtil"; -import featureAbility from "@ohos.ability.featureAbility"; import LooseObject from "../../data/LooseObject"; -import messageService from "../../service/ConversationListService"; +import ConversationListService from "../../service/ConversationListService"; +import ConversationService from '../../service/ConversationService'; import HiLog from "../../utils/HiLog"; import SettingService from "../../service/SettingService" import commonService from "../../service/CommonService"; import NotificationService from "../../service/NotificationService"; -import ConversationListDataSource from "../../model/ConversationListDataSource" -import AvatarColor from "../../model/common/AvatarColor" -import dataShare from "@ohos.data.dataShare"; +import ConversationListDataSource from "../../model/ConversationListDataSource"; +import AvatarColor from "../../model/common/AvatarColor"; +import StringUtil from "../../utils/StringUtil"; let ConversationCtrl; const TAG = "ConversationListController"; -const CONTACT_URI: string = "datashare:///com.ohos.contactsdataability/contacts/contact_data"; -const CONTENT_URI: String = "datashare:///com.ohos.contactsdataability"; export default class ConversationListController { // Determine whether to perform initialization. (To avoid the onShow time sequence problem immediately after the @@ -80,8 +79,8 @@ export default class ConversationListController { messageList: Array = []; // List of search results searchResultList: LooseObject = { - sessionList: [], - contentList: [] + "sessionList": [], + "contentList": [] }; // Search Results Queue searchResultListQueue: Array = []; @@ -120,7 +119,7 @@ export default class ConversationListController { // Check whether a common message (non-notification message) exists. hasNoOrdinaryMsg: boolean = false; // Check whether notification information exists. - hasInfoMsg: boolean = true; + hasInfoMsg: boolean = false; // Update the UI. flushTranslate: boolean = true; // Length of the operation button @@ -157,15 +156,17 @@ export default class ConversationListController { private async getDataAbilityHelper(context?) { if (this.dataShareHelper == undefined) { - this.dataShareHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, CONTENT_URI); + this.dataShareHelper = await dataShare.createDataShareHelper(context ? context : globalThis.mmsContext, + common.string.URI_ROW_CONTACTS); } return this.dataShareHelper; } registerDataChangeObserver(callback, context?) { + let contactDataUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; this.getDataAbilityHelper(context).then((dataAbilityHelper) => { if (dataAbilityHelper) { - dataAbilityHelper.on("dataChange", CONTACT_URI, callback); + dataAbilityHelper.on("dataChange", contactDataUri, callback); } }).catch(error => { HiLog.w(TAG, 'error:%s' + JSON.stringify(error.message)); @@ -173,9 +174,10 @@ export default class ConversationListController { } unregisterDataChangeObserver(callback, context?) { + let contactDataUri: string = common.string.URI_ROW_CONTACTS + common.string.CONTACT_DATA_URI; this.getDataAbilityHelper(context).then((dataAbilityHelper) => { if (dataAbilityHelper) { - dataAbilityHelper.off("dataChange", CONTACT_URI, callback); + dataAbilityHelper.off("dataChange", contactDataUri, callback); } }).catch(error => { HiLog.w(TAG, 'error:%s' + JSON.stringify(error.message)); @@ -455,58 +457,29 @@ export default class ConversationListController { deleteDialogConfirm() { this.setDelShow(); - let mmsList = []; - let threadIds = []; - let lockThreadIds = []; + let mmsList: Array = []; + let threadIds: Array = []; for (let element of this.messageList) { if (element.isCbChecked) { - if (element.isLock && !this.isSelectLockMsg) { - lockThreadIds.push(element.threadId); - mmsList.push(element); - } else { - threadIds.push(element.threadId); - } + threadIds.push(element.threadId); } else { mmsList.push(element); } } - // Set to non-multi-choice status this.isMultipleSelectState = false; this.isSelectLockMsg = false; this.messageList = mmsList; this.conversationListDataSource.refresh(this.messageList); this.total = this.messageList.length; this.hasNoOrdinaryMsg = this.total == 0 ? true : false; - this.deleteNotifyMessage(threadIds, lockThreadIds, () => { - this.deleteMessageByThreadIds(threadIds, lockThreadIds); - }); - } - deleteNotifyMessage(threadIds, lockThreadIds, callback) { - let sessionIds = []; - if (threadIds.length > 0) { - sessionIds.push(threadIds); - } - if (lockThreadIds.length > 0) { - sessionIds.push(lockThreadIds); - } - this.cancelMessageNotify(sessionIds, callback); - } - - deleteMessageByThreadIds(threadIds, lockThreadIds) { let actionData: LooseObject = {}; - if (threadIds.length > 0) { - actionData.threadIds = threadIds; - messageService.deleteMessageById(actionData); - } - if (lockThreadIds.length > 0) { - actionData.threadIds = lockThreadIds; - actionData.isMessageDetail = false; - messageService.dealMessageLockContent(actionData, res => { - actionData.hasLock = 0; - messageService.deleteMessageBySessionIdsAndLock(actionData); - }); - } + actionData.threadIds = threadIds; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + NotificationService.getInstance().updateBadgeNumber(); + actionData.hasRead = null; + ConversationListService.getInstance().deleteMessageById(actionData, null, null); } deleteDialogCancel() { @@ -528,25 +501,28 @@ export default class ConversationListController { } clickToMarkAllAsRead() { - // Mark unread as read. Here we deal with the values in the information list. - let threadIds = []; + let threadIds: Array = []; for (let mms of this.messageList) { if (mms.countOfUnread > common.int.MESSAGE_CODE_ZERO) { threadIds.push(mms.threadId); } } - - this.cancelMessageNotify(threadIds, () => { - // Marks the notification information as read. - let actionData = { - hasRead: 1, - smsType: 1, + let actionData: LooseObject = {}; + ConversationListService.getInstance().markAllToRead(actionData); + NotificationService.getInstance().setBadgeNumber(0); + actionData.threadIds = threadIds; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + this.unreadTotalOfInfo = 0; + this.unreadTotal = 0; + let tempMsgList: Array = this.messageList; + for (let msg of tempMsgList) { + if (threadIds.indexOf(msg.threadId) != -1) { + msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; } - messageService.markAllToRead(actionData); - this.unreadTotalOfInfo = 0; - this.unreadTotal = 0; - this.markAllAsRead(threadIds); - }); + } + this.messageList = tempMsgList; + this.conversationListDataSource.refresh(this.messageList); } jumpToSettingsPage() { @@ -593,21 +569,18 @@ export default class ConversationListController { // statistical data statisticalData() { - let actionData: LooseObject = {}; let that = this; - messageService.statisticalData(actionData, function (result) { + ConversationListService.getInstance().statisticalData(result => { if (result.code == common.int.SUCCESS) { // Total number of lists that.unreadTotal = result.response.totalListCount; // Unreading of notification messages that.unreadTotalOfInfo = result.response.unreadTotalOfInfo; - let actionData = {}; - NotificationService.getInstance().cancelMessageNotify(actionData, res => { - }); + NotificationService.getInstance().setBadgeNumber(Number(that.unreadTotal)); } else { HiLog.w(TAG, "statisticalData, failed"); } - }); + }, null); } // Obtains the switch value for integrating notification information and displaying contact avatars. @@ -655,23 +628,23 @@ export default class ConversationListController { if (contactsNum == common.int.MESSAGE_CODE_ONE) { var actionData = { phoneNumber: telephone, - pageFlag: common.contractPage.PAGE_FLAG_CONTACT_DETAILS + pageFlag: common.contactPage.PAGE_FLAG_CONTACT_DETAILS }; - this.jumpToContract(actionData); + this.jumpToContact(actionData); } else { - let threadId = this.messageList[index].threadId; + let threadId = this.messageList[index]?.threadId; let contactsNum = this.messageList[index]?.contactsNum; this.jumpToGroupDetail(threadId, contactsNum); } } // Switching to the Contacts app - jumpToContract(actionData) { - let str = commonService.commonContractParam(actionData); + jumpToContact(actionData) { + let str = commonService.commonContactParam(actionData); globalThis.mmsContext.startAbility(str).then((data) => { - HiLog.i(TAG, "jumpToContract, startAbility success"); + HiLog.i(TAG, "jumpToContact, startAbility success"); }).catch((error) => { - HiLog.e(TAG, "jumpToContract, failed Cause: " + JSON.stringify(error.message)); + HiLog.e(TAG, "jumpToContact, failed Cause: " + JSON.stringify(error.message)); }) this.isJumping = false; } @@ -701,22 +674,15 @@ export default class ConversationListController { // Querying All Lists queryAllMessages() { HiLog.i(TAG, "queryAllMessages, start"); - let that = this; - if (this.page == 1) { - this.limit = 50; - } else { - this.limit = 100; - } let actionData: LooseObject = {}; - // Whether notification information needs to be integrated + this.limit = StringUtil.getLimitForSession(this.page); if (this.hasAggregate) { - // Only non-notification information is queried. - actionData.numberType = 0; + actionData.smsType = common.sms_type.COMMON; } actionData.page = this.page; actionData.limit = this.limit; - messageService.querySessionList(actionData, result => { - HiLog.i(TAG, "querySessionList code=" + result.code); + actionData.orderByTimeDesc = true; + ConversationListService.getInstance().querySessionList(actionData, result => { if (result.code == common.int.SUCCESS) { let res = this.buildSessionList(result); this.messageList = this.messageList.concat(res); @@ -734,7 +700,7 @@ export default class ConversationListController { globalThis.needToUpdate = false; } } - }); + }, null); } buildSessionList(result) { @@ -780,55 +746,6 @@ export default class ConversationListController { } } - // Mark all unread notifications as read. - clickToMarkAllAsReadForInfo() { - let actionData = { - hasRead: 1, - smsType: 1, - } - let threadIds = []; - for (let msg of this.messageList) { - msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; - threadIds.push(msg.threadId); - } - this.cancelMessageNotify(threadIds, () => { - messageService.markAllToRead(actionData); - this.unreadTotalOfInfo = 0; - }); - } - - markAllAsRead(threadIds) { - let tempMsgList = this.messageList; - // Mark the information corresponding to threadIds as read. - let valueBucket = { - "unread_count": 0, - }; - let actionData: LooseObject = {}; - actionData.threadIds = threadIds; - actionData.valueBucket = valueBucket; - actionData.hasRead = 1; - // Update data marked read to 0 - messageService.markAllAsRead(actionData); - for (let msg of tempMsgList) { - if (threadIds.indexOf(msg.threadId) > common.int.FAILURE) { - // Controls the display of unread icons in the list - msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; - } - } - this.messageList = tempMsgList; - this.conversationListDataSource.refresh(this.messageList); - } - - cancelMessageNotify(threadIds, callback) { - let actionData = { - threadIds: threadIds, - hasRead: 0 - }; - NotificationService.getInstance().cancelMessageNotify(actionData, res => { - callback(); - }); - } - // The SM details page is displayed. clickInfoToConversation(index) { if (this.resetTouch()) { @@ -870,14 +787,23 @@ export default class ConversationListController { } markAllAsReadByIndex(index) { - let threadId = this.messageList[index].threadId; - let threadIds = [threadId]; - this.cancelMessageNotify(threadIds, () => { - // Mark the information corresponding to the contact index as read. - this.markAllAsRead(threadIds); - this.setListItemTransX(0); - this.statisticalData(); - }); + let threadId: number = this.messageList[index]?.threadId; + let actionData: LooseObject = {}; + actionData.threadId = threadId; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + ConversationListService.getInstance().markAllToRead(actionData); + let tempMsgList: Array = this.messageList; + for (let msg of tempMsgList) { + if (threadId == msg.threadId) { + // Controls the display of unread icons in the list + msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; + } + } + this.messageList = tempMsgList; + this.conversationListDataSource.refresh(this.messageList); + this.setListItemTransX(0); + this.statisticalData(); } deleteAction(idx) { @@ -888,78 +814,6 @@ export default class ConversationListController { this.hasLockMsg = this.judgehasLockMsg(); } - // 搜索 - clickToSearch(inputContent) { - this.inputValueOfSearch = inputContent; - this.search(inputContent); - } - - search(text) { - // 在信息列表页面搜索 - let actionData: LooseObject = {} - actionData.inputValue = text - this.searchTextAsync(actionData); - } - - searchTextAsync(actionData) { - messageService.searchMessageWithLike(actionData, result => { - if (result.code == common.int.SUCCESS) { - // 获取搜索返回的结果先做判空处理 - if (this.inputValueOfSearch !== common.string.EMPTY_STR) { - this.dealSearchResult(result); - } - } else { - this.searchResultListEmpty(); - } - }); - } - - searchResultListEmpty() { - this.searchResultList = { - contentList: [], - sessionList: [] - } - this.isSearchStatus = true; - this.hasInfoMsg = true; - if (this.isShowSearchBack) { - this.isSearchCoverage = true; - } else { - this.isSearchCoverage = false; - } - } - - dealSearchResult(result) { - this.searchResultList = { - contentList: [], - sessionList: [] - } - this.hasInfoMsg = false; - this.isSearchStatus = false; - this.isSearchCoverage = false; - this.buildSearchResult(result); - if (this.inputValueOfSearch === result.search) { - this.searchResultList = result.resultMap; - } - } - - buildSearchResult(result) { - if (result.resultMap.contentList) { - result.resultMap.contentList.forEach(content => { - content.timeMillisecond = parseInt(content.timeMillisecond); - DateUtil.convertDateFormatForItem(content, true); - if (content.isFavorite) { - content.name = $r("app.string.message_in_favorites"); - } - }); - } - if (result.resultMap.sessionList) { - result.resultMap.sessionList.forEach(session => { - session.timeMillisecond = parseInt(session.timeMillisecond); - DateUtil.convertDateFormatForItem(session, true); - }); - } - } - checkHasCommonMessage() { return this.messageList.length > 0; } diff --git a/entry/src/main/ets/pages/infomsg/InfoMsg.ets b/entry/src/main/ets/pages/infomsg/InfoMsg.ets index 6a86bb2..c623fa9 100644 --- a/entry/src/main/ets/pages/infomsg/InfoMsg.ets +++ b/entry/src/main/ets/pages/infomsg/InfoMsg.ets @@ -203,10 +203,10 @@ export default struct InfoMsg { .enabled(!this.mIsMultipleSelectState) .backgroundColor($r("sys.color.ohos_id_color_text_field_bg")) .onChange((value: string) => { - this.mInfoMsgCtrl.clickToSearch(value); + //this.mInfoMsgCtrl.clickToSearch(value); }) .onSubmit((value: string) => { - this.mInfoMsgCtrl.clickToSearch(value); + //this.mInfoMsgCtrl.clickToSearch(value); }) } .visibility(Visibility.None) @@ -417,6 +417,6 @@ export default struct InfoMsg { .height("100%") } } - .margin({ left: this.gridMargin }) + .margin({ left: this.gridMargin, right: this.gridMargin }) } } \ No newline at end of file diff --git a/entry/src/main/ets/pages/infomsg/InfoMsgController.ets b/entry/src/main/ets/pages/infomsg/InfoMsgController.ets index 047b0e2..82be335 100644 --- a/entry/src/main/ets/pages/infomsg/InfoMsgController.ets +++ b/entry/src/main/ets/pages/infomsg/InfoMsgController.ets @@ -12,23 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import common from "../../data/commonData"; -import commonEvent from "@ohos.commonEventManager"; -import commonService from "../../service/CommonService"; -import dateUtil from "../../utils/DateUtil"; -import featureAbility from "@ohos.ability.featureAbility"; -import LooseObject from "../../data/LooseObject" -// Information List Service -import messageService from "../../service/ConversationListService"; -// Log tool class -import HiLog from "../../utils/HiLog"; -import MmsPreferences from "../../utils/MmsPreferences"; -import NotificationService from "../../service/NotificationService"; -// Notification Information -import router from "@system.router"; -// Obtain the setting switch. -import settingService from "../../service/SettingService"; -import ConversationListDataSource from "../../model/ConversationListDataSource" +import commonEvent from '@ohos.commonEventManager'; +import router from '@system.router'; + +import common from '../../data/commonData'; +import commonService from '../../service/CommonService'; +import dateUtil from '../../utils/DateUtil'; +import LooseObject from '../../data/LooseObject' +import ConversationListService from '../../service/ConversationListService'; +import ConversationService from '../../service/ConversationService'; +import HiLog from '../../utils/HiLog'; +import NotificationService from '../../service/NotificationService'; +import settingService from '../../service/SettingService'; +import ConversationListDataSource from '../../model/ConversationListDataSource' const TAG = "InfoMsgController" @@ -55,8 +51,8 @@ export default class InfoMsgController { isSelectLockMsg: boolean = false; // List of search results searchResultList: LooseObject = { - sessionList: [], - contentList: [] + "sessionList": [], + "contentList": [] }; // Search Results Queue searchResultListQueue: Array = []; @@ -88,7 +84,6 @@ export default class InfoMsgController { // Number of unread notifications. unreadTotalOfInfo: number = 0; messageList: Array = []; - numberType: number = 1; // Indicates whether to display the contact profile picture. isShowContactHeadIcon: boolean = true; // Number of search results @@ -135,9 +130,7 @@ export default class InfoMsgController { this.page = 0; this.requestItem(); this.subscribeInfo(); - let actionData = {}; - NotificationService.getInstance().cancelMessageNotify(actionData, res => { - }); + NotificationService.getInstance().updateBadgeNumber(); } onHide() { @@ -146,12 +139,12 @@ export default class InfoMsgController { } // Querying List Data queryAllMessages() { - let actionData: LooseObject = { - page: this.page, - limit: this.limit, - } - actionData.numberType = this.numberType; - messageService.querySessionList(actionData, result => { + let actionData: LooseObject = {}; + actionData.smsType = common.sms_type.NOTICE; + actionData.page = this.page; + actionData.limit = this.limit; + actionData.orderByTimeDesc = true; + ConversationListService.getInstance().querySessionList(actionData, result => { if (result.code == common.int.SUCCESS) { HiLog.i(TAG, "queryAllMessages, Success"); let res = this.buildSessionList(result); @@ -165,7 +158,7 @@ export default class InfoMsgController { } else { HiLog.w(TAG, "queryAllMessages, failed"); } - }); + }, null); } dealMmsListContent(element) { @@ -241,100 +234,7 @@ export default class InfoMsgController { this.searchStatus = false; this.showToolBar = true; } - // Search - clickToSearch(text) { - this.inputValueOfSearch = text; - this.search(text); - } - // Search on the notification information page. - search(text) { - let actionData: LooseObject = {}; - actionData.inputValue = text - this.searchTextAsync(actionData) - } - searchTextAsync(actionData) { - actionData.numberType = this.numberType; - messageService.searchMessageWithLike(actionData, result => { - if (result.code == common.int.SUCCESS) { - // Check whether the search result is empty before obtaining the search result. - if (this.inputValueOfSearch !== common.string.EMPTY_STR) { - this.dealSearchResult(result); - } - } else { - this.searchResultListEmpty(); - } - }); - } - - dealSearchResult(result) { - this.searchResultList = { - contentList: [], - sessionList: [] - } - this.isSearchStatus = false; - this.isSearchCoverage = false; - this.dealSearchResultTimeAndName(result); - if (this.inputValueOfSearch === result.search) { - this.searchResultList = result.resultMap; - } - } - - dealSearchResultTimeAndName(result) { - if (result.resultMap.sessionList) { - result.resultMap.sessionList.forEach(session => { - session.timeMillisecond = parseInt(session.timeMillisecond); - dateUtil.convertDateFormatForItem(session, true); - }); - } - if (result.resultMap.contentList) { - result.resultMap.contentList.forEach(content => { - content.timeMillisecond = parseInt(content.timeMillisecond); - dateUtil.convertDateFormatForItem(content, true); - if (content.isFavorite) { - content.name = $r("app.string.message_in_favorites"); - } - }); - } - } - - searchResultListEmpty() { - this.searchResultList = { - contentList: [], - sessionList: [] - } - // Display Information List - this.isSearchStatus = true; - if (this.isShowSearchBack) { - this.isSearchCoverage = true; - } else { - this.isSearchCoverage = false; - } - } - // Check whether the multi-choice status is selected. - searchTouchStart() { - if (this.isMultipleSelectState) { - return false; - } - this.searchStatus = true; - this.showToolBar = false; - // Search area touchStart monitoring - // x > 125 && x < 600) && (y < 70 && y > 20 - // var x = event.touches[0].x; - // if (isSearchType && x > 80 && x < 560) { - // Show New Button - this.isShowSearchBack = true; - // Mask Display - this.isSearchCoverage = true; - // Start the input method. - setTimeout(() => { - this.isSearchFocusable = true; - }, common.int.MESSAGE_CODE_THREE_ZERO_ZERO); - // } - this.resetTouch(); - return false; - } - // Touch and hold a list to display the selection and deletion functions. conversationLongPress(index) { // Check whether the left slide button exists. If yes, the button cannot be clicked. if (this.itemTouchedIdx >= 0 && this.messageList[this.itemTouchedIdx].isDelShow) { @@ -439,8 +339,8 @@ export default class InfoMsgController { if (contactsNum == common.int.MESSAGE_CODE_ONE) { var actionData: LooseObject = {}; actionData.phoneNumber = telephone; - actionData.pageFlag = common.contractPage.PAGE_FLAG_CONTACT_DETAILS; - this.jumpToContract(actionData); + actionData.pageFlag = common.contactPage.PAGE_FLAG_CONTACT_DETAILS; + this.jumpToContact(actionData); } else { let threadId = item.threadId; let contactsNum = item.contactsNum; @@ -490,78 +390,57 @@ export default class InfoMsgController { } // Counting the number of unread messages countUnread() { - let actionData: LooseObject = {}; let that = this; - messageService.statisticalData(actionData, function (result) { + ConversationListService.getInstance().statisticalData(result => { if (result.code == common.int.SUCCESS) { // Unreading of notification messages that.unreadTotalOfInfo = result.response.unreadTotalOfInfo; HiLog.i(TAG, "countUnread = " + that.unreadTotalOfInfo); + NotificationService.getInstance().setBadgeNumber(Number(result.response.totalListCount)); } else { HiLog.w(TAG, "countUnread, statisticalData failed"); } - }); + }, null); } // Mark all unread notifications as read. clickToMarkAllAsReadForInfo() { - let actionData = { - hasRead: 1, - smsType: 1 - } - let threadIds = []; + let threadIds: Array = []; for (let msg of this.messageList) { msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; threadIds.push(msg.threadId); } - this.cancelMessageInfoNotify(threadIds, () => { - messageService.markAllToRead(actionData); - this.unreadTotalOfInfo = 0; - }); + let actionData: LooseObject = {}; + actionData.threadIds = threadIds; + actionData.hasRead = common.is_read.UN_READ; + actionData.smsType = common.sms_type.NOTICE; + NotificationService.getInstance().cancelMessageNotify(actionData); + ConversationListService.getInstance().markAllToRead(actionData); + NotificationService.getInstance().updateBadgeNumber(); + this.unreadTotalOfInfo = 0; } markAllAsReadByIndex(index) { - let item = this.messageList[index]; - let threadId = item.threadId; - let threadIds = [threadId]; - this.cancelMessageInfoNotify(threadIds, () => { - // Marks all information about a contact (argument type: array) as read. - this.markAllAsRead(threadIds); - this.setListItemTransX(0); - item.isDelShow = false; - }); - } - - cancelMessageInfoNotify(threadIds, callback) { - let actionData = { - threadIds: threadIds, - hasRead: 0 - }; - NotificationService.getInstance().cancelMessageNotify(actionData, res => { - callback(); - }); - } - - markAllAsRead(threadIds) { - let tempMsgList = this.messageList; - // Marks all information about a contact (argument type: array) as read. - let valueBucket = { - "unread_count": 0, - }; + let item: LooseObject = this.messageList[index]; + let threadId: number = item.threadId; let actionData: LooseObject = {}; - actionData.threadIds = threadIds; - actionData.valueBucket = valueBucket; - actionData.hasRead = 1; - // Update data marked read to 0 - messageService.markAllAsRead(actionData); + actionData.threadId = threadId; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + NotificationService.getInstance().updateBadgeNumber(); + ConversationListService.getInstance().markAllToRead(actionData); + let tempMsgList: Array = this.messageList; for (let msg of tempMsgList) { - if (threadIds.indexOf(msg.threadId) > common.int.FAILURE) { + if (threadId == msg.threadId) { // Controls the display of unread icons in the list msg.countOfUnread = common.int.MESSAGE_CODE_ZERO; } } this.messageList = tempMsgList; this.conversationListDataSource.refresh(this.messageList); - this.unreadTotalOfInfo = this.unreadTotalOfInfo - threadIds.length; + this.unreadTotalOfInfo = this.unreadTotalOfInfo - 1; + + this.setListItemTransX(0); + item.isDelShow = false; } selectInMoreMenu(menuId: number) { @@ -609,19 +488,13 @@ export default class InfoMsgController { deleteDialogConfirm() { this.setDelShow(); - let mmsList = []; - let threadIds = []; - let lockSessionIds = []; - for (let item of this.messageList) { - if (item.isCbChecked) { - if (item.isLock && !this.isSelectLockMsg) { - lockSessionIds.push(item.threadId); - mmsList.push(item); - } else { - threadIds.push(item.threadId); - } + let mmsList: Array = []; + let threadIds: Array = []; + for (let element of this.messageList) { + if (element.isCbChecked) { + threadIds.push(element.threadId); } else { - mmsList.push(item); + mmsList.push(element); } } this.isMultipleSelectState = false; @@ -633,9 +506,13 @@ export default class InfoMsgController { if (this.total == 0) { router.back(); } - this.deleteNotifyMessageInfo(threadIds, lockSessionIds, () => { - this.deleteMessageInfoByThreadIds(threadIds, lockSessionIds); - }); + let actionData: LooseObject = {}; + actionData.threadIds = threadIds; + actionData.hasRead = common.is_read.UN_READ; + NotificationService.getInstance().cancelMessageNotify(actionData); + NotificationService.getInstance().updateBadgeNumber(); + actionData.hasRead = null; + ConversationListService.getInstance().deleteMessageById(actionData, null, null); } setDelShow() { @@ -646,31 +523,6 @@ export default class InfoMsgController { } }; - deleteNotifyMessageInfo(threadIds, lockSessionIds, callback) { - let sessionIds = []; - if (lockSessionIds.length > 0) { - sessionIds.push(lockSessionIds); - } - if (threadIds.length > 0) { - sessionIds.push(threadIds); - } - this.cancelMessageInfoNotify(sessionIds, callback); - } - - deleteMessageInfoByThreadIds(threadIds, lockSessionIds) { - let actionData: LooseObject = {}; - if (threadIds.length > 0) { - actionData.threadIds = threadIds; - messageService.deleteMessageById(actionData); - } - if (lockSessionIds.length > 0) { - actionData.threadIds = lockSessionIds; - messageService.dealMessageLockContent(actionData, res => { - actionData.hasLock = 0; - messageService.deleteMessageBySessionIdsAndLock(actionData); - }); - } - } // Select All/Deselect All clickConversationCheckAll() { if (this.isConversationCheckAll) { @@ -712,11 +564,11 @@ export default class InfoMsgController { if (contactsNum == common.int.MESSAGE_CODE_ONE) { var actionData = { phoneNumber: telephone, - pageFlag: common.contractPage.PAGE_FLAG_CONTACT_DETAILS + pageFlag: common.contactPage.PAGE_FLAG_CONTACT_DETAILS }; - this.jumpToContract(actionData); + this.jumpToContact(actionData); } else { - let threadId = this.messageList[index].threadId; + let threadId = this.messageList[index]?.threadId; let contactsNum = this.messageList[index]?.contactsNum; this.jumpToGroupDetail(threadId, contactsNum); } @@ -755,8 +607,8 @@ export default class InfoMsgController { return false; } if (item.isDelShow) { - this.setListItemTransX(0); item.isDelShow = false; + this.setListItemTransX(0); return true; } } @@ -857,11 +709,11 @@ export default class InfoMsgController { } } // Switching to the Contacts app - jumpToContract(actionData) { - var str = commonService.commonContractParam(actionData); + jumpToContact(actionData) { + var str = commonService.commonContactParam(actionData); globalThis.mmsContext.startAbility(str).then((data) => { }).catch((error) => { - HiLog.e(TAG, "jumpToContract, failed: " + JSON.stringify(error.message)); + HiLog.e(TAG, "jumpToContact, failed: " + JSON.stringify(error.message)); }) this.isJumping = false; } diff --git a/entry/src/main/ets/pages/queryreport/queryReport.ets b/entry/src/main/ets/pages/queryreport/queryReport.ets index 99b6467..260741b 100644 --- a/entry/src/main/ets/pages/queryreport/queryReport.ets +++ b/entry/src/main/ets/pages/queryreport/queryReport.ets @@ -36,60 +36,58 @@ struct queryReport { } build() { - GridRow({ columns: this.gridColumns, gutter: this.gridGutter }) { - GridCol({ span: this.girdSpan }) { - Row() { - Image($rawfile('icon/ic_message_back.svg')) - .width(24) - .height(24) - .onClick(() => { - router.back() - }) - Text($r("app.string.send_reports")) - .margin({ left: 16 }) - .fontSize(20) - .fontWeight(FontWeight.Bold) - .lineHeight(28) - } - .alignItems(VerticalAlign.Center) - .height(56) + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) { + Row() { + Image($rawfile('icon/ic_message_back.svg')) + .width(24) + .height(24) + .onClick(() => { + router.back() + }) + Text($r("app.string.send_reports")) + .margin({ left: 16 }) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .lineHeight(28) } - GridCol({ span: this.girdSpan }) { - Column() { + .alignItems(VerticalAlign.Center) + .height(56) + + Column() { + Text() { + Span($r("app.string.putAddresser")).fontSize(16) + Span(this.queryReportController.telephone).fontSize(16) + } + .fontSize(16) + .height(48) + .fontWeight(FontWeight.Medium) + .lineHeight(22) + + Text() { + Span($r("app.string.Status")).fontSize(16) + Span(this.queryReportController.sendStatusDesc).fontSize(16) + } + .fontSize(16) + .height(48) + .fontWeight(FontWeight.Medium) + .lineHeight(22) + + if (!this.queryReportController.isMsm && this.queryReportController.sendStatus != 2) { Text() { - Span($r("app.string.putAddresser")).fontSize(16) - Span(this.queryReportController.telephone).fontSize(16) + Span($r("app.string.Delivered")).fontSize(16) + Span(this.queryReportController.mmsTime).fontSize(16) + Span(" ") + Span(this.queryReportController.specificTime).fontSize(16) } .fontSize(16) .height(48) .fontWeight(FontWeight.Medium) .lineHeight(22) - - Text() { - Span($r("app.string.Status")).fontSize(16) - Span(this.queryReportController.sendStatusDesc).fontSize(16) - } - .fontSize(16) - .height(48) - .fontWeight(FontWeight.Medium) - .lineHeight(22) - - if (!this.queryReportController.isMsm && this.queryReportController.sendStatus != 2) { - Text() { - Span($r("app.string.Delivered")).fontSize(16) - Span(this.queryReportController.mmsTime).fontSize(16) - Span(" ") - Span(this.queryReportController.specificTime).fontSize(16) - } - .fontSize(16) - .height(48) - .fontWeight(FontWeight.Medium) - .lineHeight(22) - } } - .alignItems(HorizontalAlign.Start) - .padding({ left: 12, right: 12 }) } + .alignItems(HorizontalAlign.Start) + .padding({ left: 12, right: 12 }) + } .width("100%") .height("100%") diff --git a/entry/src/main/ets/pages/settings/advancedSettings/advancedSettings.ets b/entry/src/main/ets/pages/settings/advancedSettings/advancedSettings.ets index da4d665..501f18c 100644 --- a/entry/src/main/ets/pages/settings/advancedSettings/advancedSettings.ets +++ b/entry/src/main/ets/pages/settings/advancedSettings/advancedSettings.ets @@ -278,28 +278,24 @@ struct DeliveryReportsDialog { .lineHeight(28) .fontWeight(FontWeight.Medium) .fontFamily("HarmonyHeiTi") - Flex({ - direction: FlexDirection.Row, - justifyContent: FlexAlign.SpaceBetween, - alignItems: ItemAlign.Center - }) { + Stack() { Text($r("app.string.sms")) .fontSize(16) .fontColor($r("sys.color.ohos_id_color_foreground")) .lineHeight(22) .fontWeight(FontWeight.Medium) .fontFamily("HarmonyHeiTi") + .align(Alignment.Start) + .width('100%') Toggle({ type: ToggleType.Checkbox, isOn: this.isOnOfSms }) - .width(20) + .width("100%") .height(20) - .offset({ x: 16, y: 0 }) .selectedColor($r("sys.color.ohos_id_color_activated")) + .align(Alignment.End) .onChange((isOn: boolean) => { this.isOnOfSms = isOn }) - } - .width("100%") - .height(48) + }.margin({ bottom: 5 }) Divider() .vertical(false) @@ -307,28 +303,24 @@ struct DeliveryReportsDialog { .width("100%") .color($r("sys.color.ohos_id_color_list_separator")) - Flex({ - direction: FlexDirection.Row, - justifyContent: FlexAlign.SpaceBetween, - alignItems: ItemAlign.Center - }) { + Stack() { Text($r("app.string.mms")) .fontSize(16) .fontColor($r("sys.color.ohos_id_color_foreground")) .lineHeight(22) .fontWeight(FontWeight.Medium) .fontFamily("HarmonyHeiTi") + .align(Alignment.Start) + .width('100%') Toggle({ type: ToggleType.Checkbox, isOn: this.isOnOfMms }) - .width(20) + .width("100%") .height(20) - .offset({ x: 16, y: 0 }) .selectedColor($r("sys.color.ohos_id_color_activated")) + .align(Alignment.End) .onChange((isOn: boolean) => { this.isOnOfMms = isOn }) - } - .width("100%") - .height(48) + }.margin({ top: 5 }) } .padding({ left: 24, right: 24, bottom: 9 }) diff --git a/entry/src/main/ets/pages/transmitmsg/transmitMsg.ets b/entry/src/main/ets/pages/transmitmsg/transmitMsg.ets index 7966910..3ea000e 100644 --- a/entry/src/main/ets/pages/transmitmsg/transmitMsg.ets +++ b/entry/src/main/ets/pages/transmitmsg/transmitMsg.ets @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -42,12 +41,6 @@ export default struct TransmitMsg { autoCancel: false, alignment: this.dialogAlignment, offset: this.dialogOffset, - changeValue: (item) => { - this.mTransmitMsgCtrl.changeValue(item) - }, - clickChecked: (isOn: boolean) => { - this.mConListCtrl.clickChecked(isOn) - } }); aboutToAppear() { @@ -104,7 +97,7 @@ export default struct TransmitMsg { Flex(){ Column(){ Row() { - Text($r("app.string.selectContracts")) + Text($r("app.string.selectContacts")) .fontSize("16fp") .fontColor($r("sys.color.ohos_id_color_text_primary")) Blank() @@ -122,7 +115,7 @@ export default struct TransmitMsg { .width("100%") .onClick(() => { //Go to Select Contact - this.mTransmitMsgCtrl.jumpToSelectContracts() + this.mTransmitMsgCtrl.jumpToSelectContacts(); }) //recent diff --git a/entry/src/main/ets/pages/transmitmsg/transmitMsgController.ets b/entry/src/main/ets/pages/transmitmsg/transmitMsgController.ets index a0d6965..161620d 100644 --- a/entry/src/main/ets/pages/transmitmsg/transmitMsgController.ets +++ b/entry/src/main/ets/pages/transmitmsg/transmitMsgController.ets @@ -1,5 +1,4 @@ // @ts-nocheck - /** * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,16 +14,16 @@ * limitations under the License. */ -import LooseObject from "../../data/LooseObject" import router from '@ohos.router'; -import contactService from '../../service/ContractService'; + +import LooseObject from "../../data/LooseObject" +import ContactService from '../../service/ContactsService'; import common from '../../data/commonData'; import commonService from '../../service/CommonService' -import conversationListService from "../../service/ConversationListService"; +import ConversationListService from "../../service/ConversationListService"; import AvatarColor from "../../model/common/AvatarColor"; import DateUtil from "../../utils/DateUtil"; import TransmitMsgDataSource from "../../model/TransmitMsgDataSource"; -// Log tool class import HiLog from "../../utils/HiLog"; const TAG = "TransmitMsgController" @@ -35,7 +34,7 @@ export default class TransmitMsgController { // Total total: 0; // Information List - contractsList: Array = []; + contactsList: Array = []; // List of contents forwarded by multiple messages transmitContentList: Array = []; // Dual SIM card @@ -65,7 +64,7 @@ export default class TransmitMsgController { // Card 2 simTwo: number = 1; // Sending SMS message ID - threadId: string = ''; + threadId: number = 0; // Forwarded Content Title transmitContent: string = ''; // Formatted forwarding content @@ -73,7 +72,7 @@ export default class TransmitMsgController { // Forwarding Content Editing Status Content transmitContentEdit: string = ''; // Display Forwarding Dialog Box - contractsPage: boolean = false; + contactsPage: boolean = false; // The font size of the dialog title is displayed. When the number of characters is small, the large font is // displayed. When the number of characters is large, the small font is displayed. titleChecked: boolean = false; @@ -90,7 +89,7 @@ export default class TransmitMsgController { transmitItemSources: Array = []; reg: RegExp = /^[\u4e00-\u9fa5_a-zA-Z]+$/; dialogMsg: LooseObject = {}; - DialogShow: false; + DialogShow: boolean = false; transmitMsgDataSource: TransmitMsgDataSource = new TransmitMsgDataSource(); static getInstance() { @@ -119,8 +118,8 @@ export default class TransmitMsgController { if (this.page === 0) { this.page++; this.queryAllMessages(); - } else if (count < this.total && this.contractsList.length > (this.page - 1) * this.limit) { - // The restriction on contractsList is to prevent multiple update requests during initialization. + } else if (count < this.total && this.contactsList.length > (this.page - 1) * this.limit) { + // The restriction on contactsList is to prevent multiple update requests during initialization. this.page++; this.queryAllMessages(); } @@ -128,17 +127,15 @@ export default class TransmitMsgController { // Queries all list information. queryAllMessages() { - let that = this; let actionData: LooseObject = {}; actionData.page = this.page; actionData.limit = this.limit; - conversationListService.querySessionList(actionData, result => { + actionData.orderByTimeDesc = true; + ConversationListService.getInstance().querySessionList(actionData, result => { if (result.code == common.int.SUCCESS) { - this.contractsList = this.buildSessionList(result);; - this.transmitMsgDataSource.refresh(this.contractsList); + this.contactsList = this.buildSessionList(result); + this.transmitMsgDataSource.refresh(this.contactsList); this.total = result.total; - this.hasNoOrdinaryMsg = this.total == 0 ? true : false; - this.hasInfoMsg = result.hasInfoMsg; } }); } @@ -147,7 +144,7 @@ export default class TransmitMsgController { let res = []; result.response.forEach(item => { // Inherit selected items - this.contractsList.some(oldItem => { + this.contactsList.some(oldItem => { if (item.threadId === oldItem.threadId) { item.isCbChecked = oldItem.isCbChecked; return true; @@ -207,21 +204,21 @@ export default class TransmitMsgController { } } - jumpToSelectContracts(callback) { + jumpToSelectContacts(callback?) { // The page for selecting a contact is displayed. let actionData: LooseObject = {}; - actionData.pageFlag = common.contractPage.PAGE_FLAG_SINGLE_CHOOSE; - this.jumpToContractForResult(actionData, callback); + actionData.pageFlag = common.contactPage.PAGE_FLAG_SINGLE_CHOOSE; + this.jumpToContactForResult(actionData, callback); } // Go to Contacts app - async jumpToContractForResult(actionData, callback) { - let str = commonService.commonContractParam(actionData); + async jumpToContactForResult(actionData, callback) { + let str = commonService.commonContactParam(actionData); let data = await globalThis.mmsContext.startAbilityForResult(str); this.dialogMsg.data = data; if (data.resultCode == 0 && JSON.parse(data.want.parameters.contactObjects).length != 0) { this.DialogShow = true; - let contactsParam = contactService.dealContractParams(data.want.parameters.contactObjects); + let contactsParam = ContactService.getInstance().dealContactParams(data.want.parameters.contactObjects); let contactsParamMsg: LooseObject = {}; contactsParamMsg.contactsNum = contactsParam.contactsNum; contactsParamMsg.contactName = contactsParam.strContactsName; @@ -230,7 +227,7 @@ export default class TransmitMsgController { contactsParamMsg.contactNameSplit = contactsParam.strContactsName.split(common.string.COMMA)[0]; contactsParamMsg.telephoneFormatSplit = contactsParam.strContactsNumberFormat.split(common.string.COMMA)[0]; this.dialogMsg.contactsParam = contactsParamMsg; - conversationListService.querySessionByTelephone(this.telephone, res => { + ConversationListService.getInstance().querySessionByTelephone(this.telephone, res => { let response = res.response; if (res.code === common.int.SUCCESS && response.id > 0) { this.threadId = response.id; @@ -238,9 +235,10 @@ export default class TransmitMsgController { this.threadId = 0; } this.checkContactNameLen(); - }); - callback(); - + }, null); + if (callback) { + callback(); + } } } @@ -249,18 +247,18 @@ export default class TransmitMsgController { item.content = e.text; } - transmit() { - let params = { - threadId: this.threadId, - strContactsName: this.dialogMsg.contactsParam.contactName, //Contact Name - strContactsNumber: this.dialogMsg.contactsParam.telephone, //Mobile phone number - strContactsNumberFormat: this.dialogMsg.contactsParam.telephoneFormat, //Format the mobile number. - transmitFlag: true, //Send Flag - contractsPage: false, //Display Forwarding Dialog Box - mmsSource: this.mmsSource, //MMS list data - isSlideDetail: this.isSlideDetail,//Indicates whether the slide page is an MMS message. - transmitSource: this.transmitContentList,//List of contents forwarded by multiple messages - isContainerOriginSource: this.isChecked //Whether selected + transmit(): void { + let params: LooseObject = { + "threadId": this.threadId, + "strContactsName": this.dialogMsg.contactsParam.contactName, //Contact Name + "strContactsNumber": this.dialogMsg.contactsParam.telephone, //Mobile phone number + "strContactsNumberFormat": this.dialogMsg.contactsParam.telephoneFormat, //Format the mobile number. + "transmitFlag": true, //Send Flag + "contactsPage": false, //Display Forwarding Dialog Box + "mmsSource": this.mmsSource, //MMS list data + "isSlideDetail": this.isSlideDetail,//Indicates whether the slide page is an MMS message. + "transmitSource": this.transmitContentList,//List of contents forwarded by multiple messages + "isContainerOriginSource": this.isChecked //Whether selected } router.replaceUrl({ url: 'pages/conversation/conversation', diff --git a/entry/src/main/ets/service/CommonService.ets b/entry/src/main/ets/service/CommonService.ets index 9284330..3c28304 100644 --- a/entry/src/main/ets/service/CommonService.ets +++ b/entry/src/main/ets/service/CommonService.ets @@ -16,10 +16,10 @@ import common from "../data/commonData"; export default { - commonContractParam(actionData) { + commonContactParam(actionData) { let str = { - "bundleName": common.string.CONTRACT_BUNDLE_NAME, - "abilityName": common.string.CONTRACT_ABILITY_NAME, + "bundleName": common.string.CONTACT_BUNDLE_NAME, + "abilityName": common.string.CONTACT_ABILITY_NAME, "parameters": actionData, "entities": [ common.string.COMMON_ENTITIES diff --git a/entry/src/main/ets/service/ContactsService.ets b/entry/src/main/ets/service/ContactsService.ets new file mode 100644 index 0000000..2a2e9e3 --- /dev/null +++ b/entry/src/main/ets/service/ContactsService.ets @@ -0,0 +1,205 @@ +/** + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import HiLog from '../utils/HiLog'; +import common from '../data/commonData'; +import telephoneUtil from '../utils/TelephoneUtil'; +import LooseObject from '../data/LooseObject'; +import ContactsModel from '../model/ContactsModel'; + +const TAG = "ContactsService"; + +export default class ContactsService { + private static instance: ContactsService; + private contactsModel = new ContactsModel(); + + private constructor() { + } + + public static getInstance(): ContactsService { + if (ContactsService.instance == null) { + ContactsService.instance = new ContactsService(); + } + return ContactsService.instance; + } + + public async queryContactDataByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryContactDataByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryContactDataByCondition(actionData, callback, mmsContext); + } + + } + + public async queryContactDataSizeByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryContactDataSizeByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryContactDataSizeByCondition(actionData, callback, mmsContext); + } + } + + public async queryContactByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryContactByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryContactByCondition(actionData, callback, mmsContext); + } + } + + public async queryContactSizeByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryContactSizeByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryContactSizeByCondition(actionData, callback, mmsContext); + } + } + + public async queryRawContactSizeByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryRawContactSizeByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryRawContactSizeByCondition(actionData, callback, mmsContext); + } + } + + public async queryContactViewByCondition(actionData, callback, context): Promise { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryContactViewByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.contactsModel.queryContactViewByCondition(actionData, callback, mmsContext); + } + } + + public queryContact(actionData, callback, context): void { + this.queryContactByCondition(actionData, res => { + if (res.code == common.int.FAILURE) { + callback(res); + return; + } + actionData.contactIds = res.abilityResult[0]; + this.queryContactDataByCondition(actionData, res => { + if (res.code == common.int.FAILURE) { + callback(res); + return; + } + let contactList: Array = this.buildContactList(res.abilityResult); + let result: LooseObject = {}; + result.code = common.int.SUCCESS; + result.response = contactList; + callback(result); + }, context); + }, context); + } + + public dealContactParams(contactObjects): LooseObject { + let contactParams: LooseObject = {}; + if (contactObjects && contactObjects != common.string.EMPTY_STR) { + let params: Array = []; + try { + params = JSON.parse(contactObjects); + } catch (Error) { + HiLog.i(TAG, `JSON.parse error ${Error}`); + return contactParams; + } + let contactsNumber: string = common.string.EMPTY_STR; + let contactsName: string = common.string.EMPTY_STR; + let contactsNumberFormat: string = common.string.EMPTY_STR; + let length: number = params.length; + for (let item of params) { + contactsNumber = contactsNumber + item.telephone + common.string.COMMA; + contactsNumberFormat = contactsNumberFormat + item.telephone + common.string.COMMA; + if (item.contactsName) { + contactsName += (item.contactsName + common.string.COMMA); + } else if (length > 1) { + contactsName += (item.telephone + common.string.COMMA); + } + } + let telephone: string = contactsNumber.substring(0, contactsNumber.length - 1); + contactsNumber = telephoneUtil.dealTelephoneSort(telephone); + contactParams.strContactsNumber = contactsNumber; + contactParams.strContactsNumberFormat = contactsNumber; + contactParams.strContactsName = contactsName.substring(0, contactsName.length - 1); + contactParams.contactsNum = length; + } + return contactParams; + } + + public judgeContactExist(actionData, callback, context): void { + this.queryContactDataSizeByCondition(actionData, res => { + let isContactExist: boolean = false; + if (res.code == common.int.FAILURE) { + HiLog.e(TAG, "judgeProfileExit fail!"); + callback(isContactExist); + } else { + if (res.abilityResult > 0) { + isContactExist = true; + } + callback(isContactExist); + } + }, context); + } + + private buildContactList(contacts): Array { + let contactList: Array = []; + for (let contact of contacts) { + let item: LooseObject = {}; + item.contactName = contact.displayName; + item.headImage = "icon/user_avatar_full_fill.svg"; + item.telephone = contact.detailInfo; + item.telephoneFormat = contact.detailInfo; + item.select = false; + contactList.push(item); + } + return contactList; + } +} diff --git a/entry/src/main/ets/service/ConversationListService.ets b/entry/src/main/ets/service/ConversationListService.ets index b5187d3..9ea21fd 100644 --- a/entry/src/main/ets/service/ConversationListService.ets +++ b/entry/src/main/ets/service/ConversationListService.ets @@ -13,638 +13,531 @@ * limitations under the License. */ -import HiLog from "../utils/HiLog"; -import common from "../data/commonData"; -import ConversationListModel from "../model/ConversationListModel"; -import conversationService from "./ConversationService"; -import contractService from "./ContractService"; -import commonService from "./CommonService"; -import telephoneUtils from "../utils/TelephoneUtil"; -import LooseObject from "../data/LooseObject" +import HiLog from '../utils/HiLog'; +import common from '../data/commonData'; +import ConversationListModel from '../model/ConversationListModel'; +import ConversationService from './ConversationService'; +import ContactService from './ContactsService'; +import commonService from './CommonService'; +import telephoneUtils from '../utils/TelephoneUtil'; +import LooseObject from '../data/LooseObject' -let conversationListModel = new ConversationListModel(); const TAG = "ConversationListService"; -export default { - /** - * Querying list data - * - * @param actionData - * @callback callback - */ - querySessionList(actionData, callback) { - // Querying Data Lists - let result: LooseObject = {}; - let queryPromise = conversationListModel.querySessionList(actionData); - // Obtains the total number of records. - let countPromise = conversationListModel.countSessionList(actionData); - // Check whether the notification information exists. - let notificationPromise = new Promise((resolve) => { - this.judgeIsNotificationData(res => { - resolve(res); - }); - }); - Promise.all([queryPromise, countPromise, notificationPromise]).then((res) => { - result.code = common.int.SUCCESS; - let telephones = []; - let messageList = this.convertSessionList(res[0].response, telephones); - result.total = res[1].total; - result.hasInfoMsg = res[2]; - HiLog.i(TAG, "querySessionList, messageList length=" + messageList.length - + ", total=" + result.total + ", hasInfoMsg=" + result.hasInfoMsg); - this.dealContactsName(telephones, actionData, messageList, sessionList => { - HiLog.i(TAG, "querySessionList, dealContactsName len=" + sessionList.length); - result.response = sessionList; - callback(result); - }); - }).catch((err) => { - HiLog.e(TAG, "querySessionList, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, +export default class ConversationListService { + private static instance: ConversationListService; + private conversationListModel: ConversationListModel = new ConversationListModel(); - convertSessionList(sessionList, telephones) { - let messageList = []; - for (let session of sessionList) { - let item: LooseObject = {}; - item.name = common.string.EMPTY_STR; - item.contactsNum = session.contactsNum; - item.content = session.content; - item.countOfUnread = session.unreadCount; - if (session.smsType == 0) { - item.icon = "icon/user_avatar_full_fill.svg"; - } else { - item.icon = "icon/entrance_icon01.svg"; - } - item.smsType = session.smsType; - item.isCbChecked = false; - item.isLock = false; - item.sendingFailed = session.sendStatus == common.int.SEND_MESSAGE_FAILED ? true : false; - item.telephone = session.telephone; - if (item.contactsNum > 1) { - let telephoneSplit = item.telephone.split(common.string.COMMA); - for (let item of telephoneSplit) { - telephones.push(item); - } - } else { - telephones.push(item.telephone); - } - item.telephoneFormat = session.telephoneFormat; - item.threadId = session.id; - item.timeMillisecond = session.time; - item.isDraft = session.hasDraft == 1 ? true : false; - item.isLock = session.hasLock == 1 ? true : false; - item.time = common.string.EMPTY_STR; - item.messageCount = session.messageCount; - item.hasMms = session.hasMms == 1 ? true : false; - item.hasAttachment = session.hasAttachment == 1 ? true : false; - messageList.push(item); - } - return messageList; - }, + private constructor() { + } - dealContactsName(telephones, actionData, sessionLists, callback) { - actionData.telephones = telephones; - if (telephones.length == 0) { - HiLog.w(TAG, "dealContactsName, has no telephones"); - callback(sessionLists); - return; - } - contractService.queryContactDataByTelephone(actionData, contacts => { - if (contacts.length == 0) { - HiLog.w(TAG, "dealContactsName, has no contacts"); - callback(sessionLists); - } else { - // Convert the result to Map, key: mobile number, value: name - let telephoneMap = this.getTelephoneMap(contacts); - this.buildName(sessionLists, telephoneMap); - callback(sessionLists); - } - }); - }, - - getTelephoneMap(contacts) { - let telephoneMap = new Map(); - for (let item of contacts) { - if (item.displayName == common.string.EMPTY_STR) { - telephoneMap.set(item.detailInfo, item.detailInfo); - } else { - telephoneMap.set(item.detailInfo, item.displayName); - } - } - return telephoneMap; - }, - - buildName(sessionLists, telephoneMap) { - // Match the result based on the mobile number. - for (let session of sessionLists) { - // Indicates the combination of multiple names. The names need to be displayed in combination. - if (session.contactsNum > 1) { - this.dealMultiName(session, telephoneMap); - } else if (telephoneMap.has(session.telephone)) { - session.name = telephoneMap.get(session.telephone); - } - } - }, - - dealMultiName(session, telephoneMap) { - let telephones = session.telephone.split(common.string.COMMA); - let name = common.string.EMPTY_STR; - for (let telephone of telephones) { - if (telephoneMap.has(telephone)) { - name = name + telephoneMap.get(telephone) + common.string.COMMA; - } else { - name = name + telephone + common.string.COMMA; - } - } - session.name = name.substring(0, name.length - 1); - }, - - /** - * Check whether notification data exists. - * - * @callback callback - */ - judgeIsNotificationData(callback) { - let param = { - numberType: 1, - limit: 1, - page: 1 - }; - this.querySessionByNumberType(param, res => { - if (res.code == common.int.SUCCESS && res.response.length > 0) { - callback(true); - } else { - callback(false); - } - }); - }, - - /** - * statistical data - * - * @param actionData - * @callBack callBack - */ - statisticalData(actionData, callBack) { - let normalPromise = new Promise((resolve) => { - conversationListModel.statisticalData(actionData, res => { - let result: LooseObject = {}; - result.code = res.code; - if (res.code == common.int.SUCCESS) { - result.response = res.abilityResult; - resolve(result.response); - } else { - HiLog.w(TAG, "statisticalData, failed"); - } - }); - }); - let notifyPromise = new Promise((resolve) => { - conversationService.statisticsUnreadNotify(actionData, res => { - resolve(res); - }); - }); - Promise.all([normalPromise, notifyPromise]).then(res => { - let normalResult = res[0]; - let notifyResult = res[1]; - let response = { - "totalListCount": normalResult.totalListCount, - "unreadCount": (normalResult.totalListCount - notifyResult), - "unreadTotalOfInfo": notifyResult - } - let result = { - code: common.int.SUCCESS, - response: response - } - callBack(result); - }).catch(err => { - HiLog.e(TAG, "statisticalData, failed: " + JSON.stringify(err)); - let result = { - code: common.int.FAILURE - } - callBack(result); - }); - }, - - /** - * Delete data based on the primary key id. - * - * @param threadIds Session ID - */ - deleteMessageById(actionData) { - // Deletes data from the session list. - conversationListModel.deleteMessageById(actionData.threadIds); - // Deletes data from the information list. - conversationService.deleteMessageBySessionIds(actionData); - }, - - /** - * Delete data based on the primary key id. - * - * @param threadIds Session ID - */ - deleteMessageBySessionId(threadIds) { - // Deletes data from the session list. - conversationListModel.deleteMessageById(threadIds); - globalThis.needToUpdate = true; - }, - - /** - * Update data based on the primary key id. - * - * @param threadIds Session ID - * @param valueBucket - */ - updateById(threadIds, valueBucket) { - conversationListModel.updateById(threadIds, valueBucket); - globalThis.needToUpdate = true; - }, - - /** - * Marking a read SMS message - * - * @param actionData - */ - markAllAsRead(actionData) { - if (actionData.threadIds.length == 0) { - return; - } - // Tag on session list read - conversationListModel.markAllAsRead(actionData.threadIds, actionData.valueBucket); - // SMS message read - conversationService.markAllAsRead(actionData); - }, - - /** - * Updates all unread information to read. - * - * @param actionData - */ - markAllToRead(actionData) { - conversationListModel.markAllToRead(actionData.smsType); - conversationService.markAllToRead(actionData); - }, - - /** - * Add a new session list - * - * @param valueBucket New data - * @callback callback - */ - insertSession(valueBucket, callback) { - conversationListModel.insertSession(valueBucket, res => { - callback(res); - }); - }, - - /** - * Adding a session draft list - * - * @param valueBucket New Data - * @callback callback - */ - insertSessionDraft(actionData, callback) { - let param = this.dealSendResults(actionData); - // Check whether a session list has been created - this.querySessionByTelephone(param.telephone, res => { - let response = res.response; - if(res.code == common.int.SUCCESS && response.id <= 0) { - // If you modify the recipient in draft state and save the modification again, you need to delete the - // unnecessary session draft before modification. - if (actionData.threadId != 0) { - conversationListModel.deleteMessageById([actionData.threadId]); - } - this.dealInsertSession(param, actionData, callback); - } else { - this.deleteDraftDataOrUpdate(actionData, response, param, callback); - } - globalThis.needToUpdate = true; - }); - }, - - dealInsertSession(param, actionData, callback) { - let valueBucket = { - "telephone": param.telephone, - "content": param.content, - "contacts_num": param.contractsNum, - "sms_type": param.smsType, - "unread_count": 0, - "sending_status": 1, - "has_draft": 1, - "time": param.timestamp, - "has_mms": param.hasMms, - "has_attachment": param.hasAttachment, - } - this.insertSession(valueBucket, sessionResult => { - // Invoke the SMS database to insert SMS messages. - let sessionId = sessionResult.rowId; - conversationService.dealInsertMessageDetail(param, actionData, sessionId, res => { - callback(); - }); - }); - }, - - deleteDraftDataOrUpdate(actionData, response, param, callback) { - if (actionData.groupId > 0) { - let groupIds = [actionData.groupId]; - actionData.groupIds = groupIds; - // Delete the original draft first. - conversationService.deleteMessageByGroupIds(actionData); - } - if (actionData.content != common.string.EMPTY_STR || actionData.mmsSource.length > 0) { - // Save New Draft - this.updateDraftData(response, param, actionData, callback); - } else { - callback(); - } - }, - - updateDraftData(response, param, actionData, callback) { - let sessionId = response.id; - // Invoke the SMS database to insert SMS messages. - let threadIds = [sessionId]; - let time = new Date(); - let valueBucket = { - "content": param.content, - "has_draft": 1, - "time": time.getTime(), - "has_attachment": param.hasAttachment, - "has_mms": param.hasMms, - } - this.updateById(threadIds, valueBucket); - conversationService.dealInsertMessageDetail(param, actionData, sessionId, res => { - callback(); - }); - }, - - dealSendResults(actionData) { - let contractsNum = 1; - let telephone = common.string.EMPTY_STR; - if (actionData.isNewMsg) { - let selectContacts = actionData.selectContacts; - if (selectContacts.length > 1) { - for (let contact of selectContacts) { - telephone = telephone + contact.telephone + common.string.COMMA; - } - // If it fails, then the session list turns out to be a failure. - telephone = telephone.substring(0, telephone.length - 1); - contractsNum = selectContacts.length; - } else if (selectContacts.length == 1) { - telephone = selectContacts[0]?.telephone; - } - let receiveContactValue = actionData.receiveContactValue; - if (receiveContactValue != common.string.EMPTY_STR) { - telephone = actionData.receiveContactValue; - } - } else { - telephone = actionData.telephone; - } - let smsType = 0; - if (contractsNum == 1 && telephoneUtils.judgeIsInfoMsg(telephone)) { - smsType = 1; - } - let sendResult = { - telephone: telephone, - content: actionData.content, - sendStatus: common.int.SEND_DRAFT - } - actionData.sendResults = [sendResult]; - let timestamp = new Date().getTime(); - let result: LooseObject = {}; - result.contractsNum = contractsNum; - result.telephone = telephoneUtils.dealTelephoneSort(telephone); - result.content = actionData.content; - if (actionData.isMms) { - result.content = commonService.getMmsContent(actionData.mmsSource); - } - result.sendStatus = 1; - result.smsType = smsType; - result.timestamp = timestamp; - result.hasMms = actionData.isMms ? 1 : 0; - result.hasAttachment = actionData.hasAttachment ? 1 : 0; - return result; - }, - - /** - * Querying the session list by mobile number - * - * @param actionData - * @callback callback - */ - querySessionByNumberType(actionData, callback) { - let result: LooseObject = {}; - let queryPromise = conversationListModel.querySessionList(actionData); - Promise.all([queryPromise]).then((res) => { - result.code = common.int.SUCCESS; - result.response = res[0].response; - HiLog.i(TAG, "querySessionList SUCCESS. len=" + result.response.length); - callback(result); - }).catch((err) => { - HiLog.e(TAG, "querySessionByNumberType, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, - - /** - * Querying the session list by mobile number - * - * @param telephone - * @callback callback - */ - querySessionByTelephone(telephone, callback) { - let result: LooseObject = {}; - if (telephone == null) { - HiLog.w(TAG, "querySesByTele, telephone == null") - result.code = common.int.FAILURE; - callback(result); - } else { - HiLog.i(TAG, "querySesByTele, telephone != null") - let queryPromise = conversationListModel.querySessionByTelephone(telephone); - Promise.all([queryPromise]).then((res) => { - result.code = common.int.SUCCESS; - result.response = res[0]; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "querySesByTele, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - } - }, - - /** - * Querying the session list by mobile number - * - * @param telephone - * @callback callback - */ - querySessionById(threadId, callback) { - let result: LooseObject = {}; - HiLog.i(TAG, "querySessionById, threadId:" + threadId); - let queryPromise = conversationListModel.querySessionById(threadId); - Promise.all([queryPromise]).then((res) => { - result.code = common.int.SUCCESS; - result.response = res[0]; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "querySessionById, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, - - deleteMessageBySessionIdsAndLock(actionData) { - conversationService.deleteMessageBySessionIdsAndLock(actionData); - }, - - dealMessageLockContent(actionData, callback) { - let threadIds = actionData.threadIds; - let length = threadIds.length; - let count = 0; - for (let id of threadIds) { - actionData.threadId = id; - if (!actionData.isMessageDetail) { - actionData.hasLock = 1; - } - conversationService.queryMessageDetail(actionData, res => { - if (res.code == common.int.SUCCESS && res.response.length > 0) { - count++; - actionData.mmsList = res.response; - this.updateLastItemContent(actionData); - } - if (count == length) { - callback(common.int.SUCCESS); - } - }); - } - }, - - updateLastItemContent(actionData) { - let length = actionData.mmsList.length; - let item = actionData.mmsList[length - 1]; - let content = item.content || ''; - let threadIds = [actionData.threadId]; - let hasAttachment = false; - if (item.isMsm) { - content = commonService.getMmsContent(item.mms); - hasAttachment = true; - } - let valueBucket = { - "content": content, - "sending_status": item.sendStatus, - "has_mms": item.isMsm ? 1 : 0, - "has_attachment": hasAttachment ? 1 : 0, - "message_count": length, - "unread_count": 0 - }; - this.updateById(threadIds, valueBucket); - }, - - /** - * Search message with text - * - * @param actionData - * @callback callback - */ - searchMessageWithLike(actionData, callback) { - // Session Details Search Data - let searchText = actionData.inputValue; - let sessionListPromise = new Promise((resolve, reject) => { - this.searchSessionByTelephone(actionData, res => { - if (res.code === common.int.SUCCESS) { - resolve(res.response); - } else { - reject(res.code); - } - }); - }); - // Information List Search Data - let contentListPromise = new Promise((resolve, reject) => { - conversationService.searchMessageByContent(actionData, res => { - if (res.code === common.int.SUCCESS) { - resolve(res.response); - } else { - reject(res.code); - } - }); - }); - let resultMap: LooseObject = {}; - let result: LooseObject = {}; - Promise.all([sessionListPromise, contentListPromise]).then((res) => { - result.code = common.int.SUCCESS; - resultMap.sessionList = res[0]; - resultMap.contentList = res[1]; - result.resultMap = resultMap; - result.search = searchText; - callback(result); - }).catch((err) => { - HiLog.e(TAG, "searchMessageWithLike, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, - - /** - * Fuzzy match of the session list based on the mobile number - * - * @param actionData - * @callback callback - */ - async searchSessionByTelephone(actionData, callback) { - let result: LooseObject = {}; - let telephone = actionData.inputValue; - let numberType = actionData.numberType; - let queryPromise = conversationListModel.searchSessionByTelephone(telephone, numberType); - queryPromise.then((res) => { - result.code = common.int.SUCCESS; - let telephones = []; - let messageList = this.convertSessionList(res, telephones); - this.dealContactsName(telephones, actionData, messageList, sessionList => { - result.response = this.dealSessionLikeData(sessionList); - callback(result); - }); - }).catch((err) => { - HiLog.e(TAG, "searchSessionByTelephone, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, - - dealSessionLikeData(mmList) { - let sessionList = []; - for (let item of mmList) { - let map: LooseObject = {} - map.name = item.name; - map.threadId = item.threadId; - map.telephone = item.telephone; - map.telephoneFormat = item.telephoneFormat; - map.contactsNum = item.contactsNum; - map.isDraft = item.isDraft; - let names = item.name.split(common.string.COMMA); - let telephones = item.telephone.split(common.string.COMMA); - let telephoneFormats = item.telephoneFormat.split(common.string.COMMA); - let nameFormatter = common.string.EMPTY_STR; - let index = 0; - for (let name of names) { - nameFormatter += (name == null || name == common.string.EMPTY_STR ? telephones[index] : name); - nameFormatter += "<"; - nameFormatter += telephoneFormats[index]; - nameFormatter += ">"; - if (index < telephones.length - 1) { - nameFormatter += common.string.COMMA; - } - index++; - } - map.nameFormatter = nameFormatter; - map.date = common.string.EMPTY_STR; - map.time = common.string.EMPTY_STR; - map.timeMillisecond = item.timeMillisecond; - map.size = item.messageCount; - map.icon = item.icon; - sessionList.push(map); - } - return sessionList; + public static getInstance(): ConversationListService { + if (ConversationListService.instance == null) { + ConversationListService.instance = new ConversationListService(); } + return ConversationListService.instance; + } + + public insertSession(valueBucket, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.insertSession, { + valueBucket: valueBucket, + context: mmsContext + }, res => { + if (callback) { + callback(res); + } + }); + } else { + this.conversationListModel.insertSession(valueBucket, callback, mmsContext); + } + globalThis.needToUpdate = true; + } + + public deleteSessionByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.deleteSessionByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + if (callback) { + callback(res); + } + }); + } else { + this.conversationListModel.deleteSessionByCondition(actionData, callback, mmsContext); + } + globalThis.needToUpdate = true; + } + + public updateSessionByCondition(actionData, valueBucket, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.updateSessionByCondition, { + actionData: actionData, + valueBucket: valueBucket, + context: mmsContext + }, res => { + if (callback) { + callback(res); + } + }); + } else { + this.conversationListModel.updateSessionByCondition(actionData, valueBucket, callback, mmsContext); + } + globalThis.needToUpdate = true; + } + + public querySessionByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.querySessionByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationListModel.querySessionByCondition(actionData, callback, mmsContext); + } + } + + public querySessionSizeByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.querySessionSizeByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationListModel.querySessionSizeByCondition(actionData, callback, mmsContext); + } + } + + public async getSessionListSize(actionData, context): Promise { + let condition: LooseObject = {}; + condition.smsType = actionData.smsType; + let result: Promise = new Promise((resolve) => { + this.querySessionSizeByCondition(condition, res => { + let size: number = 0; + if (res.code == common.int.SUCCESS && res.abilityResult != null) { + size = res.abilityResult; + } + resolve(size); + }, context); + }); + return result; + } + + public getSessionListResult(actionData, context): Promise { + let result: Promise = new Promise((resolve) => { + this.querySessionByCondition(actionData, res => { + let result: LooseObject = { + "messageList": [], + "telephones": [] + }; + if (res.code == common.int.SUCCESS && res.abilityResult != null) { + result = this.getConvertSessionListResult(res.abilityResult); + } + resolve(result); + }, context) + }); + return result; + } + + public isExistNoticeMessage(context): Promise { + let result: Promise = new Promise((resolve) => { + let actionData: LooseObject = {}; + actionData.smsType = common.sms_type.NOTICE; + this.querySessionSizeByCondition(actionData, res => { + let isExistNoticeMessage: boolean = false; + if (res.code == common.int.SUCCESS && res.abilityResult != null && res.abilityResult > 0) { + isExistNoticeMessage = true; + } + resolve(isExistNoticeMessage); + }, context); + }); + return result; + } + + public querySessionList(actionData, callback, context): void { + let result: LooseObject = {}; + let queryPromise: Promise = this.getSessionListResult(actionData, context); + let countPromise: Promise = this.getSessionListSize(actionData, context); + let noticePromise: Promise = this.isExistNoticeMessage(context); + Promise.all([queryPromise, countPromise, noticePromise]).then(res => { + result.code = common.int.SUCCESS; + result.total = res[1]; + result.hasInfoMsg = res[2]; + result.response = []; + HiLog.i(TAG, "querySessionList, sessionList.length: " + res[0].messageList.length + ", total=" + result.total + + ", hasInfoMsg=" + result.hasInfoMsg); + if (result.total > 0) { + this.dealContactsName(res[0].telephones, actionData, res[0].messageList, res => { + result.response = res; + callback(result); + }, context); + } else { + callback(result); + } + }).catch(error => { + HiLog.e(TAG, "querySessionList, error: " + JSON.stringify(error)); + result.code = common.int.FAILURE; + callback(result); + }); + } + + private getConvertSessionListResult(sessionList): LooseObject { + let result: LooseObject = { + "messageList": [], + "telephones": [] + }; + if (sessionList == null) { + return result; + } + let messageList: Array = []; + let telephones: Array = []; + for (let session of sessionList) { + let item: LooseObject = {}; + item.name = common.string.EMPTY_STR; + item.contactsNum = session.contactsNum; + item.content = session.content; + item.countOfUnread = session.unreadCount; + if (session.smsType == common.sms_type.COMMON) { + item.icon = "icon/user_avatar_full_fill.svg"; + } else { + item.icon = "icon/entrance_icon01.svg"; + } + item.smsType = session.smsType; + item.isCbChecked = false; + item.isLock = false; + item.sendingFailed = session.sendStatus == common.int.SEND_MESSAGE_FAILED ? true : false; + item.telephone = session.telephone; + if (item.contactsNum > 1) { + let telephoneSplit = item.telephone.split(common.string.COMMA); + for (let item of telephoneSplit) { + telephones.push(item); + } + } else { + telephones.push(item.telephone); + } + item.telephoneFormat = session.telephoneFormat; + item.threadId = session.id; + item.timeMillisecond = session.time; + item.isDraft = session.hasDraft == 1 ? true : false; + item.isLock = session.hasLock == 1 ? true : false; + item.time = common.string.EMPTY_STR; + item.messageCount = session.messageCount; + item.hasMms = session.hasMms == 1 ? true : false; + item.hasAttachment = session.hasAttachment == 1 ? true : false; + messageList.push(item); + } + result.messageList = messageList; + result.telephones = telephones; + return result; + } + + private dealContactsName(telephones, actionData, sessionLists, callback, context) { + if (telephones.length == 0) { + HiLog.w(TAG, "dealContactsName, has no telephones"); + callback(sessionLists); + return; + } + actionData.telephones = telephones; + actionData.hasDelete = "0"; + ContactService.getInstance().queryContactDataByCondition(actionData, res => { + if (res.code == common.int.FAILURE || res.abilityResult.length == 0) { + HiLog.w(TAG, "dealContactsName, has no contacts"); + callback(sessionLists); + } else { + callback(this.buildSessionNames(res.abilityResult, sessionLists)); + } + }, context); + } + + private buildSessionNames(contacts, sessionLists) { + let telephoneMap = new Map(); + for (let item of contacts) { + if (item.displayName == common.string.EMPTY_STR) { + telephoneMap.set(item.detailInfo, item.detailInfo); + } else { + telephoneMap.set(item.detailInfo, item.displayName); + } + } + for (let session of sessionLists) { + if (session.contactsNum > 1) { + this.dealMultiName(session, telephoneMap); + } else if (telephoneMap.has(session.telephone)) { + session.name = telephoneMap.get(session.telephone); + } + } + return sessionLists; + } + + private dealMultiName(session, telephoneMap): void { + let telephones: Array = session.telephone.split(common.string.COMMA); + let name: string = common.string.EMPTY_STR; + for (let telephone of telephones) { + if (telephoneMap.has(telephone)) { + name = name + telephoneMap.get(telephone) + common.string.COMMA; + } else { + name = name + telephone + common.string.COMMA; + } + } + session.name = name.substring(0, name.length - 1); + } + + public statisticalData(callBack, context): void { + let normalPromise = new Promise((resolve) => { + ConversationService.getInstance().statisticalData(res => { + if (res.code == common.int.SUCCESS) { + resolve(res.abilityResult); + } else { + HiLog.w(TAG, "statisticalData, failed"); + } + }, context); + }); + let notifyPromise = new Promise((resolve) => { + ConversationService.getInstance().statisticsUnreadNotify(res => { + resolve(res); + }, context); + }); + let result: LooseObject = {}; + Promise.all([normalPromise, notifyPromise]).then(res => { + let normalResult: LooseObject = res[0]; + let notifyResult: number = res[1]; + result.code = common.int.SUCCESS; + let response: LooseObject = {}; + response.totalListCount = normalResult.totalListCount; + response.unreadCount = normalResult.totalListCount - notifyResult; + response.unreadTotalOfInfo = notifyResult; + result.response = response; + callBack(result); + }).catch(error => { + HiLog.e(TAG, "statisticalData, failed: " + JSON.stringify(error)); + result.code = common.int.FAILURE; + callBack(result); + }); + } + + public deleteMessageById(actionData, callback, context): void { + // Deletes data from the session list. + this.deleteSessionByCondition(actionData, callback, context); + // Deletes data from the information list. + ConversationService.getInstance().deleteSmsMmsInfoByCondition(actionData, null, null); + } + + public markAllToRead(actionData) { + actionData.unreadCount_greaterThan = 0; + let sessionValueBucket: LooseObject = { + "unread_count": 0 + }; + this.updateSessionByCondition(actionData, sessionValueBucket, null, null); + + actionData.hasRead = common.is_read.UN_READ; + let smsMmsInfoValueBucket: LooseObject = { + "is_read": common.is_read.READ + }; + ConversationService.getInstance().updateSmsMmsInfoByCondition(actionData, smsMmsInfoValueBucket, null, null); + } + + /** + * Adding a session draft list + * + * @param valueBucket New Data + * @callback callback + */ + public insertSessionDraft(actionData, callback, context): void { + let param: LooseObject = this.dealSendResults(actionData); + // Check whether a session list has been created + this.querySessionByTelephone(param.telephone, res => { + if (res.code == common.int.SUCCESS && res.response.id <= 0) { + // If you modify the recipient in draft state and save the modification again, you need to delete the + // unnecessary session draft before modification. + if (actionData.threadId != 0 && actionData.isDraft) { + this.deleteSessionByCondition(actionData, null, null); + } + this.dealInsertSession(param, actionData, callback, context); + } else { + this.deleteDraftDataOrUpdate(actionData, res.response, param, callback, context); + } + globalThis.needToUpdate = true; + }, context); + } + + public dealInsertSession(param, actionData, callback, context): void { + let valueBucket: LooseObject = { + "telephone": param.telephone, + "content": param.content, + "contacts_num": param.contactsNum, + "sms_type": param.smsType, + "unread_count": 0, + "sending_status": common.int.SEND_MESSAGE_SENDING, + "has_draft": common.has_draft.HAVE, + "time": param.timestamp, + "has_mms": param.hasMms, + "has_attachment": param.hasAttachment, + } + this.insertSession(valueBucket, sessionResult => { + // Invoke the SMS database to insert SMS messages. + let sessionId: number = sessionResult.abilityResult; + ConversationService.getInstance().dealInsertMessageDetail(param, actionData, sessionId, res => { + callback(); + }, context); + }, context); + } + + public deleteDraftDataOrUpdate(actionData, response, param, callback, context): void { + if (actionData.groupId > 0) { + ConversationService.getInstance().deleteSmsMmsInfoByCondition(actionData, null, null); + } + if (actionData.content != common.string.EMPTY_STR || actionData.mmsSource.length > 0) { + // Save New Draft + this.updateDraftData(response, param, actionData, callback, context); + } else { + if (callback) { + callback(); + } + } + } + + public updateDraftData(response, param, actionData, callback, context): void { + let valueBucket: LooseObject = { + "content": param.content, + "has_draft": common.has_draft.HAVE, + "time": new Date().getTime(), + "has_attachment": param.hasAttachment, + "has_mms": param.hasMms, + } + let sessionId: number = response.id; + let condition: LooseObject = {}; + condition.threadId = sessionId; + this.updateSessionByCondition(condition, valueBucket, null, null); + ConversationService.getInstance().dealInsertMessageDetail(param, actionData, sessionId, res => { + if (callback) { + callback(); + } + }, context); + } + + public dealSendResults(actionData): LooseObject { + let contactsNum: number = 1; + let telephone: string = common.string.EMPTY_STR; + if (actionData.isNewMsg) { + let selectContacts = actionData.selectContacts; + if (selectContacts.length > 1) { + for (let contact of selectContacts) { + telephone = telephone + contact.telephone + common.string.COMMA; + } + // If it fails, then the session list turns out to be a failure. + telephone = telephone.substring(0, telephone.length - 1); + contactsNum = selectContacts.length; + } else if (selectContacts.length == 1) { + telephone = selectContacts[0]?.telephone; + } + let receiveContactValue = actionData.receiveContactValue; + if (receiveContactValue != common.string.EMPTY_STR) { + telephone = actionData.receiveContactValue; + } + } else { + telephone = actionData.telephone; + } + let smsType: number = common.sms_type.COMMON; + if (contactsNum == 1 && telephoneUtils.judgeIsInfoMsg(telephone)) { + smsType = common.sms_type.NOTICE; + } + let sendResult: LooseObject = { + telephone: telephone, + content: actionData.content, + sendStatus: common.int.SEND_DRAFT + } + actionData.sendResults = [sendResult]; + let timestamp = new Date().getTime(); + let result: LooseObject = {}; + result.contactsNum = contactsNum; + result.telephone = telephoneUtils.dealTelephoneSort(telephone); + result.content = actionData.content; + if (actionData.isMms) { + result.content = commonService.getMmsContent(actionData.mmsSource); + } + result.sendStatus = common.int.SEND_MESSAGE_SENDING; + result.smsType = smsType; + result.timestamp = timestamp; + result.hasMms = actionData.isMms ? 1 : 0; + result.hasAttachment = actionData.hasAttachment ? 1 : 0; + + return result; + } + + public querySessionByTelephone(telephone, callback, context): void { + let result: LooseObject = {}; + if (telephone == null) { + HiLog.w(TAG, "querySessionByTelephone, telephone is null!"); + result.code = common.int.FAILURE; + callback(result); + } else { + HiLog.i(TAG, "querySessionByTelephone, telephone != null"); + let actionData: LooseObject = {}; + actionData.telephone = telephone; + this.querySessionByCondition(actionData, res => { + if (res.code == common.int.FAILURE) { + callback(res); + } else { + result.code = common.int.SUCCESS; + result.response = res.abilityResult[0]; + callback(result); + } + }, context); + } + } + + public dealMessageLockContent(actionData, callback, context): void { + let threadIds = actionData.threadIds; + let length: number = threadIds.length; + let count: number = 0; + for (let id of threadIds) { + actionData.threadId = id; + if (!actionData.isMessageDetail) { + actionData.hasLock = 1; + } + ConversationService.getInstance().queryMessageDetail(actionData, res => { + if (res.code == common.int.SUCCESS && res.response.length > 0) { + count++; + actionData.mmsList = res.response; + this.updateLastItemContent(actionData, null, null); + } + if (count == length) { + callback(common.int.SUCCESS); + } + }, context); + } + } + + public updateLastItemContent(actionData, callback, context): void { + let valueBucket: LooseObject = { + "content": common.string.EMPTY_STR, + "sending_status": common.int.SEND_MESSAGE_FAILED, + "has_mms": common.has_mms.NO, + "has_attachment": common.has_attachment.NO, + "message_count": 0, + "unread_count": 0 + }; + let length: number = actionData.mmsList.length; + if (length > 0) { + let item: LooseObject = actionData.mmsList[length - 1]; + valueBucket.content = item.isMsm ? commonService.getMmsContent(item.mms) : item.content; + valueBucket.sending_status = item.sendStatus; + valueBucket.has_mms = item.isMsm ? common.has_mms.HAVE : common.has_mms.NO; + valueBucket.has_attachment = item.isMsm ? common.has_attachment.HAVE : common.has_attachment.NO; + valueBucket.message_count = length; + } + let condition: LooseObject = { + threadId: actionData.threadId + }; + this.updateSessionByCondition(condition, valueBucket, callback, context); + } } \ No newline at end of file diff --git a/entry/src/main/ets/service/ConversationService.ets b/entry/src/main/ets/service/ConversationService.ets index 451c293..5dcce76 100644 --- a/entry/src/main/ets/service/ConversationService.ets +++ b/entry/src/main/ets/service/ConversationService.ets @@ -13,1154 +13,601 @@ * limitations under the License. */ -import ContactsModel from "../model/ContactsModel"; import ConversationModel from "../model/ConversationModel"; import common from "../data/commonData"; import HiLog from "../utils//HiLog"; -import conversationListService from "./ConversationListService"; +import ConversationListService from "./ConversationListService"; import telephoneUtils from "../utils/TelephoneUtil"; -import contractService from "./ContractService"; -import commonService from "./CommonService"; -import LooseObject from "../data/LooseObject" -import MmsPreferences from "../utils/MmsPreferences"; +import ContactsService from "./ContactsService"; +import LooseObject from "../data/LooseObject"; -const TAG = "ConversationService"; +const TAG: string = "ConversationService"; -let mConversationModel = new ConversationModel(); +export default class ConversationService { + private static instance: ConversationService; + private conversationModel: ConversationModel = new ConversationModel(); -export default { + private constructor() { + } - /** - * Check whether a contact exists. - * - * @param params contact phone number - * @callback Whether the contact exists - */ - judgeContactExists(actionData, callback) { - globalThis.DataWorker.sendRequest("queryContactDataByTelephone", { - actionData: actionData, - context: globalThis.mmsContext - }, result => { - let hasExitContract = false; - if (result.length >= 1) { - // Whether the contact exists - hasExitContract = true; - } - callback(hasExitContract); - }); - }, + public static getInstance(): ConversationService { + if (ConversationService.instance == null) { + ConversationService.instance = new ConversationService(); + } + return ConversationService.instance; + } - /** - * Obtain information details. - * - * @param params phone number/session id - * @callback callback - */ - queryMessageDetail(actionData, callback) { - globalThis.DataWorker.sendRequest("queryMessageDetail", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - let result: LooseObject = {}; - result.code = res.code; - if (res.code == common.int.SUCCESS) { - this.groupDetailMessage(res.abilityResult, actionData, resultList => { - result.response = resultList; - callback(result); - }); - } else { - HiLog.w(TAG, "queryMessageDetail, failed"); - callback(result); - } - }); - }, - - convertConversationList(mmsList) { - let resultList = []; - for (let item of mmsList) { - let result: LooseObject = {}; - result.id = item.msgId; - result.content = item.msgContent; - result.isLock = item.isLock == 0 ? false : true; - result.isStared = item.isCollect == 0 ? false : true; - // Fields related to MMS messages - result.msgType = 0; - result.isFullScreenImg = true; - result.read = item.isRead == 0 ? "0" : "1"; - if (item.msgState == 0) { - result.sendStatus = common.int.SEND_MESSAGE_SUCCESS; - } else if (item.msgState == 2) { - result.sendStatus = common.int.SEND_MESSAGE_FAILED; - } else if (item.msgState == 1) { - result.sendStatus = common.int.SEND_MESSAGE_SENDING; - } else { - result.sendStatus = common.int.SEND_DRAFT; - } - result.subId = item.slotId; - result.timeMillisecond = item.startTime; - result.isMsm = item.msgType == 0 ? false : true; - result.isCbChecked = false; - result.isDraft = false; - // Fields related to group-sending - result.groupId = item.groupId; - // Determine whether it is the receiver or sender. - result.isReceive = item.isSender == 0 ? false : true; - result.date = common.string.EMPTY_STR; - result.time = common.string.EMPTY_STR; - result.completeNumber = 0; - result.failuresNumber = 0; - result.hasReport = item.isSendReport == 0 ? false : true; - if (!result.isMsm) { - result.msgShowType = common.MESSAGE_SHOW_TYPE.NORMAL; - } - resultList.push(result); + public insertSmsMmsInfo(valueBucket, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.insertSmsMmsInfo, { + valueBucket: valueBucket, + context: mmsContext + }, res => { + if (callback) { + callback(res); } - return resultList; - }, + }); + } else { + this.conversationModel.insertSmsMmsInfo(valueBucket, callback, mmsContext); + } + } - groupDetailMessage(mmsList, actionData, callback) { - let details = this.convertConversationList(mmsList); - let msgIds = []; - if (actionData.contactsNum == 1) { - for (let item of details) { - if (item.isMsm) { - msgIds.push(item.id); - } - } - this.dealMmsPartData(details, msgIds, actionData, res => { - callback(res); - }); - return; + public deleteSmsMmsInfoByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.deleteSmsMmsInfoByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + if (callback) { + callback(res); } - let resultList = []; - // Group by groupId. - let detailMap = this.convertConversationMap(details); - // By group - let groupIds = detailMap.keys(); - for (let groupId of groupIds) { - let groups = detailMap.get(groupId); - let result = groups[0]; - let failuresNumber = 0; - let completeNumber = 0; - if (result.isMsm) { - msgIds.push(result.id); - } - for (let item of groups) { - if (item.sendStatus == common.int.SEND_MESSAGE_FAILED) { - failuresNumber++; - } - if (item.sendStatus == common.int.SEND_MESSAGE_FAILED || - item.sendStatus == common.int.SEND_MESSAGE_SUCCESS) { - completeNumber++; - } - } - result.completeNumber = completeNumber; - result.failuresNumber = failuresNumber; - resultList.push(result); + }); + } else { + this.conversationModel.deleteSmsMmsInfoByCondition(actionData, callback, mmsContext); + } + } + + public updateSmsMmsInfoByCondition(actionData, valueBucket, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.updateSmsMmsInfoByCondition, { + actionData: actionData, + valueBucket: valueBucket, + context: mmsContext + }, res => { + if (callback) { + callback(res); } - this.dealMmsPartData(resultList, msgIds, actionData, res => { - callback(res); - }); - }, - - dealMmsPartData(resultList, msgIds, actionData, callback) { - if (msgIds.length == 0) { - callback(resultList); - return; - } - actionData.msgIds = msgIds; - this.queryMmsPartByIds(actionData, res => { - let mmsParts = res.response; - let mmsPartMap = new Map(); - for (let item of mmsParts) { - if (mmsPartMap.has(item.msgId)) { - let strings = mmsPartMap.get(item.msgId); - strings.push(item); - } else { - let strings = []; - strings.push(item); - mmsPartMap.set(item.msgId, strings); - } - } - for (let item of resultList) { - if (mmsPartMap.has(item.id)) { - let mmsParts = mmsPartMap.get(item.id); - // Determine whether to display 0 common style, 1 theme, and 2 slides, - item.mms = commonService.getMmsSource(mmsParts); - item.msgShowType = commonService.getDisplay(item.mms); - commonService.setItemMmsContent(item, item.mms); - } - } - callback(resultList); - }); - }, - - convertConversationMap(details) { - let conversationMap = new Map(); - // grouping - for (let element of details) { - if (conversationMap.has(element.groupId)) { - let groups = conversationMap.get(element.groupId); - groups.push(element); - } else { - let groups = []; - groups.push(element); - conversationMap.set(element.groupId, groups); - } - } - return conversationMap; - }, - - /** - * Inserting session details and sms details - * - * @param actionData - * @callback callback - */ - insertSessionAndDetail(actionData, callback): void { - let sendResults: Array = actionData.sendResults; - let isReceive: boolean = actionData.isReceive; - if (sendResults.length == 0) { - HiLog.w(TAG, "insertSessionAndDetail, sendResults.length == 0"); - return; - } - let param: LooseObject = this.dealSendResults(sendResults); - // Check whether a session list has been created. - conversationListService.querySessionByTelephone(param.telephone, res => { - let response = res.response; - if (res.code == common.int.SUCCESS && response.id <= 0) { - this.dealNoExitingSession(isReceive, param, actionData, callback); - } else { - this.dealExitingSession(response, param, actionData, callback); - } - }); - }, - - dealNoExitingSession(isReceive, param, actionData, callback) { - let unreadCount = 0; - if (isReceive) { - unreadCount = 1; - } - let valueBucket: LooseObject = { - "telephone": param.telephone, - "content": param.content, - "contacts_num": param.contractsNum, - "sms_type": param.smsType, - "unread_count": unreadCount, - "sending_status": param.sendStatus, - "has_draft": 0, - "time": param.timestamp, - "message_count": 1, - "has_mms": actionData.isMms ? 1 : 0, - "has_attachment": actionData.hasAttachment ? 1 : 0 - } - conversationListService.insertSession(valueBucket, sessionResult => { - HiLog.i(TAG, "dealNoExitingSession, insertSession callback"); - // Invoke the SMS database to insert SMS messages. - this.dealInsertMessageDetail(param, actionData, sessionResult.rowId, res => { - let result = { - rowId: sessionResult.rowId, - initDatas: res.initDatas, - groupId: res.groupId - } - callback(result); - }); - }); - }, - - dealExitingSession(response, param, actionData, callback): void { - let sessionId = response.id; - // Invoke the SMS database to insert SMS messages. - let threadIds = [sessionId]; - let time = new Date(); - let unreadCount: number = 0; - if (actionData.isReceive) { - unreadCount = response.unreadCount; - unreadCount = unreadCount + 1; - } - let hasDraft = response.hasDraft; - if (actionData.hasDraft && hasDraft == 1) { - hasDraft = 0; - } - let messageCount = response.messageCount; - messageCount = messageCount + 1; - let valueBucket: LooseObject = { - "content": param.content, - "unread_count": unreadCount, - "time": time.getTime(), - "sending_status": param.sendStatus, - "has_draft": hasDraft, - "message_count": messageCount, - "has_attachment": actionData.hasAttachment ? 1 : 0, - "has_mms": actionData.isMms ? 1 : 0, - } - conversationListService.updateById(threadIds, valueBucket); - // Invoke the SMS database to insert SMS messages. - this.dealInsertMessageDetail(param, actionData, sessionId, res => { - let result: LooseObject = { - rowId: sessionId, - initDatas: res.initDatas, - groupId: res.groupId - } - callback(result); - }); - }, - - dealInsertMessageDetail(param, actionData, threadId, callback) { - this.queryMaxGroupId(actionData, res => { - let maxGroupId: number = 0; - if (res.code === common.int.SUCCESS) { - HiLog.i(TAG, "dealInsertMessageDetail, queryMaxGroupId maxGroupId=" + res.response.maxGroupId) - maxGroupId = res.response.maxGroupId == common.string.EMPTY_STR ? 0 : Number(res.response.maxGroupId); - maxGroupId = maxGroupId + 1; - } else { - HiLog.w(TAG, "dealInsertMessageDetail, queryMaxGroupId failed"); - callback(); - } - this.insertMessageDetailByMaxGroupId(param, actionData, threadId, maxGroupId, result => { - callback(result); - }); - }); - }, - - insertMessageDetailByMaxGroupId(param, actionData, threadId, maxGroupId, callback) { - let count: number = 0; - let initDatas: Array = []; - let result: LooseObject = {}; - result.groupId = maxGroupId; - let sendResults = actionData.sendResults; - sendResults.forEach(sendResult => { - let insertDetail: LooseObject = this.initInsertDetail(param, actionData, threadId, maxGroupId); - if (actionData.isReceive) { - insertDetail.receiverNumber = actionData.ownNumber; - insertDetail.senderNumber = sendResult.telephone; - insertDetail.isRead = 0; - } else { - insertDetail.receiverNumber = sendResult.telephone; - insertDetail.senderNumber = actionData.ownNumber; - insertDetail.isRead = 1; - } - insertDetail.sendStatus = sendResult.sendStatus; - if (sendResult.sendStatus == common.int.SEND_MESSAGE_FAILED) { - insertDetail.sendStatus = 2; - } else if (sendResult.sendStatus == common.int.SEND_MESSAGE_SUCCESS) { - insertDetail.sendStatus = 0; - } - if (sendResult.time != null) { - insertDetail.time = sendResult.time; - } - if (sendResult.slotId != null) { - insertDetail.slotId = sendResult.slotId; - } - this.insertMessageDetail(insertDetail, id => { - HiLog.d(TAG, "insertMessageDetailByMaxGroupId, insertMessageDetail id=" + id); - count++; - let initData: LooseObject = { - id: id, - telephone: sendResult.telephone - }; - initDatas.push(initData); - if (count == actionData.sendResults.length) { - result.initDatas = initDatas; - callback(result); - } - }); - }) - }, - - initInsertDetail(param, actionData, threadId, maxGroupId) { - let insertDetail: LooseObject = { - slotId: common.int.SIM_ONE, - receiverNumber: common.string.EMPTY_STR, - senderNumber: common.string.EMPTY_STR, - smsType: param.smsType, - content: param.content, - sendStatus: common.int.SEND_MESSAGE_FAILED, - sessionType: 0, - threadId: threadId, - isSender: actionData.isSender, - groupId: maxGroupId, - time: common.string.EMPTY_STR, - hasReport: actionData.hasReport, - isMms: actionData.isMms, - mmsSource: actionData.mmsSource, - messageType: actionData.messageType - }; - return insertDetail; - }, - - dealSendResults(sendResults: Array): LooseObject { - let contractsNum: number = sendResults.length; - let telephone: string = common.string.EMPTY_STR; - let content: string = common.string.EMPTY_STR; - let sendStatus: number = common.int.SEND_MESSAGE_SUCCESS; - let failSum: number = 0; - let time = common.string.EMPTY_STR; - for (let sendResult of sendResults) { - telephone = telephone + sendResult.telephone + common.string.COMMA; - content = sendResult.content; - sendStatus = sendResult.sendStatus; - if (sendResult.sendStatus == common.int.SEND_MESSAGE_FAILED) { - failSum++; - } - if (sendResult.time != null) { - time = sendResult.time; - } - if (sendResult.isMessageSim != null && sendResult.isMessageSim) { - telephone = sendResult.telephone; - contractsNum = 1; - } - } - // If it fails, then the session list turns out to be a failure. - if (failSum > 0) { - sendStatus = common.int.SEND_MESSAGE_FAILED; - } - telephone = telephone.substring(0, telephone.length - 1); - let smsType: number = 0; - if (contractsNum == 1 && telephoneUtils.judgeIsInfoMsg(telephone)) { - smsType = 1; - } - let result: LooseObject = {}; - let timestamp = new Date().getTime(); - result.contractsNum = contractsNum; - result.content = content; - result.telephone = telephoneUtils.dealTelephoneSort(telephone); - result.sendStatus = sendStatus; - result.timestamp = time != common.string.EMPTY_STR ? time : timestamp; - result.smsType = smsType; - return result; - }, - - /** - * Inserting sms messages - * - * @param actionData session ids - * @callback callback - */ - insertMessageDetail(param, callback) { - let actionData: LooseObject = {}; - let time = new Date(); - let timeStr = param.time != common.string.EMPTY_STR ? param.time : time.getTime() + common.string.EMPTY_STR; - let stringValue: LooseObject = { - "slot_id": common.int.SIM_ONE, - "receiver_number": param.receiverNumber, - "sender_number": param.senderNumber, - "start_time": timeStr, - "end_time": timeStr, - "msg_type": param.isMms ? "1" : "0", - "sms_type": param.smsType, - "msg_title": param.content, - "msg_content": param.content, - "msg_state": param.sendStatus, - "operator_service_number": common.string.EMPTY_STR, - "msg_code": common.string.EMPTY_STR, - "session_id": param.threadId, - "is_lock": "0", - "is_read": param.isRead, - "is_collect": "0", - "session_type": param.sessionType, - "is_sender": param.isSender, - "group_id": param.groupId, - "is_send_report": param.hasReport - }; - if (param.slotId != null) { - stringValue.slot_id = param.slotId; - } - actionData.stringValue = stringValue; - actionData.featureAbility = param.featureAbility; - globalThis.DataWorker.sendRequest("insertMessageDetail", { - actionData: actionData, - context: globalThis.mmsContext - }, result => { - if (result.code == common.int.SUCCESS) { - this.dealBatchInsertMmsPart(param, result, callback); - } else { - HiLog.w(TAG, "insertMessageDetail, fail"); - } - }); - }, - - dealBatchInsertMmsPart(param, result, callback) { - if (param.isMms) { - param.msgId = result.abilityResult; - this.batchInsertMmsPart(param, res => { - callback(result.abilityResult); - }); - } else { - callback(result.abilityResult); - } - }, - - batchInsertMmsPart(param, callback) { - let actionData: LooseObject = {}; - actionData.featureAbility = param.featureAbility; - let batchMmsParts: Array = []; - for (let mms of param.mmsSource) { - let stringValue = { - "msg_id": param.msgId, - "group_id": param.groupId, - "type": mms.msgType, - "location_path": mms.msgUriPath, - "content": mms.content, - "recording_time": mms.time, - "part_size": (mms.fileSize + ''), - "state": param.messageType - }; - batchMmsParts.push(stringValue); - } - actionData.batchMmsParts = batchMmsParts; - globalThis.DataWorker.sendRequest("batchInsertMmsPart", { - actionData: actionData, - context: globalThis.mmsContext - }, result => { - callback(result); - }); - }, - - updateSessionAndDetail(actionData) { - let sendResults = actionData.sendResults; - if (sendResults.length == 0) { - return; - } - let param = this.dealSendResults(sendResults); - // Update the status of the session list. - let threadIds = [actionData.threadId]; - let valueBucket = { - "sending_status": param.sendStatus, - "content": param.content - } - conversationListService.updateById(threadIds, valueBucket); - // Update the status of the information list. - for (let sendResult of sendResults) { - actionData.sendStatus = sendResult.sendStatus; - if (sendResult.sendStatus == common.int.SEND_MESSAGE_FAILED) { - actionData.sendStatus = 2; - } else if (sendResult.sendStatus == common.int.SEND_MESSAGE_SUCCESS) { - actionData.sendStatus = 0; - } else { - actionData.sendStatus = 1; - } - actionData.msgId = sendResult.id; - this.updateById(actionData, result => { - }); - } - }, - - /** - * Deletes list data in batches based on session ids. - * - * @param actionData session ids - */ - deleteMessageBySessionIds(actionData) { - globalThis.DataWorker.sendRequest("queryGroupIdBySessionId", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - if (res.code == common.int.SUCCESS) { - globalThis.DataWorker.sendRequest("deleteMessageBySessionIds", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - // do nothing - }); - let groupIds = res.abilityResult; - actionData.groupIds = groupIds; - globalThis.DataWorker.sendRequest("deleteMmsPartByGroupIds", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - // do nothing - }); - } - }); - }, - - /** - * Deletes list data in batches based on ids. - * - * @param actionData primary key id session ids - */ - deleteMessageByIds(actionData) { - mConversationModel.deleteMessageByIds(actionData); - }, - - deleteMessageBySessionIdsAndLock(actionData) { - globalThis.DataWorker.sendRequest("deleteMessageBySessionIdsAndLock", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - // do nothing - }); - }, - - /** - * Deletes list data in batches based on the group id. - * - * @param actionData session ids - */ - deleteMessageByGroupIds(actionData) { - globalThis.DataWorker.sendRequest("deleteMessageByGroupIds", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - // do nothing - }); - // Deleting mms data - globalThis.DataWorker.sendRequest("deleteMmsPartByGroupIds", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - // do nothing - }); - }, - - /** - * Based on batch marking - * - * @param actionData - * @callback callback - */ - markAllAsRead(actionData, callback?) { - globalThis.DataWorker.sendRequest("markAllAsRead", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - if (callback) { - callback(res); - } - }); - }, - - /** - * Based on batch marking - * - * @param actionData - * @callback callback - */ - markAllToRead(actionData, callback?) { - globalThis.DataWorker.sendRequest("markAllToRead", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - if (callback) { - callback(res); - } - }); - }, - - /** - * Update based on a single id. - * - * @param actionData - * @callback callback - */ - updateById(actionData, callback) { - globalThis.DataWorker.sendRequest("updateById", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - callback(res); - }); - }, - - /** - * Query the maximum group id. - * - * @param actionData - * @callBack callBack - */ - queryMaxGroupId(actionData, callBack) { - globalThis.DataWorker.sendRequest("queryMaxGroupId", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - let result: LooseObject = {}; - result.code = res.code; - if (res.code == common.int.SUCCESS) { - result.response = res.abilityResult; - } else { - HiLog.w(TAG, "queryMaxGroupId, failed"); - } - callBack(result); - }); - }, - - /** - * Save picture - * - * @param params threadId, pduId - * @callback callback - */ - saveImage(params, callback) { - mConversationModel.saveImage(params, function (result) { - let message = ''; - if (result.code == common.int.SUCCESS) { - HiLog.i(TAG, "saveImage, success"); - message = this.$t("strings.attachment_saved_to") + result.abilityResult.filePath - + this.$t("strings.please_keep_it_secure"); - } else { - HiLog.w(TAG, "saveImage, error"); - message = this.$t("string.save_img_failed"); - } - callback(message); - }); - }, - - /** - * Go to share - * - * @param actionData - * @callback callback - */ - gotoShare(actionData, callback) { - let result: LooseObject = {}; - mConversationModel.gotoShare(actionData, res => { - result.code = res.code; + }); + } else { + this.conversationModel.updateSmsMmsInfoByCondition(actionData, valueBucket, callback, mmsContext); + } + } + + public querySmsMmsInfoByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.querySmsMmsInfoByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationModel.querySmsMmsInfoByCondition(actionData, callback, mmsContext); + } + } + + public querySmsMmsInfoSizeByCondition(actionData, callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.querySmsMmsInfoSizeByCondition, { + actionData: actionData, + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationModel.querySmsMmsInfoSizeByCondition(actionData, callback, mmsContext); + } + } + + public statisticalData(callback, context) { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.statisticalData, { + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationModel.statisticalData(callback, mmsContext); + } + } + + public queryMaxGroupId(callback, context): void { + let mmsContext = context ? context : globalThis.mmsContext; + if (globalThis.DataWorker != null) { + globalThis.DataWorker.sendRequest(common.RUN_IN_WORKER_METHOD.queryMaxGroupId, { + context: mmsContext + }, res => { + callback(res); + }); + } else { + this.conversationModel.queryMaxGroupId(callback, mmsContext); + } + } + + public queryMessageDetail(actionData, callback, context): void { + this.querySmsMmsInfoByCondition(actionData, res => { + let result: LooseObject = {}; + result.code = res.code; + if (res.code == common.int.SUCCESS) { + this.groupDetailMessage(res.abilityResult, actionData, resultList => { + result.response = resultList; + callback(result); }); + } else { + HiLog.w(TAG, "queryMessageDetail, failed"); callback(result); - }, + } + }, context); + } - /** - * Update the lock tag - * - * @param actionData - * @callback callback - */ - updateLock(actionData, callback) { - let result: LooseObject = {}; - mConversationModel.updateLock(actionData, res => { - result.code = res.code; - callback(result); - }); - }, + public convertConversationList(mmsList): Array { + let resultList: Array = []; + for (let item of mmsList) { + let result: LooseObject = {}; + result.id = item.msgId; + result.content = item.msgContent; + result.isLock = item.isLock == 0 ? false : true; + result.isStared = item.isCollect == 0 ? false : true; + // Fields related to MMS messages + result.msgType = 0; + result.isFullScreenImg = true; + result.read = item.isRead == 0 ? "0" : "1"; + if (item.msgState == 0) { + result.sendStatus = common.int.SEND_MESSAGE_SUCCESS; + } else if (item.msgState == 2) { + result.sendStatus = common.int.SEND_MESSAGE_FAILED; + } else if (item.msgState == 1) { + result.sendStatus = common.int.SEND_MESSAGE_SENDING; + } else { + result.sendStatus = common.int.SEND_DRAFT; + } + result.subId = item.slotId; + result.timeMillisecond = item.startTime; + result.isMsm = item.msgType == 0 ? false : true; + result.isCbChecked = false; + result.isDraft = false; + // Fields related to group-sending + result.groupId = item.groupId; + // Determine whether it is the receiver or sender. + result.isReceive = item.isSender == 0 ? false : true; + result.date = common.string.EMPTY_STR; + result.time = common.string.EMPTY_STR; + result.completeNumber = 0; + result.failuresNumber = 0; + result.hasReport = item.isSendReport == 0 ? false : true; + if (!result.isMsm) { + result.msgShowType = common.MESSAGE_SHOW_TYPE.NORMAL; + } + resultList.push(result); + } + return resultList; + } - /** - * Update favorites - * - * @param actionData - * @callback callback - */ - updateCollect(actionData, callback) { - let result: LooseObject = {}; - mConversationModel.updateCollect(actionData, res => { - result.code = res.code; - callback(result); - }); - }, - - /** - * Fuzzy search, by content - * - * @param actionData - * @callback callback - */ - searchMessageByContent(actionData, callback) { - let smsPromise = new Promise((resolve, reject) => { - this.searchSmsMessageByContent(actionData, res => { - if (res.code === common.int.SUCCESS) { - resolve(res.response); - } else { - reject(res.code); - } - }); - }); - // Information List Search Data - let mmsPartPromise = new Promise((resolve, reject) => { - this.searchMmsPartByContent(actionData, res => { - if (res.code === common.int.SUCCESS) { - resolve(res.response); - } else { - reject(res.code); - } - }); - }); - let result: LooseObject = {}; - Promise.all([smsPromise, mmsPartPromise]).then((res) => { - result.code = common.int.SUCCESS; - let resultList = []; - resultList = resultList.concat(res[0]); - resultList = resultList.concat(res[1]); - result.response = this.dealMessageSort(resultList); - callback(result); - }).catch((err) => { - HiLog.e(TAG, "searchMessageByContent, error: " + JSON.stringify(err.message)); - result.code = common.int.FAILURE; - callback(result); - }); - }, - - dealMessageSort(resultList) { - let favoriteList = []; - let messageList = []; - for (let item of resultList) { - if (item.isFavorite) { - favoriteList.push(item); - } else { - messageList.push(item); - } + public groupDetailMessage(mmsList, actionData, callback): void { + let details: Array = this.convertConversationList(mmsList); + if (actionData.contactsNum == 1) { + callback(details); + return; + } + let resultList: Array = []; + // Group by groupId. + let detailMap = this.convertConversationMap(details); + // By group + let groupIds = detailMap.keys(); + for (let groupId of groupIds) { + let groups = detailMap.get(groupId); + let result: LooseObject = groups[0]; + let failuresNumber = 0; + let completeNumber = 0; + for (let item of groups) { + if (item.sendStatus == common.int.SEND_MESSAGE_FAILED) { + failuresNumber++; } - let response = []; - // Favorites list in reverse order - if (favoriteList.length > 0) { - // inverted - favoriteList.sort((a, b) => { - return b.timeMillisecond - a.timeMillisecond - }); - response = response.concat(favoriteList); + if (item.sendStatus == common.int.SEND_MESSAGE_FAILED || item.sendStatus == common.int.SEND_MESSAGE_SUCCESS) { + completeNumber++; } - // List of common SMs in reverse order - if (messageList.length > 0) { - // inverted - messageList.sort((a, b) => { - return b.timeMillisecond - a.timeMillisecond - }) - response = response.concat(messageList); + } + result.completeNumber = completeNumber; + result.failuresNumber = failuresNumber; + resultList.push(result); + } + callback(resultList); + } + + public convertConversationMap(details) { + let conversationMap = new Map(); + // grouping + for (let element of details) { + if (conversationMap.has(element.groupId)) { + let groups = conversationMap.get(element.groupId); + groups.push(element); + } else { + let groups = []; + groups.push(element); + conversationMap.set(element.groupId, groups); + } + } + return conversationMap; + } + + public insertSessionAndDetail(actionData, callback, context): void { + let sendResults: Array = actionData.sendResults; + let isReceive: boolean = actionData.isReceive; + if (sendResults.length == 0) { + HiLog.w(TAG, "insertSessionAndDetail, sendResults.length == 0"); + return; + } + let param: LooseObject = this.dealSendResults(sendResults); + // Check whether a session list has been created. + ConversationListService.getInstance().querySessionByTelephone(param.telephone, res => { + let response: LooseObject = res.response; + if (res.code == common.int.SUCCESS && response.id <= 0) { + this.dealNoExistSession(isReceive, param, actionData, callback, context); + } else { + this.dealExistSession(response, param, actionData, callback, context); + } + }, context); + } + + public dealNoExistSession(isReceive, param, actionData, callback, context): void { + let unreadCount: number = 0; + if (isReceive) { + unreadCount = 1; + } + let valueBucket: LooseObject = { + "telephone": param.telephone, + "content": param.content, + "contacts_num": param.contactsNum, + "sms_type": param.smsType, + "unread_count": unreadCount, + "sending_status": param.sendStatus, + "has_draft": common.has_draft.NO, + "time": param.timestamp, + "message_count": 1, + "has_mms": actionData.isMms ? common.has_mms.HAVE : common.has_mms.NO, + "has_attachment": actionData.hasAttachment ? common.has_attachment.HAVE : common.has_attachment.NO + } + ConversationListService.getInstance().insertSession(valueBucket, sessionResult => { + HiLog.i(TAG, "dealNoExistSession, insertSession callback"); + if (sessionResult.code == common.int.FAILURE) { + HiLog.e(TAG, "dealNoExistSession, insertSession fail!"); + callback(sessionResult); + return; + } + // Invoke the SMS database to insert SMS messages. + this.dealInsertMessageDetail(param, actionData, sessionResult.abilityResult, res => { + let result: LooseObject = { + "rowId": sessionResult.abilityResult, + "initDatas": res.initDatas, + "groupId": res.groupId } - return response; - }, - - /** - * Fuzzy search, by content - * - * @param actionData - * @callback callback - */ - searchSmsMessageByContent(actionData, callback) { - let searchText = actionData.inputValue; - actionData.content = searchText; - let result: LooseObject = {}; - // The query details need to be disabled. - mConversationModel.searchSmsMessageByContent(actionData, res => { - result.code = res.code; - if (res.code == common.int.SUCCESS) { - let telephones = []; - let resultList = this.convertLikeConversation(res.abilityResult, searchText, telephones, new Map()); - this.dealContactsName(telephones, actionData, resultList, sessionList => { - result.response = sessionList; - callback(result); - }); - } else { - callback(result); - } - }); - }, - - convertLikeConversation(mmsList, searchText, telephones, mmsPartMap) { - let resultList = []; - for (let item of mmsList) { - let map: LooseObject = {}; - map.content = item.msgContent; - if (mmsPartMap.has(item.msgId)) { - map.content = mmsPartMap.get(item.msgId).content; - } - map.name = common.string.EMPTY_STR; - map.telephone = item.receiverNumber; - map.telephoneFormat = item.receiverNumber; - if (item.isSender == 1) { - map.telephone = item.senderNumber; - map.telephoneFormat = item.senderNumber; - } - telephones.push(map.telephone); - map.nameFormatter = map.name + "<" + map.telephoneFormat + ">"; - map.date = common.string.EMPTY_STR; - map.time = common.string.EMPTY_STR; - map.timeMillisecond = item.startTime; - map.isFavorite = item.isCollect == 0 ? false : true; - map.threadId = item.sessionId; - if (item.smsType == 0) { - map.icon = "icon/user_avatar_full_fill.svg"; - } else { - map.icon = "icon/entrance_icon01.svg"; - } - map.groupId = item.groupId; - resultList.push(map); - } - return resultList; - }, - - dealContactsName(telephones, actionData, resultList, callback) { - actionData.telephones = telephones; - if (telephones.length == 0) { - callback(resultList); - } - contractService.queryContactDataByTelephone(actionData, contacts => { - let groupIdMap: LooseObject = {}; - if (contacts.length == 0) { - groupIdMap = this.convertingMessageByGroup(resultList); - } else { - // Convert the result to Map, key: mobile number, value: name - let telephoneMap = new Map(); - for (let item of contacts) { - if (item.displayName == common.string.EMPTY_STR) { - telephoneMap.set(item.detailInfo, item.detailInfo); - } else { - telephoneMap.set(item.detailInfo, item.displayName); - } - } - // Match the result based on the mobile number. - groupIdMap = this.getGroupIdMap(resultList, telephoneMap); - } - let lists = []; - let favoriteList = []; - for (let key of Object.keys(groupIdMap)) { - let value = groupIdMap[key]; - let contactsNums = value.telephone.split(common.string.COMMA); - value.contactsNum = contactsNums.length; - if (value.isFavorite) { - let temp = JSON.parse(JSON.stringify(value)); - temp.icon = "/common/icon/icon_favorite.svg"; - favoriteList.push(temp); - value.isFavorite = false; - } - lists.push(value); - } - // Add favorite data to the search list. - if (favoriteList.length > 0) { - lists = lists.concat(favoriteList); - } - callback(lists); - }); - }, - - getGroupIdMap(resultList, telephoneMap) { - let groupIdMap: LooseObject = {}; - for (let map of resultList) { - // Indicates the combination of multiple names. The names need to be displayed in combination. - if (telephoneMap.has(map.telephone)) { - map.name = telephoneMap.get(map.telephone); - map.nameFormatter = map.name + "<" + map.telephoneFormat + ">"; - } else { - map.nameFormatter = map.telephoneFormat; - } - if (Object.keys(groupIdMap).indexOf(map.groupId) > -1) { - let list = groupIdMap[map.groupId]; - list.name = list.name + common.string.COMMA + map.name; - list.nameFormatter = list.nameFormatter + common.string.COMMA + map.nameFormatter; - list.telephone = list.telephone + common.string.COMMA + map.telephone; - list.telephoneFormat = list.telephoneFormat + common.string.COMMA + map.telephoneFormat; - } else { - groupIdMap[map.groupId] = map; - } - } - return groupIdMap; - }, - - convertingMessageByGroup(resultList) { - let groupIdMap: LooseObject = {}; - for (let element of resultList) { - if (Object.keys(groupIdMap).indexOf(element.groupId) == -1) { - groupIdMap[element.groupId] = element; - } - } - return groupIdMap; - }, - - /** - * Fuzzy search for mms messages by content - * - * @param actionData - * @callback callback - */ - searchMmsPartByContent(actionData, callback) { - let searchText = actionData.inputValue; - actionData.content = searchText; - // The query details need to be disabled. - let result: LooseObject = {}; - mConversationModel.searchMmsPartByContent(actionData, res => { - result.code = res.code; - if (res.code == common.int.SUCCESS) { - let mmsPartMap = this.getMmsPartMap(res.abilityResult); - actionData.msgIds = this.getMsgIds(mmsPartMap); - if (actionData.msgIds.length == 0) { - result.response = []; - callback(result); - return; - } - this.buildMmsPartContacts(actionData, searchText, mmsPartMap, sessionList => { - result.response = sessionList; - callback(result); - }); - } else { - HiLog.w(TAG, "searchMmsPartByContent, failed"); - callback(result); - } - }); - }, - - buildMmsPartContacts(actionData, searchText, mmsPartMap, callback) { - mConversationModel.queryMessageDetail(actionData, messageDetails => { - let telephones = []; - let mmsParts = messageDetails.abilityResult; - let resultList = this.convertLikeConversation(mmsParts, searchText, telephones, mmsPartMap); - this.dealContactsName(telephones, actionData, resultList, sessionList => { - callback(sessionList); - }); - }); - }, - - getMmsPartMap(mmsParts) { - let mmsPartMap = new Map(); - // grouping - for (let element of mmsParts) { - if (!mmsPartMap.has(element.msgId)) { - mmsPartMap.set(element.msgId, element); - } - } - return mmsPartMap; - }, - - getMsgIds(mmsPartMap) { - let msgIds = []; - for (let msgId of mmsPartMap.keys()) { - msgIds.push(msgId); - } - return msgIds; - }, - - /** - * Get pictures and videos from gallery - * - * @param actionData - * @callback callback - */ - queryFromGallery(actionData, callback) { - let result: LooseObject = {}; - mConversationModel.queryFromGallery(actionData, res => { - result.code = res.code; - result.pictureListFromGallery = res.abilityResult; - }); callback(result); - }, + }, context); + }, context); + } - /** - * Querying sms messages in the last 30 days - * - * @param actionData - * @callback callback - */ - queryMessageThirty(actionData, callBack) { - let result: LooseObject = {}; - mConversationModel.queryMessageThirty(actionData, res => { - result.code = res.code; - if (res.code == common.int.SUCCESS) { - result.response = res.abilityResult; - } else { - HiLog.w(TAG, "queryMessageThirty, failed"); - } - callBack(result); - }); - }, - - /** - * Inserting data into the sim card - * - * @param actionData - * @callback callback - */ - insertManageSimData(actionData, callback) { - HiLog.i(TAG, "insertManageSimData") - let sendResults = actionData.sendResults; - let value = this.dealSendResults(sendResults); - // Check whether a session list has been created. - conversationListService.querySessionByTelephone(value.telephone, res => { - let response = res.response; - if (res.code == common.int.SUCCESS && response.id < 0) { - this.insertManageSimNoExiting(value, actionData, callback); - } else { - let sessionId = response.id; - this.dealInsertMessageDetail(value, actionData, sessionId, res => { - let result = { - rowId: sessionId, - initDatas: res.initDatas, - groupId: res.groupId - } - callback(result); - }); - } - }); - }, - - insertManageSimNoExiting(value, actionData, callback) { - let valueBucket = { - "telephone": value.telephone, - "content": value.content, - "contacts_num": value.contractsNum, - "sms_type": value.smsType, - "unread_count": 0, - "sending_status": value.sendStatus, - "has_draft": 0, - "time": value.timestamp, - "message_count": 1 + public dealExistSession(response, param, actionData, callback, context): void { + let unreadCount: number = 0; + if (actionData.isReceive) { + unreadCount = response.unreadCount + 1; + } + let hasDraft: number = response.hasDraft; + if (actionData.hasDraft && hasDraft == 1) { + hasDraft = 0; + } + let valueBucket: LooseObject = { + "content": param.content, + "unread_count": unreadCount, + "time": new Date().getTime(), + "sending_status": param.sendStatus, + "has_draft": hasDraft, + "message_count": (response.messageCount + 1), + "has_attachment": actionData.hasAttachment ? 1 : 0, + "has_mms": actionData.isMms ? 1 : 0, + } + let sessionId: number = response.id; + let condition: LooseObject = {}; + condition.threadId = sessionId; + ConversationListService.getInstance().updateSessionByCondition(condition, valueBucket, res => { + // Invoke the SMS database to insert SMS messages. + this.dealInsertMessageDetail(param, actionData, sessionId, res => { + let result: LooseObject = { + "rowId": sessionId, + "initDatas": res.initDatas, + "groupId": res.groupId } - conversationListService.insertSession(valueBucket, sessionResult => { - // Invoke the SMS database to insert SMS messages. - this.dealInsertMessageDetail(value, actionData, sessionResult.rowId, res => { - let result = { - rowId: sessionResult.rowId, - initDatas: res.initDatas, - groupId: res.groupId - } - callback(result); - }); - }); - }, + callback(result); + }, context); + }, context); + } - /** - * Counting the number of unread notifications - * - * @param actionData - * @callback callback - */ - statisticsUnreadNotify(actionData, callback) { - mConversationModel.statisticsUnreadNotify(actionData, res => { - if (res.code == common.int.SUCCESS) { - callback(res.abilityResult); - } else { - HiLog.w(TAG, "statisticsUnreadNotify, failed"); - callback(0); - } - }); - }, + public dealInsertMessageDetail(param, actionData, threadId, callback, context): void { + this.queryMaxGroupId(res => { + let maxGroupId: number = 0; + if (res.code == common.int.SUCCESS) { + maxGroupId = Number(res.abilityResult) + 1; + } else { + HiLog.w(TAG, "dealInsertMessageDetail, queryMaxGroupId failed"); + callback(res); + } + this.insertMessageDetailByMaxGroupId(param, actionData, threadId, maxGroupId, result => { + callback(result); + }, context); + }, context); + } - /** - * This interface is used to query MMS information based on groupId. - * - * @param actionData - * @callback callback - */ - queryMmsPartByIds(actionData, callback) { - globalThis.DataWorker.sendRequest("queryMmsPart", { - actionData: actionData, - context: globalThis.mmsContext - }, res => { - let result: LooseObject = {}; - result.code = res.code; - if (res.code == common.int.SUCCESS) { - result.response = res.abilityResult; - } else { - HiLog.w(TAG, "queryMmsPartByIds, failed"); - } - callback(result); - }); - }, + private insertMessageDetailByMaxGroupId(param, actionData, threadId, maxGroupId, callback, context): void { + let count: number = 0; + let initDatas: Array = []; + let result: LooseObject = {}; + result.groupId = maxGroupId; + let sendResults = actionData.sendResults; + sendResults.forEach(sendResult => { + let valueBucket: LooseObject = this.buildInsertSmsMmsRow(param, actionData, sendResult, threadId, maxGroupId); + this.insertSmsMmsInfo(valueBucket, res => { + count++; + let initData: LooseObject = { + "id": res.abilityResult, + "telephone": sendResult.telephone + }; + initDatas.push(initData); + if (count == actionData.sendResults.length) { + result.initDatas = initDatas; + callback(result); + } + }, context); + }); + } - /** - * Obtains the lock status based on sessionId. - * - * @param actionData - * @callback callback - */ - queryMessageLockBySessionId(actionData, callback) { - let result: LooseObject = {}; - HiLog.i(TAG, "queryMessageLockBySessionId"); - mConversationModel.queryMessageLockBySessionId(actionData, res => { - result.code = res.code; - if (res.code == common.int.SUCCESS) { - callback(res.abilityResult); - } else { - HiLog.w(TAG, "queryMessageLockBySessionId, failed"); - callback(result); - } - }); - }, + private buildInsertSmsMmsRow(param, actionData, sendResult, threadId, maxGroupId): LooseObject { + let valueBucket: LooseObject = { + "slot_id": common.int.SIM_ONE, + "receiver_number": common.string.EMPTY_STR, + "sender_number": common.string.EMPTY_STR, + "start_time": common.string.EMPTY_STR, + "end_time": common.string.EMPTY_STR, + "msg_type": common.MESSAGE_TYPE.NORMAL, + "sms_type": common.sms_type.COMMON, + "msg_title": common.string.EMPTY_STR, + "msg_content": common.string.EMPTY_STR, + "msg_state": common.int.SEND_MESSAGE_SENDING, + "operator_service_number": common.string.EMPTY_STR, + "msg_code": common.string.EMPTY_STR, + "session_id": threadId, + "is_lock": common.is_lock.NO, + "is_read": common.is_read.UN_READ, + "is_collect": common.is_collect.NOT_FAVORITE, + "session_type": common.session_type.COMMON, + "is_sender": common.is_sender.NO, + "group_id": maxGroupId, + "is_send_report": common.is_send_report.NO + }; + if (sendResult.slotId != null) { + valueBucket.slot_id = sendResult.slotId; + } + if (actionData.isReceive) { + valueBucket.receiver_number = actionData.ownNumber ? actionData.ownNumber : common.string.EMPTY_STR; + valueBucket.sender_number = sendResult.telephone ? sendResult.telephone : common.string.EMPTY_STR; + valueBucket.is_read = common.is_read.UN_READ; + } else { + valueBucket.receiver_number = sendResult.telephone ? sendResult.telephone : common.string.EMPTY_STR; + valueBucket.sender_number = actionData.ownNumber ? actionData.ownNumber : common.string.EMPTY_STR; + valueBucket.is_read = common.is_read.READ; + } + let time: string = sendResult.time; + if (time == null) { + time = new Date().getTime() + common.string.EMPTY_STR; + } + valueBucket.start_time = time; + valueBucket.end_time = time; + if (param.isMms != null && param.isMms) { + valueBucket.msg_type = common.MESSAGE_TYPE.THEME; + } + if (param.smsType != null) { + valueBucket.sms_type = param.smsType; + } + if (param.content != null) { + valueBucket.msg_title = param.content; + valueBucket.msg_content = param.content; + } + if (sendResult.sendStatus != null) { + valueBucket.msg_state = sendResult.sendStatus; + } + if (actionData.isSender != null) { + valueBucket.is_sender = actionData.isSender; + } + if (actionData.hasReport != null) { + valueBucket.is_send_report = actionData.hasReport; + } + return valueBucket; + } + + public dealSendResults(sendResults: Array): LooseObject { + let contactsNum: number = sendResults.length; + let telephone: string = common.string.EMPTY_STR; + let content: string = common.string.EMPTY_STR; + let sendStatus: number = common.int.SEND_MESSAGE_SUCCESS; + let failSum: number = 0; + let time: string = common.string.EMPTY_STR; + for (let sendResult of sendResults) { + telephone = telephone + sendResult.telephone + common.string.COMMA; + content = sendResult.content; + sendStatus = sendResult.sendStatus; + if (sendResult.sendStatus == common.int.SEND_MESSAGE_FAILED) { + failSum++; + } + if (sendResult.time != null) { + time = sendResult.time; + } + if (sendResult.isMessageSim != null && sendResult.isMessageSim) { + telephone = sendResult.telephone; + contactsNum = 1; + } + } + // If it fails, then the session list turns out to be a failure. + if (failSum > 0) { + sendStatus = common.int.SEND_MESSAGE_FAILED; + } + telephone = telephone.substring(0, telephone.length - 1); + let smsType: number = common.sms_type.COMMON; + if (contactsNum == 1 && telephoneUtils.judgeIsInfoMsg(telephone)) { + smsType = common.sms_type.NOTICE; + } + let result: LooseObject = {}; + let timestamp: number = new Date().getTime(); + result.contactsNum = contactsNum; + result.content = content; + result.telephone = telephoneUtils.dealTelephoneSort(telephone); + result.sendStatus = sendStatus; + result.timestamp = time != common.string.EMPTY_STR ? time : timestamp; + result.smsType = smsType; + return result; + } + + public updateSessionAndDetail(actionData): void { + let sendResults: Array = actionData.sendResults; + if (sendResults.length == 0) { + return; + } + let param: LooseObject = this.dealSendResults(sendResults); + // Update the status of the session list. + let valueBucket: LooseObject = { + "sending_status": param.sendStatus, + "content": param.content + } + ConversationListService.getInstance().updateSessionByCondition(actionData, valueBucket, null, null); + // Update the status of the information list. + for (let sendResult of sendResults) { + actionData.sendStatus = sendResult.sendStatus; + if (sendResult.sendStatus == common.int.SEND_MESSAGE_FAILED) { + actionData.sendStatus = common.int.SEND_MESSAGE_FAILED; + } else if (sendResult.sendStatus == common.int.SEND_MESSAGE_SUCCESS) { + actionData.sendStatus = common.int.SEND_MESSAGE_SUCCESS; + } else { + actionData.sendStatus = common.int.SEND_MESSAGE_SENDING; + } + actionData.msgId = sendResult.id; + let valueBucket: LooseObject = { + "msg_state": actionData.sendStatus, + }; + this.updateSmsMmsInfoByCondition(actionData, valueBucket, null, null); + } + } + + public saveImage(actionData, callback, context): void { + callback("saveImage function to be developed!"); + } + + public gotoShare(actionData, callback, context): void { + callback("gotoShare function to be developed!"); + } + + public dealContactsName(telephones, actionData, resultList, callback, context): void { + actionData.telephones = telephones; + actionData.hasDelete = "0"; + if (telephones.length == 0) { + callback(resultList); + } + ContactsService.getInstance().queryContactDataByCondition(actionData, res => { + let groupIdMap: LooseObject = {}; + if (res.code == common.int.FAILURE || res.abilityResult.length == 0) { + groupIdMap = this.convertingMessageByGroup(resultList); + } else { + // Convert the result to Map, key: mobile number, value: name + let telephoneMap = new Map(); + let contacts: Array = res.abilityResult; + for (let item of contacts) { + if (item.displayName == common.string.EMPTY_STR) { + telephoneMap.set(item.detailInfo, item.detailInfo); + } else { + telephoneMap.set(item.detailInfo, item.displayName); + } + } + // Match the result based on the mobile number. + groupIdMap = this.getGroupIdMap(resultList, telephoneMap); + } + let lists = []; + let favoriteList = []; + for (let key of Object.keys(groupIdMap)) { + let value = groupIdMap[key]; + let contactsNums = value.telephone.split(common.string.COMMA); + value.contactsNum = contactsNums.length; + if (value.isFavorite) { + let temp = JSON.parse(JSON.stringify(value)); + temp.icon = "/common/icon/icon_favorite.svg"; + favoriteList.push(temp); + value.isFavorite = false; + } + lists.push(value); + } + // Add favorite data to the search list. + if (favoriteList.length > 0) { + lists = lists.concat(favoriteList); + } + callback(lists); + }, context); + } + + public getGroupIdMap(resultList, telephoneMap): LooseObject { + let groupIdMap: LooseObject = {}; + for (let map of resultList) { + // Indicates the combination of multiple names. The names need to be displayed in combination. + if (telephoneMap.has(map.telephone)) { + map.name = telephoneMap.get(map.telephone); + map.nameFormatter = map.name + "<" + map.telephoneFormat + ">"; + } else { + map.nameFormatter = map.telephoneFormat; + } + if (Object.keys(groupIdMap).indexOf(map.groupId) > -1) { + let list = groupIdMap[map.groupId]; + list.name = list.name + common.string.COMMA + map.name; + list.nameFormatter = list.nameFormatter + common.string.COMMA + map.nameFormatter; + list.telephone = list.telephone + common.string.COMMA + map.telephone; + list.telephoneFormat = list.telephoneFormat + common.string.COMMA + map.telephoneFormat; + } else { + groupIdMap[map.groupId] = map; + } + } + return groupIdMap; + } + + public convertingMessageByGroup(resultList): LooseObject { + let groupIdMap: LooseObject = {}; + for (let element of resultList) { + if (Object.keys(groupIdMap).indexOf(element.groupId) == -1) { + groupIdMap[element.groupId] = element; + } + } + return groupIdMap; + } + + public statisticsUnreadNotify(callback, context): void { + let actionData: LooseObject = {}; + actionData.hasRead = common.is_read.UN_READ; + actionData.smsType = common.sms_type.NOTICE; + this.querySmsMmsInfoSizeByCondition(actionData, res => { + if (res.code == common.int.SUCCESS) { + callback(res.abilityResult); + } else { + HiLog.w(TAG, "statisticsUnreadNotify fail!"); + callback(0); + } + }, context); + } } \ No newline at end of file diff --git a/entry/src/main/ets/service/NotificationService.ets b/entry/src/main/ets/service/NotificationService.ets index 4a7df72..a825e0d 100644 --- a/entry/src/main/ets/service/NotificationService.ets +++ b/entry/src/main/ets/service/NotificationService.ets @@ -14,15 +14,15 @@ */ import WantAgent from "@ohos.app.ability.wantAgent"; import Notification from "@ohos.notificationManager"; + import common from "../data/commonData"; import HiLog from "../utils/HiLog"; -import conversationService from "./ConversationService"; -import LooseObject from "../data/LooseObject"; -import messageService from "../service/ConversationListService"; +import ConversationService from "./ConversationService"; +import ConversationListService from "../service/ConversationListService"; var notificationManager = globalThis.requireNapi("notificationManager"); const label = "notification_"; -const TAG = "NotificationService"; +const TAG: string = "NotificationService"; export default class NotificationService { private static sInstance: NotificationService; @@ -52,10 +52,6 @@ export default class NotificationService { notificationRequest.wantAgent = data; notificationRequest.id = actionData.msgId; notificationRequest.label = label + actionData.msgId; - if(Number(actionData.unreadTotal) >= 0){ - HiLog.i(TAG, `unreadTotal is: ${Number(actionData.unreadTotal)}`) - notificationManager.setBadgeNumber(Number(actionData.unreadTotal)); - } Notification.publish(notificationRequest); HiLog.i(TAG, "sendNotify finished"); }); @@ -126,21 +122,23 @@ export default class NotificationService { return notificationRequest; } - cancelMessageNotify(actionData, callback) { - conversationService.queryMessageDetail(actionData, res => { + cancelMessageNotify(actionData, callback?) { + ConversationService.getInstance().queryMessageDetail(actionData, res => { if (res.code == common.int.FAILURE || res.response.length == 0) { - callback(common.int.FAILURE); + if (callback != null) { + callback(common.int.FAILURE); + } } let count = 0; for (let item of res.response) { - this.cancelNotify(parseInt(item.id), result => { + this.cancelNotify(Number(item.id), result => { count++; - if (count == res.response.length) { + if (count == res.response.length && callback != null) { callback(common.int.SUCCESS); } }); } - }); + }, null); } cancelNotify(msgId, callback) { @@ -151,13 +149,6 @@ export default class NotificationService { } callback(common.int.SUCCESS); }); - let params: LooseObject = {}; - messageService.statisticalData(params, function (res) { - if (res.code == common.int.SUCCESS) { - notificationManager.setBadgeNumber(Number(res.response.totalListCount)); - HiLog.i(TAG, "sendNotification, callback actionData"); - } - }); } cancelAllNotify() { @@ -167,4 +158,16 @@ export default class NotificationService { HiLog.e(TAG, "cancelAllNotify, error: " + JSON.stringify(err.message)); }); } + + public setBadgeNumber(unreadTotal: number): void { + notificationManager.setBadgeNumber(unreadTotal); + } + + public updateBadgeNumber(context?): void { + ConversationListService.getInstance().statisticalData(res => { + if (res.code == common.int.SUCCESS) { + this.setBadgeNumber(Number(res.response.totalListCount)); + } + }, context); + } }; \ No newline at end of file diff --git a/entry/src/main/ets/service/SendMsgService.ets b/entry/src/main/ets/service/SendMsgService.ets index 2197e38..58b0229 100644 --- a/entry/src/main/ets/service/SendMsgService.ets +++ b/entry/src/main/ets/service/SendMsgService.ets @@ -29,28 +29,33 @@ export default { * @callback callback Return the message sending status. */ sendMessage(params, callback) { - sms.sendMessage({ - slotId: params.slotId, - destinationHost: params.destinationHost, - content: params.content, - sendCallback: (err, value) => { - let sendStatus; - if (err) { - HiLog.w(TAG, "sendMessage, sendCallback failed err: " + JSON.stringify(err.message)); - sendStatus = common.int.SEND_MESSAGE_FAILED; - } else { - sendStatus = this.dealSendResult(value); - HiLog.i(TAG, `sendMessage, sendCallback success result=${value.result}, sendStatus=${sendStatus}`); + try { + sms.sendMessage({ + slotId: Number(params.slotId), + destinationHost: params.destinationHost, + content: params.content, + sendCallback: (err, value) => { + let sendStatus: number = common.int.SEND_MESSAGE_FAILED; + if (err) { + HiLog.w(TAG, "sendMessage, sendCallback failed err: " + JSON.stringify(err.message)); + sendStatus = common.int.SEND_MESSAGE_FAILED; + } else { + sendStatus = this.dealSendResult(value); + HiLog.i(TAG, `sendMessage, sendCallback success result=${value.result}, sendStatus=${sendStatus}`); + } + callback(sendStatus); + }, + deliveryCallback: (err, value) => { + if (err) { + HiLog.w(TAG, "sendMessage, deliveryCallback failed err: " + JSON.stringify(err.message)); + return; + } } - callback(sendStatus); - }, - deliveryCallback: (err, value) => { - if (err) { - HiLog.w(TAG, "sendMessage, deliveryCallback failed err: " + JSON.stringify(err.message)); - return; - } - } - }); + }); + } catch (error) { + HiLog.e(TAG, "sendMessage, sendMessage failed error: " + JSON.stringify(error)); + callback(common.int.SEND_MESSAGE_FAILED); + } }, dealSendResult(value) { diff --git a/entry/src/main/ets/service/SettingService.ets b/entry/src/main/ets/service/SettingService.ets index 6d06ec2..207d878 100644 --- a/entry/src/main/ets/service/SettingService.ets +++ b/entry/src/main/ets/service/SettingService.ets @@ -32,9 +32,9 @@ export default { */ setOnSettingValueListener(callback) { let result: LooseObject = { - integrationSwitch: false, - maliciousWebSwitch: false, - showContactSwitch: false, + "integrationSwitch": false, + "maliciousWebSwitch": false, + "showContactSwitch": false, }; mSettingModel.setOnSettingValueListener(settingValue => { if (settingValue.integrationSwitch === common.bool.TRUE || settingValue.integrationSwitch === '') { @@ -154,9 +154,9 @@ export default { */ getSettingFlagForConvListPage() { let result: LooseObject = { - isShowContactHeadIcon: false, - hasAggregate: false, - recallMessagesFlag: false, + "isShowContactHeadIcon": false, + "hasAggregate": false, + "recallMessagesFlag": false, }; mSettingModel.getSettingValue(settingValue => { if (settingValue.code === common.int.SUCCESS) { diff --git a/entry/src/main/ets/utils/StringUtil.ets b/entry/src/main/ets/utils/StringUtil.ets new file mode 100644 index 0000000..1e91b78 --- /dev/null +++ b/entry/src/main/ets/utils/StringUtil.ets @@ -0,0 +1,46 @@ +import HiLog from "../utils/HiLog"; + +const TAG: string = "StringUtil"; +const NON_ALPHABET_REG: RegExp = /[^\x00-\x80]/g; + +class StringUtil { + public countNonAlphabet(str: string): number { + let match: RegExpMatchArray | null = str.match(NON_ALPHABET_REG); + return (!match ? 0 : match.length); + } + + public getOffsetForSession(page: number): number { + let offset: number = 0; + if (page < 3) { + offset = (page - 1) * 50; + } else { + offset = (page - 2) * 100 + 50; + } + return offset; + } + + public getLimitForSession(page: number): number { + let limit: number = 0; + if (page == 1) { + limit = 50; + } else { + limit = 100; + } + return limit; + } + + public getGroupIdsFromResultList(resultList): Array { + let groupIds: Array = []; + if (resultList != null) { + for (let item of resultList) { + if (item.groupId != null) { + groupIds.push(item.groupId); + } + } + } + return groupIds; + } +} + +// Singleton +export default new StringUtil(); \ No newline at end of file diff --git a/entry/src/main/ets/utils/TelephoneUtil.ets b/entry/src/main/ets/utils/TelephoneUtil.ets index 12c5608..e41ec42 100644 --- a/entry/src/main/ets/utils/TelephoneUtil.ets +++ b/entry/src/main/ets/utils/TelephoneUtil.ets @@ -35,14 +35,15 @@ export default { * @param telephone * @return Yes or no */ - judgeIsInfoMsg(telephone) { - let result = false; + judgeIsInfoMsg(telephone: string): boolean { + let result: boolean = false; if (telephone == null || telephone == common.string.EMPTY_STR) { return result; } for (let item of infoMegTelephone) { if (telephone.indexOf(item) == 0) { result = true; + break; } } return result; diff --git a/entry/src/main/ets/utils/WantUtil.ets b/entry/src/main/ets/utils/WantUtil.ets index 45610e0..672d954 100644 --- a/entry/src/main/ets/utils/WantUtil.ets +++ b/entry/src/main/ets/utils/WantUtil.ets @@ -13,13 +13,14 @@ * limitations under the License. */ -import contactService from "../service/ContractService"; -import conversationListService from "../service/ConversationListService"; -import common from "../data/commonData"; -import featureAbility from "@ohos.ability.featureAbility"; -import HiLog from "./HiLog"; import router from "@system.router"; +import ContactService from "../service/ContactsService"; +import ConversationListService from "../service/ConversationListService"; +import common from "../data/commonData"; +import HiLog from "./HiLog"; +import LooseObject from '../data/LooseObject'; + const TAG = "WantUtil"; export default { @@ -39,15 +40,15 @@ export default { pageFlag = parameters.pageFlag; HiLog.i(TAG, "pageFlag = " + pageFlag); } - let contractParams = {} + let contactParams = {} if (parameters.hasOwnProperty("contactObjects")) { - contractParams = contactService.dealContractParams(parameters.contactObjects); + contactParams = ContactService.getInstance().dealContactParams(parameters.contactObjects); } - this.jump(pageFlag, contractParams); + this.jump(pageFlag, contactParams); } }, - jump(pageFlag, contractParams) { + jump(pageFlag, contactParams) { let result = { uri: '', params: {} @@ -56,9 +57,9 @@ export default { switch (pageFlag) { case "conversation": result.uri = "pages/conversation/conversation"; - if (contractParams) { - result.params = contractParams; - this.jumpIsNewPage(result, contractParams); + if (contactParams) { + result.params = contactParams; + this.jumpIsNewPage(result, contactParams); } else { router.push(result); } @@ -68,12 +69,14 @@ export default { } }, - async jumpIsNewPage(result, contractParams) { + async jumpIsNewPage(result, contactParams) { // Check whether a session has been created for the current phone number in the SMS message. - conversationListService.querySessionByTelephone(contractParams.strContactsNumber, res => { + ConversationListService.getInstance().querySessionByTelephone(contactParams.strContactsNumber, res => { if (res.code == common.int.SUCCESS && res.response.id > 0) { result.params.threadId = res.response.id; - this.markAllAsRead(result.params.threadId); + let actionData: LooseObject = {}; + actionData.threadId = result.params.threadId; + ConversationListService.getInstance().markAllToRead(actionData); if (res.response.hasDraft && res.response.messageCount == 0) { result.params.isNewMsg = true; } else { @@ -83,17 +86,6 @@ export default { result.params.isNewMsg = true; } router.push(result); - }); + }, null); }, - - markAllAsRead(threadId) { - let actionData = { - threadIds: [threadId], - hasRead: 1, - valueBucket: { - "unread_count": 0 - } - }; - conversationListService.markAllAsRead(actionData); - } } \ No newline at end of file diff --git a/entry/src/main/ets/views/receive/receive.ets b/entry/src/main/ets/views/receive/receive.ets index 3c6ca51..f6bed4d 100644 --- a/entry/src/main/ets/views/receive/receive.ets +++ b/entry/src/main/ets/views/receive/receive.ets @@ -132,7 +132,7 @@ export struct Receive { .height(24) .onClick(() => { // The page for selecting a contact is displayed. - this.mReceiveController.clickToContracts((receiverData) => { + this.mReceiveController.clickToContacts(receiverData => { this.mConversationController.setReceiveContactValue(receiverData); }) }) diff --git a/entry/src/main/ets/views/receive/receiveController.ets b/entry/src/main/ets/views/receive/receiveController.ets index dd6537b..d342926 100644 --- a/entry/src/main/ets/views/receive/receiveController.ets +++ b/entry/src/main/ets/views/receive/receiveController.ets @@ -12,10 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import HiLog from "../../utils/HiLog"; import prompt from "@system.prompt"; + +import HiLog from "../../utils/HiLog"; import common from "../../data/commonData"; -import contractService from "../../service/ContractService"; +import ContactsService from "../../service/ContactsService"; import commonService from "../../service/CommonService" import commonCtrl from "../../pages/conversation/common" import LooseObject from "../../data/LooseObject" @@ -57,7 +58,7 @@ export default class ReceiveController { onInit(call) { HiLog.i(TAG, "onInit()") // this.$watch("paramContact", "onPropertyChange"); - this.selectContacts = this.commonCtrl.paramContact.transmitContracts; + this.selectContacts = this.commonCtrl.paramContact.transmitContacts; if (this.selectContacts.length > 0) { let that = this; setTimeout(function () { @@ -88,7 +89,7 @@ export default class ReceiveController { limit: this.limit }; // Querying Contacts - contractService.queryContact(actionData, contacts => { + ContactsService.getInstance().queryContact(actionData, contacts => { if (common.int.SUCCESS == contacts.code) { let response = this.contacts.concat(contacts.response); this.contacts = []; @@ -97,11 +98,13 @@ export default class ReceiveController { } else { HiLog.w(TAG, "queryContacts, fail"); } - }); + }, null); // Number of statistics - contractService.countContact(actionData, contacts => { - this.totalMessage = contacts.response; - }); + ContactsService.getInstance().queryContactSizeByCondition(actionData, res => { + if (res.code == common.int.SUCCESS) { + this.totalMessage = res.abilityResult; + } + }, null); } searchContacts(textValue, callback) { @@ -109,16 +112,14 @@ export default class ReceiveController { let actionData = { telephone: textValue, }; - contractService.searchContracts(actionData, res => { - let code = res.code; - if (common.int.SUCCESS == res.code) { - this.contacts = []; - this.contacts = res.response; + ContactsService.getInstance().queryContactViewByCondition(actionData, res => { + if (res.code == common.int.SUCCESS) { + this.contacts = res.abilityResult; } else { HiLog.w(TAG, "searchContacts fail"); } - callback(code); - }); + callback(res.code); + }, null); } // Filter search terms to match contacts @@ -167,12 +168,12 @@ export default class ReceiveController { let selectContact: LooseObject = {}; let hasSelect = false; for (let index in this.contacts) { - let contract = this.contacts[index]; - if (contract.telephone == that.myText) { + let contact = this.contacts[index]; + if (contact.telephone == that.myText) { selectContact.headImage = "icon/user_avatar_full_fill.svg"; - selectContact.contactName = contract.contactName; - selectContact.telephone = contract.telephone; - selectContact.telephoneFormat = contract.telephone; + selectContact.contactName = contact.contactName; + selectContact.telephone = contact.telephone; + selectContact.telephoneFormat = contact.telephone; selectContact.select = false; hasSelect = true; break; @@ -348,36 +349,36 @@ export default class ReceiveController { this.refresh = !this.refresh; } - clickToContracts(call) { + clickToContacts(call) { var actionData: LooseObject = {}; - actionData.pageFlag = common.contractPage.PAGE_FLAG_SINGLE_CHOOSE; - this.jumpToContractForResult(actionData, call); + actionData.pageFlag = common.contactPage.PAGE_FLAG_SINGLE_CHOOSE; + this.jumpToContactForResult(actionData, call); } // Tap a contact's avatar to go to the contact details page. titleBarAvatar(index) { var actionData: LooseObject = {}; actionData.phoneNumber = this.contacts[index]?.telephone; - actionData.pageFlag = common.contractPage.PAGE_FLAG_CONTACT_DETAILS; - this.jumpToContract(actionData); + actionData.pageFlag = common.contactPage.PAGE_FLAG_CONTACT_DETAILS; + this.jumpToContact(actionData); } // Switching to the Contacts app - jumpToContract(actionData) { - let str = commonService.commonContractParam(actionData); + jumpToContact(actionData) { + let str = commonService.commonContactParam(actionData); globalThis.mmsContext.startAbility(str).then((data) => { }).catch((error) => { - HiLog.i(TAG, "jumpToContract failed"); + HiLog.i(TAG, "jumpToContact failed"); }); } // Switching to the Contacts app - async jumpToContractForResult(actionData, call) { - let str = commonService.commonContractParam(actionData); + async jumpToContactForResult(actionData, call) { + let str = commonService.commonContactParam(actionData); var data = await globalThis.mmsContext.startAbilityForResult(str); if (data.resultCode == 0) { - this.dealContractParams(data.want.parameters.contactObjects, call); + this.dealContactParams(data.want.parameters.contactObjects, call); } } - dealContractParams(contactObjects, call) { + dealContactParams(contactObjects, call) { this.selectContacts = []; let params = JSON.parse(contactObjects); if (this.checkSingle()) { @@ -397,7 +398,7 @@ export default class ReceiveController { return; } if (this.selectContacts.length > 0) { - this.deleteRepetitionContracts(this.contacts, this.selectContacts); + this.deleteRepetitionContacts(this.contacts, this.selectContacts); this.setInputStatus(false); this.isShowSearch = false; this.setContactValue(call); @@ -406,7 +407,7 @@ export default class ReceiveController { this.commonCtrl.paramContact.isNewRecallMessagesFlag = false; } - deleteRepetitionContracts(contacts, selectContacts) { + deleteRepetitionContacts(contacts, selectContacts) { let indexs = []; let count = 0; for (let item of contacts) { diff --git a/entry/src/main/ets/workers/DataWorkerWrapper.ets b/entry/src/main/ets/workers/DataWorkerWrapper.ets index 04ad236..8c50d21 100644 --- a/entry/src/main/ets/workers/DataWorkerWrapper.ets +++ b/entry/src/main/ets/workers/DataWorkerWrapper.ets @@ -13,18 +13,21 @@ * limitations under the License. */ -import { WorkerType } from "./WorkFactory" -import WorkerWrapper from "./base/WorkerWrapper" -import WorkerTask from "./base/WorkerTask" import { ThreadWorkerGlobalScope } from '@ohos.worker'; + +import { WorkerType } from './WorkFactory'; +import WorkerWrapper from './base/WorkerWrapper'; +import WorkerTask from './base/WorkerTask'; +import common from '../data/commonData'; import ContactsModel from '../model/ContactsModel'; import ConversationModel from '../model/ConversationModel'; +import ConversationListModel from '../model/ConversationListModel'; import HiLog from '../utils/HiLog'; const TAG = "DataWorkerWrapper" export default class DataWorkerWrapper extends WorkerWrapper { - private static sInstance: DataWorkerWrapper = undefined; + private static sInstance: DataWorkerWrapper = null; private constructor() { super() @@ -32,7 +35,7 @@ export default class DataWorkerWrapper extends WorkerWrapper { static getInstance() { HiLog.i(TAG, "getInstance in."); - if (DataWorkerWrapper.sInstance == undefined || DataWorkerWrapper.sInstance.mWorker == undefined) { + if (DataWorkerWrapper.sInstance == null || DataWorkerWrapper.sInstance.mWorker == null) { HiLog.i(TAG, "make DataWorkerWrapper."); DataWorkerWrapper.sInstance = new DataWorkerWrapper(); } @@ -44,180 +47,194 @@ export default class DataWorkerWrapper extends WorkerWrapper { } } -export enum DataWorkerConstant { - "searchContracts", - "queryContact", - "queryContactDataByIds", - "countContact", - "queryContactDataByTelephone", - "queryProfile", - "queryMessageDetail", - "queryMmsPart", - "queryMaxGroupId", - "insertMessageDetail", - "batchInsertMmsPart", - "queryGroupIdBySessionId", - "deleteMessageBySessionIds", - "deleteMmsPartByGroupIds", - "deleteMessageByGroupIds", - "deleteMessageBySessionIdsAndLock", - "markAllAsRead", - "markAllToRead", - "updateById", - "updateLock", - "updateCollect" -} - export class DataWorkerTask extends WorkerTask { - private static sInstance: DataWorkerTask = undefined; + private static sInstance: DataWorkerTask = null; private mContactsModel: ContactsModel = new ContactsModel(); private mConversationModel: ConversationModel = new ConversationModel(); + private mConversationListModel: ConversationListModel = new ConversationListModel(); + private constructor(workerPort: ThreadWorkerGlobalScope) { super(workerPort); } static getInstance(workerPort: ThreadWorkerGlobalScope) { HiLog.i(TAG, "getInstance in."); - if (DataWorkerTask.sInstance == undefined || DataWorkerTask.sInstance.workerPort == undefined) { + if (DataWorkerTask.sInstance == null || DataWorkerTask.sInstance.workerPort == null) { DataWorkerTask.sInstance = new DataWorkerTask(workerPort); } return DataWorkerTask.sInstance; } - runInWorker(request: string, callBack: (v?: any) => void, param?: any) { + public runInWorker(request: string, callBack: (v?: any) => void, param?: any) { HiLog.i(TAG, `runInWorker ${request}`); switch (request) { - case DataWorkerConstant[DataWorkerConstant.searchContracts]: - this.mContactsModel.searchContracts(param.actionData, (data) => { - HiLog.i(TAG, `searchContracts result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryContactDataByCondition: + this.mContactsModel.queryContactDataByCondition(param.actionData, res => { + HiLog.i(TAG, `queryContactDataByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; - case DataWorkerConstant[DataWorkerConstant.queryContact]: - this.mContactsModel.queryContact(param.actionData, (data) => { - HiLog.i(TAG, `queryContact result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryContactDataSizeByCondition: + this.mContactsModel.queryContactDataSizeByCondition(param.actionData, res => { + HiLog.i(TAG, `queryContactDataSizeByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; - case DataWorkerConstant[DataWorkerConstant.queryContactDataByIds]: - this.mContactsModel.queryContactDataByIds(param.actionData, (data) => { - HiLog.i(TAG, `queryContactDataByIds result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryContactByCondition: + this.mContactsModel.queryContactByCondition(param.actionData, res => { + HiLog.i(TAG, `queryContactByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; - case DataWorkerConstant[DataWorkerConstant.countContact]: - this.mContactsModel.countContact(param.actionData, (data) => { - HiLog.i(TAG, `countContact result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryContactSizeByCondition: + this.mContactsModel.queryContactSizeByCondition(param.actionData, res => { + HiLog.i(TAG, `queryContactSizeByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; - case DataWorkerConstant[DataWorkerConstant.queryContactDataByTelephone]: - this.mContactsModel.queryContactDataByTelephone(param.actionData, (data) => { - HiLog.i(TAG, `queryContactDataByTelephone result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryRawContactSizeByCondition: + this.mContactsModel.queryRawContactSizeByCondition(param.actionData, res => { + HiLog.i(TAG, `queryRawContactSizeByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; - case DataWorkerConstant[DataWorkerConstant.queryProfile]: - this.mContactsModel.queryProfile(param.actionData, (data) => { - HiLog.i(TAG, `queryProfile result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.queryMessageDetail]: - this.mConversationModel.queryMessageDetail(param.actionData, (data) => { - HiLog.i(TAG, `queryMessageDetail result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.queryMmsPart]: - this.mConversationModel.queryMmsPart(param.actionData, (data) => { - HiLog.i(TAG, `queryMmsPart result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.queryMaxGroupId]: - this.mConversationModel.queryMaxGroupId(param.actionData, (data) => { - HiLog.i(TAG, `queryMaxGroupId result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.insertMessageDetail]: - this.mConversationModel.insertMessageDetail(param.actionData, (data) => { - HiLog.i(TAG, `insertMessageDetail result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.batchInsertMmsPart]: - this.mConversationModel.batchInsertMmsPart(param.actionData, (data) => { - HiLog.i(TAG, `batchInsertMmsPart result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.queryGroupIdBySessionId]: - this.mConversationModel.queryGroupIdBySessionId(param.actionData, (data) => { - HiLog.i(TAG, `queryGroupIdBySessionId result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.deleteMessageBySessionIds]: - this.mConversationModel.deleteMessageBySessionIds(param.actionData, (data) => { - HiLog.i(TAG, `deleteMessageBySessionIds result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.deleteMmsPartByGroupIds]: - this.mConversationModel.deleteMmsPartByGroupIds(param.actionData, (data) => { - HiLog.i(TAG, `deleteMmsPartByGroupIds result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.deleteMessageByGroupIds]: - this.mConversationModel.deleteMessageByGroupIds(param.actionData, (data) => { - HiLog.i(TAG, `deleteMessageByGroupIds result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.deleteMessageBySessionIdsAndLock]: - this.mConversationModel.deleteMessageBySessionIdsAndLock(param.actionData, (data) => { - HiLog.i(TAG, `deleteMessageBySessionIdsAndLock result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.markAllAsRead]: - this.mConversationModel.markAllAsRead(param.actionData, (data) => { - HiLog.i(TAG, `markAllAsRead result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.markAllToRead]: - this.mConversationModel.markAllToRead(param.actionData, (data) => { - HiLog.i(TAG, `markAllToRead result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.updateById]: - this.mConversationModel.updateById(param.actionData, (data) => { - HiLog.i(TAG, `updateById result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.updateLock]: - this.mConversationModel.updateLock(param.actionData, (data) => { - HiLog.i(TAG, `updateLock result: ${JSON.stringify(data).length}`); - callBack(data); - }, param.context); - break; - case DataWorkerConstant[DataWorkerConstant.updateCollect]: - this.mConversationModel.updateCollect(param.actionData, (data) => { - HiLog.i(TAG, `updateCollect result: ${JSON.stringify(data).length}`); - callBack(data); + case common.RUN_IN_WORKER_METHOD.queryContactViewByCondition: + this.mContactsModel.queryContactViewByCondition(param.actionData, res => { + HiLog.i(TAG, `queryContactViewByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } }, param.context); break; default: - HiLog.w(TAG, `${request} not allow!!!`) + this.runInWorkerMore(request, callBack, param); + break; + } + } + + public runInWorkerMore(request: string, callBack: (v?: any) => void, param?: any) { + HiLog.i(TAG, `runInWorkerMore ${request}`); + switch (request) { + case common.RUN_IN_WORKER_METHOD.insertSmsMmsInfo: + this.mConversationModel.insertSmsMmsInfo(param.valueBucket, res => { + HiLog.i(TAG, `insertSmsMmsInfo result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.deleteSmsMmsInfoByCondition: + this.mConversationModel.deleteSmsMmsInfoByCondition(param.actionData, res => { + HiLog.i(TAG, `deleteSmsMmsInfoByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.updateSmsMmsInfoByCondition: + this.mConversationModel.updateSmsMmsInfoByCondition(param.actionData, param.valueBucket, res => { + HiLog.i(TAG, `updateSmsMmsInfoByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.querySmsMmsInfoByCondition: + this.mConversationModel.querySmsMmsInfoByCondition(param.actionData, res => { + HiLog.i(TAG, `querySmsMmsInfoByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.querySmsMmsInfoSizeByCondition: + this.mConversationModel.querySmsMmsInfoSizeByCondition(param.actionData, res => { + HiLog.i(TAG, `querySmsMmsInfoSizeByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.queryMaxGroupId: + this.mConversationModel.queryMaxGroupId(res => { + HiLog.i(TAG, `queryMaxGroupId result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.statisticalData: + this.mConversationModel.statisticalData(res => { + HiLog.i(TAG, `statisticalData result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + default: + this.runInWorkerMoreMore(request, callBack, param); + break; + } + } + + public runInWorkerMoreMore(request: string, callBack: (v?: any) => void, param?: any) { + HiLog.i(TAG, `runInWorkerMoreMore ${request}`); + switch (request) { + case common.RUN_IN_WORKER_METHOD.insertSession: + this.mConversationListModel.insertSession(param.valueBucket, res => { + HiLog.i(TAG, `insertSession result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.deleteSessionByCondition: + this.mConversationListModel.deleteSessionByCondition(param.actionData, res => { + HiLog.i(TAG, `deleteSessionByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.updateSessionByCondition: + this.mConversationListModel.updateSessionByCondition(param.actionData, param.valueBucket, res => { + HiLog.i(TAG, `updateSessionByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.querySessionByCondition: + this.mConversationListModel.querySessionByCondition(param.actionData, res => { + HiLog.i(TAG, `querySessionByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + case common.RUN_IN_WORKER_METHOD.querySessionSizeByCondition: + this.mConversationListModel.querySessionSizeByCondition(param.actionData, res => { + HiLog.i(TAG, `querySessionSizeByCondition result: ${JSON.stringify(res).length}`); + if (callBack) { + callBack(res); + } + }, param.context); + break; + default: + HiLog.w(TAG, `${request} not allow!!!`); break; } } diff --git a/entry/src/main/ets/workers/WorkFactory.ets b/entry/src/main/ets/workers/WorkFactory.ets index 723d1f7..7f02274 100644 --- a/entry/src/main/ets/workers/WorkFactory.ets +++ b/entry/src/main/ets/workers/WorkFactory.ets @@ -37,7 +37,7 @@ export default class WorkFactory { let data = message.data; let type = data.type; HiLog.i(TAG, `getTask in ${WorkerType[type]}.`) - let task: WorkerTask = undefined; + let task: WorkerTask = null; if (type == WorkerType.DataWorker) { HiLog.w(TAG, "getTask " + type); task = DataWorkerTask.getInstance(workerPort); @@ -54,7 +54,7 @@ export default class WorkFactory { */ static getWorker(type: WorkerType): WorkerWrapper { HiLog.i(TAG, `getWorker in ${WorkerType[type]}.`) - let worker: WorkerWrapper = undefined + let worker: WorkerWrapper = null; if (type == WorkerType.DataWorker) { HiLog.w(TAG, "getWorker " + type) worker = DataWorkerWrapper.getInstance(); diff --git a/entry/src/main/ets/workers/base/WorkerWrapper.ts b/entry/src/main/ets/workers/base/WorkerWrapper.ts index 6888b9b..3f7ed8c 100644 --- a/entry/src/main/ets/workers/base/WorkerWrapper.ts +++ b/entry/src/main/ets/workers/base/WorkerWrapper.ts @@ -33,7 +33,7 @@ export class WorkerMessage { * Processes sending tasks to workers and receiving work processing results. */ export abstract class WorkerWrapper { - protected mWorker: worker.ThreadWorker = undefined; + protected mWorker: worker.ThreadWorker = null; private callBacks: Map void> = new Map(); private requestIndex: number = 0; @@ -49,7 +49,7 @@ export abstract class WorkerWrapper { let that = this; initWorker.onexit = function (message) { HiLog.w(TAG, "onexit") - that.mWorker = undefined; + that.mWorker = null; } initWorker.onerror = function (e) { HiLog.w(TAG, "onerror:" + JSON.stringify(e)) @@ -111,7 +111,7 @@ export abstract class WorkerWrapper { public close() { HiLog.i(TAG, `${this.getWorkerType()} worker close!`); this.mWorker.terminate(); - this.mWorker = undefined; + this.mWorker = null; this.callBacks.clear(); } diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json index 35f326b..f3c8082 100644 --- a/entry/src/main/resources/base/element/string.json +++ b/entry/src/main/resources/base/element/string.json @@ -105,9 +105,12 @@ {"name": "lock", "value": "锁定"}, {"name": "unlock", "value": "解锁"}, {"name": "query_details", "value": "查看详情"}, - {"name": "msg_delete_dialog_tip1", "value": "是否删除此信息?"}, - {"name": "msg_delete_dialog_tip2", "value": "是否删除%d条信息?"}, + {"name": "msg_delete_dialog_tip1", "value": "是否删除此会话?"}, + {"name": "msg_delete_dialog_con_tip1", "value": "是否删除此信息?"}, + {"name": "msg_delete_dialog_tip2", "value": "是否删除%d条会话?"}, + {"name": "msg_delete_dialog_con_tip2", "value": "是否删除%d条信息?"}, {"name": "msg_delete_dialog_tip3", "value": "是否删除全部会话?"}, + {"name": "msg_delete_dialog_con_tip3", "value": "是否删除全部信息?"}, {"name": "msg_delete_dialog_cb_tip", "value": "同时删除锁定信息"}, {"name": "msg_delete_dialog_lock", "value": "是否删除此锁定的信息?"}, {"name": "msg_selected_tip", "value": "已选择 %d 项"}, @@ -147,7 +150,7 @@ {"name": "transmitHeadText", "value": "选择会话"}, {"name": "recently", "value": "最近"}, {"name": "searchHit", "value": "输入号码或搜索"}, - {"name": "selectContracts", "value": "选择联系人"}, + {"name": "selectContacts", "value": "选择联系人"}, {"name": "me", "value": "我"}, {"name": "transmitContentMe", "value": "我:"}, {"name": "transmitContent", "value": "转自 我:"}, diff --git a/entry/src/main/resources/en_US/element/string.json b/entry/src/main/resources/en_US/element/string.json index d162a96..fd70f29 100644 --- a/entry/src/main/resources/en_US/element/string.json +++ b/entry/src/main/resources/en_US/element/string.json @@ -105,9 +105,12 @@ {"name": "lock", "value": "Lock"}, {"name": "unlock", "value": "Unlock"}, {"name": "query_details", "value": "Display details"}, - {"name": "msg_delete_dialog_tip1", "value": "Delete this message?"}, - {"name": "msg_delete_dialog_tip2", "value": "Delete %d messages or not?"}, - {"name": "msg_delete_dialog_tip3", "value": "Delete all message?"}, + {"name": "msg_delete_dialog_tip1", "value": "Delete this session?"}, + {"name": "msg_delete_dialog_con_tip1", "value": "Delete this message?"}, + {"name": "msg_delete_dialog_tip2", "value": "Delete %d session or not?"}, + {"name": "msg_delete_dialog_con_tip2", "value": "Delete %d messages or not?"}, + {"name": "msg_delete_dialog_tip3", "value": "Delete all session?"}, + {"name": "msg_delete_dialog_con_tip3", "value": "Delete all message?"}, {"name": "msg_delete_dialog_cb_tip", "value": "Also delete locked messages"}, {"name": "msg_delete_dialog_lock", "value": "Delete this locked message?"}, {"name": "msg_selected_tip", "value": "%d item selected"}, @@ -147,7 +150,7 @@ {"name": "transmitHeadText", "value": "Select conversation"}, {"name": "recently", "value": "RECEBTS"}, {"name": "searchHit", "value": "Enter number or search"}, - {"name": "selectContracts", "value": "Select contact"}, + {"name": "selectContacts", "value": "Select contact"}, {"name": "me", "value": "Me"}, {"name": "transmitContentMe", "value": "Me:"}, {"name": "transmitContent", "value": "Forwarded from Me:"}, diff --git a/entry/src/main/resources/zh_CN/element/string.json b/entry/src/main/resources/zh_CN/element/string.json index 35f326b..f3c8082 100644 --- a/entry/src/main/resources/zh_CN/element/string.json +++ b/entry/src/main/resources/zh_CN/element/string.json @@ -105,9 +105,12 @@ {"name": "lock", "value": "锁定"}, {"name": "unlock", "value": "解锁"}, {"name": "query_details", "value": "查看详情"}, - {"name": "msg_delete_dialog_tip1", "value": "是否删除此信息?"}, - {"name": "msg_delete_dialog_tip2", "value": "是否删除%d条信息?"}, + {"name": "msg_delete_dialog_tip1", "value": "是否删除此会话?"}, + {"name": "msg_delete_dialog_con_tip1", "value": "是否删除此信息?"}, + {"name": "msg_delete_dialog_tip2", "value": "是否删除%d条会话?"}, + {"name": "msg_delete_dialog_con_tip2", "value": "是否删除%d条信息?"}, {"name": "msg_delete_dialog_tip3", "value": "是否删除全部会话?"}, + {"name": "msg_delete_dialog_con_tip3", "value": "是否删除全部信息?"}, {"name": "msg_delete_dialog_cb_tip", "value": "同时删除锁定信息"}, {"name": "msg_delete_dialog_lock", "value": "是否删除此锁定的信息?"}, {"name": "msg_selected_tip", "value": "已选择 %d 项"}, @@ -147,7 +150,7 @@ {"name": "transmitHeadText", "value": "选择会话"}, {"name": "recently", "value": "最近"}, {"name": "searchHit", "value": "输入号码或搜索"}, - {"name": "selectContracts", "value": "选择联系人"}, + {"name": "selectContacts", "value": "选择联系人"}, {"name": "me", "value": "我"}, {"name": "transmitContentMe", "value": "我:"}, {"name": "transmitContent", "value": "转自 我:"}, diff --git a/rejectAndSendMessage/sms_mms_data.h b/rejectAndSendMessage/sms_mms_data.h new file mode 100644 index 0000000..30a34a3 --- /dev/null +++ b/rejectAndSendMessage/sms_mms_data.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SMS_MMS_DATA_H +#define SMS_MMS_DATA_H + +namespace OHOS { +namespace Telephony { +class SmsMmsData { +public: + static constexpr const char *ID = "id"; + static constexpr const char *SLOT_ID = "slot_id"; + static constexpr const char *SMS_SUBSECTION_ID = "sms_subsection_id"; + static constexpr const char *RECEIVER_NUMBER = "receiver_number"; + static constexpr const char *SENDER_NUMBER = "sender_number"; + static constexpr const char *IS_SENDER = "is_sender"; + static constexpr const char *START_TIME = "start_time"; + static constexpr const char *END_TIME = "end_time"; + static constexpr const char *RAW_PUD = "raw_pdu"; + static constexpr const char *FORMAT = "format"; + static constexpr const char *DEST_PORT = "dest_port"; + static constexpr const char *SUBSECTION_INDEX = "subsection_index"; + static constexpr const char *SIZE = "size"; +}; + +class SmsMmsInfo { +public: + static constexpr const char *MSG_ID = "msg_id"; + static constexpr const char *SLOT_ID = "slot_id"; + static constexpr const char *RECEIVER_NUMBER = "receiver_number"; + static constexpr const char *SENDER_NUMBER = "sender_number"; + static constexpr const char *IS_SENDER = "is_sender"; + static constexpr const char *START_TIME = "start_time"; + static constexpr const char *END_TIME = "end_time"; + static constexpr const char *MSG_TYPE = "msg_type"; + static constexpr const char *SMS_TYPE = "sms_type"; + static constexpr const char *MSG_TITLE = "msg_title"; + static constexpr const char *MSG_CONTENT = "msg_content"; + static constexpr const char *MSG_STATE = "msg_state"; + static constexpr const char *MSG_CODE = "msg_code"; + static constexpr const char *IS_LOCK = "is_lock"; + static constexpr const char *IS_READ = "is_read"; + static constexpr const char *IS_COLLECT = "is_collect"; + static constexpr const char *SESSION_TYPE = "session_type"; + static constexpr const char *RETRY_NUMBER = "retry_number"; + static constexpr const char *OPERATOR_SERVICE_NUMBER = "operator_service_number"; + static constexpr const char *SESSION_ID = "session_id"; + static constexpr const char *GROUP_ID = "group_id"; + static constexpr const char *DEVICE_ID = "device_id"; + static constexpr const char *IS_SUBSECTION = "is_subsection"; + static constexpr const char *IS_SEND_REPORT = "is_send_report"; +}; + +class Session { +public: + static constexpr const char *ID = "id"; + static constexpr const char *TIME = "time"; + static constexpr const char *TELEPHONE = "telephone"; + static constexpr const char *CONTENT = "content"; + static constexpr const char *CONTACTS_NUM = "contacts_num"; + static constexpr const char *SMS_TYPE = "sms_type"; + static constexpr const char *UNREAD_COUNT = "unread_count"; + static constexpr const char *SENDING_STATUS = "sending_status"; + static constexpr const char *HAS_DRAFT = "has_draft"; + static constexpr const char *HAS_LOCK = "has_lock"; + static constexpr const char *MESSAGE_COUNT = "message_count"; + static constexpr const char *HAS_MMS = "has_mms"; + static constexpr const char *HAS_ATTACHMENT = "has_attachment"; +}; +} // namespace Telephony +} // namespace OHOS +#endif // SMS_MMS_DATA_H + diff --git a/rejectAndSendMessage/sms_persist_helper.cpp b/rejectAndSendMessage/sms_persist_helper.cpp new file mode 100644 index 0000000..48c2f39 --- /dev/null +++ b/rejectAndSendMessage/sms_persist_helper.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sms_persist_helper.h" + +#include "ability_manager_interface.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability.h" +#include "system_ability_definition.h" +#include "resource_manager.h" +#include "parameter.h" + +#include "telephony_log_wrapper.h" +#include "string_utils.h" + +namespace OHOS { +namespace Telephony { +class AbsSharedResultSet; +SmsPersistHelper::SmsPersistHelper() {} + +SmsPersistHelper::~SmsPersistHelper() {} + +std::shared_ptr SmsPersistHelper::CreateDataShareHelper(std::string uri) +{ + auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + TELEPHONY_LOGE(" Get system ability mgr failed."); + return nullptr; + } + auto remoteObj = saManager->GetSystemAbility(TELEPHONY_SMS_MMS_SYS_ABILITY_ID); + if (remoteObj == nullptr) { + TELEPHONY_LOGE("GetSystemAbility Service Failed."); + return nullptr; + } + return DataShare::DataShareHelper::Creator(remoteObj, uri); +} + +bool SmsPersistHelper::Insert(DataShare::DataShareValuesBucket &values) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SMS_SUBSECTION); + int ret = helper->Insert(uri, values); + helper->Release(); + return ret >= 0 ? true : false; +} + +bool SmsPersistHelper::Insert(std::string tableUri, DataShare::DataShareValuesBucket &values) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(tableUri); + int ret = helper->Insert(uri, values); + helper->Release(); + return ret >= 0 ? true : false; +} + +bool SmsPersistHelper::QuerySession(DataShare::DataSharePredicates &predicates, uint16_t §ionId, + uint16_t &messageCount) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SESSION); + std::vector columns; + auto resultSet = helper->Query(uri, predicates, columns); + if (resultSet == nullptr) { + TELEPHONY_LOGE("Query Result Set nullptr Failed."); + return false; + } + resultSet->GoToFirstRow(); + int32_t columnInt; + int columnIndex; + resultSet->GetColumnIndex("id", columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + sectionId = columnInt; + } + resultSet->GetColumnIndex("message_count", columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + messageCount = columnInt; + return true; + } + resultSet->Close(); + helper->Release(); + return false; +} + +bool SmsPersistHelper::Update(DataShare::DataSharePredicates &predicates, DataShare::DataShareValuesBucket &values) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SESSION); + int ret = helper->Update(uri, predicates, values); + helper->Release(); + return ret >= 0 ? true : false; +} + +bool SmsPersistHelper::Query(DataShare::DataSharePredicates &predicates, std::vector &indexers) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SMS_SUBSECTION); + std::vector columns; + auto resultSet = helper->Query(uri, predicates, columns); + helper->Release(); + if (resultSet == nullptr) { + TELEPHONY_LOGE("Query Result Set nullptr Failed."); + return false; + } + + int resultSetNum = resultSet->GoToFirstRow(); + while (resultSetNum == 0) { + SmsReceiveIndexer indexer; + ResultSetConvertToIndexer(indexer, resultSet); + indexers.push_back(indexer); + resultSetNum = resultSet->GoToNextRow(); + } + resultSet->Close(); + return true; +} + +bool SmsPersistHelper::QueryMaxGroupId(DataShare::DataSharePredicates &predicates, uint16_t &maxGroupId) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SMS_MMS_INFO); + std::vector columns; + auto resultSet = helper->Query(uri, predicates, columns); + if (resultSet == nullptr) { + TELEPHONY_LOGE("Query Result Set nullptr Failed."); + return false; + } + + int32_t columnInt; + int columnIndex; + resultSet->GoToLastRow(); + resultSet->GetColumnIndex(SmsMmsInfo::GROUP_ID, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + maxGroupId = columnInt; + } + resultSet->Close(); + helper->Release(); + return true; +} + +bool SmsPersistHelper::Delete(DataShare::DataSharePredicates &predicates) +{ + std::shared_ptr helper = CreateDataShareHelper(SMS_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(SMS_SUBSECTION); + int ret = helper->Delete(uri, predicates); + helper->Release(); + return ret >= 0 ? true : false; +} + +bool SmsPersistHelper::QueryBlockPhoneNumber(const std::string &phoneNum) +{ + bool result = false; + int count = 0; + const std::string phoneNumber = "phone_number"; + if (phoneNum.empty()) { + return result; + } + std::shared_ptr helper = CreateDataShareHelper(CONTACT_URI); + if (helper == nullptr) { + TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed."); + return false; + } + Uri uri(CONTACT_BLOCK); + std::vector columns; + DataShare::DataSharePredicates predicates; + predicates.EqualTo(phoneNumber, phoneNum); + auto resultSet = helper->Query(uri, predicates, columns); + helper->Release(); + if (resultSet == nullptr) { + TELEPHONY_LOGE("Query Result Set nullptr Failed."); + return result; + } + if (resultSet->GetRowCount(count) == 0 && count != 0) { + result = true; + } + resultSet->Close(); + return result; +} + +bool SmsPersistHelper::QueryParamBoolean(const std::string key, bool defValue) +{ + const int PARAM_SIZE = 64; + char paramOutBuff[PARAM_SIZE] = {0}; + std::string defStrValue = defValue ? "1" : "0"; + std::string paramValue(defStrValue); + + int retLen = GetParameter(key.c_str(), defStrValue.c_str(), paramOutBuff, PARAM_SIZE); + if (retLen > 0) { + paramOutBuff[retLen] = '\0'; + paramValue.assign(paramOutBuff, retLen); + } + + TELEPHONY_LOGI("QueryParamBoolean: %{public}zu : %{public}s", paramValue.size(), paramValue.c_str()); + if ((paramValue == std::string("1")) || (paramValue == std::string("y")) || (paramValue == std::string("yes")) || + (paramValue == std::string("on")) || (paramValue == std::string("true"))) { + return true; + } else if ((paramValue == std::string("0")) || (paramValue == std::string("n")) || + (paramValue == std::string("no")) || (paramValue == std::string("off")) || + (paramValue == std::string("false"))) { + return false; + } + return defValue; +} + +void SmsPersistHelper::ConvertIntToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet) +{ + int32_t columnInt; + int columnIndex; + resultSet->GetColumnIndex(SmsMmsData::FORMAT, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + info.SetIsCdma(columnInt != 0); + } + + resultSet->GetColumnIndex(SmsMmsData::SMS_SUBSECTION_ID, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + info.SetMsgRefId(columnInt); + } + + resultSet->GetColumnIndex(SmsMmsData::SIZE, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + info.SetMsgCount(columnInt); + } + + resultSet->GetColumnIndex(SmsMmsData::SUBSECTION_INDEX, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + info.SetMsgSeqId(columnInt); + } + + resultSet->GetColumnIndex(SmsMmsData::DEST_PORT, columnIndex); + if (resultSet->GetInt(columnIndex, columnInt) == 0) { + info.SetDestPort(columnInt); + } +} + +void SmsPersistHelper::ConvertStringToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet) +{ + int columnIndex; + std::string columnValue; + resultSet->GetColumnIndex(SmsMmsData::RECEIVER_NUMBER, columnIndex); + if (resultSet->GetString(columnIndex, columnValue) == 0) { + info.SetVisibleAddress(columnValue); + } + resultSet->GetColumnIndex(SmsMmsData::SENDER_NUMBER, columnIndex); + if (resultSet->GetString(columnIndex, columnValue) == 0) { + info.SetOriginatingAddress(columnValue); + } + + resultSet->GetColumnIndex(SmsMmsData::START_TIME, columnIndex); + if (resultSet->GetString(columnIndex, columnValue) == 0) { + info.SetTimestamp(std::stol(columnValue)); + } + resultSet->GetColumnIndex(SmsMmsData::END_TIME, columnIndex); + if (resultSet->GetString(columnIndex, columnValue) == 0) { + info.SetTimestamp(std::stol(columnValue)); + } + + resultSet->GetColumnIndex(SmsMmsData::RAW_PUD, columnIndex); + if (resultSet->GetString(columnIndex, columnValue) == 0) { + info.SetPdu(StringUtils::HexToByteVector(columnValue)); + } +} + +void SmsPersistHelper::ResultSetConvertToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet) +{ + ConvertIntToIndexer(info, resultSet); + ConvertStringToIndexer(info, resultSet); +} +} // namespace Telephony +} // namespace OHOS diff --git a/rejectAndSendMessage/sms_persist_helper.h b/rejectAndSendMessage/sms_persist_helper.h new file mode 100644 index 0000000..57fcd95 --- /dev/null +++ b/rejectAndSendMessage/sms_persist_helper.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SMS_PERSIST_HELPER_H +#define SMS_PERSIST_HELPER_H + +#include "singleton.h" + +#include "datashare_helper.h" +#include "datashare_predicates.h" + +#include "sms_receive_indexer.h" +#include "sms_mms_data.h" + +namespace OHOS { +namespace Telephony { +class SmsPersistHelper { + DECLARE_DELAYED_SINGLETON(SmsPersistHelper) +public: + bool Insert(DataShare::DataShareValuesBucket &values); + bool Insert(std::string tableUri, DataShare::DataShareValuesBucket &values); + bool Query(DataShare::DataSharePredicates &predicates, std::vector &indexers); + bool QueryMaxGroupId(DataShare::DataSharePredicates &predicates, uint16_t &maxGroupId); + bool QuerySession(DataShare::DataSharePredicates &predicates, uint16_t §ionId, uint16_t &messageCount); + bool Delete(DataShare::DataSharePredicates &predicates); + bool QueryBlockPhoneNumber(const std::string &phoneNum); + bool QueryParamBoolean(const std::string key, bool defValue); + bool Update(DataShare::DataSharePredicates &predicates, DataShare::DataShareValuesBucket &values); + + inline static const std::string SMS_CAPABLE_KEY = "sms_config_capable"; + inline static const std::string SMS_ENCODING_KEY = "sms_config_force_7bit_encoding"; + inline static const std::string SMS_CAPABLE_PARAM_KEY = "const.telephony.sms.capable"; + inline static const std::string SMS_ENCODING_PARAM_KEY = "persist.sys.sms.config.7bitforce"; + +private: + const std::string SMS_URI = "datashare:///com.ohos.smsmmsability"; + const std::string SMS_SUBSECTION = "datashare:///com.ohos.smsmmsability/sms_mms/sms_subsection"; + const std::string SMS_MMS_INFO = "datashare:///com.ohos.smsmmsability/sms_mms/sms_mms_info"; + const std::string SESSION = "datashare:///com.ohos.smsmmsability/sms_mms/session"; + const std::string CONTACT_URI = "datashare:///com.ohos.contactsdataability"; + const std::string CONTACT_BLOCK = + "datashare:///com.ohos.contactsdataability/contacts/contact_blocklist"; + + std::shared_ptr CreateDataShareHelper(std::string uri); + void ResultSetConvertToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet); + void ConvertIntToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet); + void ConvertStringToIndexer( + SmsReceiveIndexer &info, const std::shared_ptr &resultSet); +}; +} // namespace Telephony +} // namespace OHOS +#endif diff --git a/rejectAndSendMessage/sms_service.cpp b/rejectAndSendMessage/sms_service.cpp new file mode 100644 index 0000000..d31bfbd --- /dev/null +++ b/rejectAndSendMessage/sms_service.cpp @@ -0,0 +1,680 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sms_service.h" + +#include + +#include "cdma_sms_message.h" +#include "core_manager_inner.h" +#include "ims_sms_client.h" +#include "msg_text_convert.h" +#include "sms_dump_helper.h" +#include "sms_hisysevent.h" +#include "string_utils.h" +#include "telephony_log_wrapper.h" +#include "telephony_common_utils.h" +#include "telephony_permission.h" + +namespace OHOS { +namespace Telephony { +using namespace std; +using namespace AppExecFwk; +using namespace HiviewDFX; +constexpr static uint32_t CONNECT_SERVICE_WAIT_TIME = 2000; +constexpr static size_t MIN_LEN = 1; +bool g_registerResult = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +SmsService::SmsService() : SystemAbility(TELEPHONY_SMS_MMS_SYS_ABILITY_ID, true) {} + +SmsService::~SmsService() {} + +void SmsService::OnStart() +{ + TELEPHONY_LOGI("SmsService::OnStart start service Enter."); + bindTime_ = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + if (state_ == ServiceRunningState::STATE_RUNNING) { + TELEPHONY_LOGE("msService has already started."); + return; + } + if (!Init()) { + TELEPHONY_LOGE("failed to init SmsService"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; + endTime_ = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + TELEPHONY_LOGI("SmsService::OnStart start service Exit."); +} + +bool SmsService::Init() +{ + DelayedSingleton::GetInstance()->Init(); + if (!registerToService_) { + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + TELEPHONY_LOGE("SmsService::Init Publish failed!"); + return false; + } + registerToService_ = true; + WaitCoreServiceToInit(); + } + DelayedSingleton::GetInstance()->Init(); + return true; +} + +void SmsService::OnStop() +{ + state_ = ServiceRunningState::STATE_NOT_START; + registerToService_ = false; + DelayedSingleton::GetInstance()->UnInit(); + DelayedSingleton::GetInstance()->UnInit(); + TELEPHONY_LOGI("SmsService::OnStop stop service."); +} + +int32_t SmsService::Dump(std::int32_t fd, const std::vector &args) +{ + if (fd < 0) { + TELEPHONY_LOGE("dump fd invalid"); + return TELEPHONY_ERR_FAIL; + } + std::vector argsInStr; + for (const auto &arg : args) { + TELEPHONY_LOGI("Dump args: %{public}s", Str16ToStr8(arg).c_str()); + argsInStr.emplace_back(Str16ToStr8(arg)); + } + std::string result; + SmsDumpHelper dumpHelper; + if (dumpHelper.Dump(argsInStr, result)) { + TELEPHONY_LOGI("%{public}s", result.c_str()); + std::int32_t ret = dprintf(fd, "%s", result.c_str()); + if (ret < 0) { + TELEPHONY_LOGE("dprintf to dump fd failed"); + return TELEPHONY_ERR_FAIL; + } + return TELEPHONY_SUCCESS; + } + TELEPHONY_LOGW("dumpHelper failed"); + return TELEPHONY_ERR_FAIL; +} + +void SmsService::WaitCoreServiceToInit() +{ + std::thread connectTask([&]() { + while (true) { + if (CoreManagerInner::GetInstance().IsInitFinished()) { + InitModule(); + TELEPHONY_LOGI("SmsService Connection successful"); + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(CONNECT_SERVICE_WAIT_TIME)); + } + }); + connectTask.detach(); +} + +std::string SmsService::GetBindTime() +{ + return std::to_string(bindTime_); +} + +int32_t SmsService::SendMessage(int32_t slotId, const u16string desAddr, const u16string scAddr, const u16string text, + const sptr &sendCallback, const sptr &deliveryCallback) +{ + if (NoPermissionOrParametersCheckFail(slotId, desAddr, sendCallback)) { + SmsHiSysEvent::WriteSmsSendFaultEvent(slotId, SmsMmsMessageType::SMS_SHORT_MESSAGE, + SmsMmsErrorCode::SMS_ERROR_PERMISSION_ERROR, Permission::SEND_MESSAGES); + return TELEPHONY_ERR_PERMISSION_ERR; + } + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + SmsHiSysEvent::WriteSmsSendFaultEvent(slotId, SmsMmsMessageType::SMS_SHORT_MESSAGE, + SmsMmsErrorCode::SMS_ERROR_NULL_POINTER, "text sms interfaceManager is nullptr"); + TELEPHONY_LOGE("SmsService::SendMessage interfaceManager nullptr error."); + return TELEPHONY_ERR_LOCAL_PTR_NULL; + } + if (!ValidDestinationAddress(StringUtils::ToUtf8(desAddr))) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + TELEPHONY_LOGE("SmsService::SendMessage desAddr not conform to the regular specification"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + int32_t ret = interfaceManager->TextBasedSmsDelivery(StringUtils::ToUtf8(desAddr), StringUtils::ToUtf8(scAddr), + StringUtils::ToUtf8(text), sendCallback, deliveryCallback); + std::string bundleName = GetBundleName(); + if (bundleName != COM_OHOS_MMS) { + InsertSessionAndDetail(slotId, StringUtils::ToUtf8(desAddr), StringUtils::ToUtf8(text)); + } + return ret; +} + +void SmsService::InsertSessionAndDetail(int32_t slotId, const std::string &telephone, const std::string &text) +{ + uint16_t sectionId; + uint16_t messageCount; + bool ret = QuerySessionByTelephone(telephone, sectionId, messageCount); + if (ret) { + InsertSmsMmsInfo(slotId, sectionId, telephone, text); + messageCount++; + InsertSession(false, messageCount, telephone, text); + } else { + ret = InsertSession(true, 0, telephone, text); + if (ret) { + QuerySessionByTelephone(telephone, sectionId, messageCount); + InsertSmsMmsInfo(slotId, sectionId, telephone, text); + } + } +} + +bool SmsService::QuerySessionByTelephone(const std::string &telephone, uint16_t §ionId, uint16_t &messageCount) +{ + DataShare::DataSharePredicates predicates; + predicates.EqualTo(Session::TELEPHONE, telephone); + return DelayedSingleton::GetInstance()->QuerySession(predicates, sectionId, messageCount); +} + +void SmsService::InsertSmsMmsInfo(int32_t slotId, uint16_t sessionId, const std::string &number, const std::string &text) +{ + DataShare::DataSharePredicates predicates; + uint16_t maxGroupId = 0; + DelayedSingleton::GetInstance()->QueryMaxGroupId(predicates, maxGroupId); + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + DataShare::DataShareValuesBucket smsMmsInfoBucket; + smsMmsInfoBucket.Put(SmsMmsInfo::SLOT_ID, std::to_string(slotId)); + smsMmsInfoBucket.Put(SmsMmsInfo::RECEIVER_NUMBER, number); + smsMmsInfoBucket.Put(SmsMmsInfo::SENDER_NUMBER, ""); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_SENDER, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::START_TIME, std::to_string(duration.count())); + smsMmsInfoBucket.Put(SmsMmsInfo::END_TIME, std::to_string(duration.count())); + smsMmsInfoBucket.Put(SmsMmsInfo::MSG_TYPE, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::SMS_TYPE, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::MSG_TITLE, text); + smsMmsInfoBucket.Put(SmsMmsInfo::MSG_CONTENT, text); + smsMmsInfoBucket.Put(SmsMmsInfo::MSG_STATE, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::MSG_CODE, ""); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_LOCK, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_READ, "1"); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_COLLECT, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::SESSION_TYPE, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::SESSION_ID, std::to_string(sessionId)); + smsMmsInfoBucket.Put(SmsMmsInfo::GROUP_ID, std::to_string(maxGroupId + 1)); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_SUBSECTION, "0"); + smsMmsInfoBucket.Put(SmsMmsInfo::IS_SEND_REPORT, "0"); + DelayedSingleton::GetInstance()->Insert(SMS_MMS_INFO, smsMmsInfoBucket); +} + +bool SmsService::InsertSession(bool isNewSession, uint16_t messageCount, const std::string &number, + const std::string &text) +{ + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + DataShare::DataShareValuesBucket sessionBucket; + sessionBucket.Put(Session::TIME, std::to_string(duration.count())); + sessionBucket.Put(Session::TELEPHONE, number); + sessionBucket.Put(Session::CONTENT, text); + sessionBucket.Put(Session::CONTACTS_NUM, "1"); + sessionBucket.Put(Session::SMS_TYPE, "0"); + sessionBucket.Put(Session::UNREAD_COUNT, "0"); + sessionBucket.Put(Session::SENDING_STATUS, "0"); + sessionBucket.Put(Session::HAS_DRAFT, "0"); + sessionBucket.Put(Session::HAS_LOCK, "0"); + sessionBucket.Put(Session::HAS_MMS, "0"); + sessionBucket.Put(Session::HAS_ATTACHMENT, "0"); + if (!isNewSession) { + sessionBucket.Put(Session::MESSAGE_COUNT, std::to_string(messageCount)); + DataShare::DataSharePredicates predicates; + predicates.EqualTo(Session::TELEPHONE, number); + return DelayedSingleton::GetInstance()->Update(predicates, sessionBucket); + } + sessionBucket.Put(Session::MESSAGE_COUNT, "1"); + return DelayedSingleton::GetInstance()->Insert(SESSION, sessionBucket); +} + +int32_t SmsService::SendMessage(int32_t slotId, const u16string desAddr, const u16string scAddr, uint16_t port, + const uint8_t *data, uint16_t dataLen, const sptr &sendCallback, + const sptr &deliveryCallback) +{ + if (NoPermissionOrParametersCheckFail(slotId, desAddr, sendCallback)) { + SmsHiSysEvent::WriteSmsSendFaultEvent(slotId, SmsMmsMessageType::SMS_SHORT_MESSAGE, + SmsMmsErrorCode::SMS_ERROR_PERMISSION_ERROR, Permission::SEND_MESSAGES); + return TELEPHONY_ERR_PERMISSION_ERR; + } + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + TELEPHONY_LOGE("SmsService::SendMessage interfaceManager nullptr error."); + SmsHiSysEvent::WriteSmsSendFaultEvent(slotId, SmsMmsMessageType::SMS_SHORT_MESSAGE, + SmsMmsErrorCode::SMS_ERROR_NULL_POINTER, "data sms interfaceManager is nullptr"); + return TELEPHONY_ERR_LOCAL_PTR_NULL; + } + if (!ValidDestinationAddress(StringUtils::ToUtf8(desAddr))) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + TELEPHONY_LOGE("SmsService::SendMessage desAddr not conform to the regular specification"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + return interfaceManager->DataBasedSmsDelivery( + StringUtils::ToUtf8(desAddr), StringUtils::ToUtf8(scAddr), port, data, dataLen, sendCallback, deliveryCallback); +} + +bool SmsService::NoPermissionOrParametersCheckFail( + int32_t slotId, const u16string desAddr, const sptr &sendCallback) +{ + if (!TelephonyPermission::CheckPermission(Permission::SEND_MESSAGES)) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Send Messages Permisson."); + return true; + } + if (desAddr.empty()) { + SmsSender::SendResultCallBack(sendCallback, ISendShortMessageCallback::SEND_SMS_FAILURE_UNKNOWN); + TELEPHONY_LOGE("SmsService::SendMessage desAddr invalid."); + return true; + } + return false; +} + +int32_t SmsService::IsImsSmsSupported(int32_t slotId, bool &isSupported) +{ + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("interfaceManager is nullptr."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + return interfaceManager->IsImsSmsSupported(slotId, isSupported); +} + +int32_t SmsService::GetImsShortMessageFormat(std::u16string &format) +{ + int32_t slotId = GetDefaultSmsSlotId(); + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("interfaceManager is nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + return interfaceManager->GetImsShortMessageFormat(format); +} + +bool SmsService::HasSmsCapability() +{ + int32_t slotId = GetDefaultSmsSlotId(); + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("Get SmsInterfaceManager is nullptr error."); + return true; + } + return interfaceManager->HasSmsCapability(); +} + +int32_t SmsService::SetSmscAddr(int32_t slotId, const std::u16string &scAddr) +{ + if (!TelephonyPermission::CheckPermission(Permission::SET_TELEPHONY_STATE)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Set State Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("interfaceManager is nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + string sca = StringUtils::ToUtf8(scAddr); + TrimSmscAddr(sca); + if (sca.empty() || sca.length() == 0) { + TELEPHONY_LOGE("sca is empty"); + return TELEPHONY_ERR_ARGUMENT_NULL; + } + return interfaceManager->SetSmscAddr(sca); +} + +void SmsService::TrimSmscAddr(std::string &sca) +{ + if (sca.length() < MIN_LEN) { + return; + } + while (sca.length() >= MIN_LEN && sca[0] == ' ') { + sca.erase(0, 1); + } + while (sca.length() > MIN_LEN && sca[sca.length() - 1] == ' ') { + sca.erase(sca.length() - 1, 1); + } +} + +int32_t SmsService::GetSmscAddr(int32_t slotId, std::u16string &smscAddress) +{ + if (!TelephonyPermission::CheckPermission(Permission::GET_TELEPHONY_STATE)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Get State Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::GetSmscAddr interfaceManager nullptr error"); + return TELEPHONY_ERR_SLOTID_INVALID; + } + return interfaceManager->GetSmscAddr(smscAddress); +} + +int32_t SmsService::AddSimMessage( + int32_t slotId, const std::u16string &smsc, const std::u16string &pdu, SimMessageStatus status) +{ + if (!TelephonyPermission::CheckPermission(Permission::RECEIVE_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Receive Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + if (!TelephonyPermission::CheckPermission(Permission::SEND_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Send Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::AddSimMessage interfaceManager nullptr error"); + return TELEPHONY_ERR_SLOTID_INVALID; + } + std::string smscData = StringUtils::ToUtf8(smsc); + std::string pduData = StringUtils::ToUtf8(pdu); + if (pdu.empty() || pduData.empty()) { + TELEPHONY_LOGE("SmsService::AddSimMessage pdu empty error"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + return interfaceManager->AddSimMessage(smscData, pduData, status); +} + +int32_t SmsService::DelSimMessage(int32_t slotId, uint32_t msgIndex) +{ + if (!TelephonyPermission::CheckPermission(Permission::RECEIVE_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Receive Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + if (!TelephonyPermission::CheckPermission(Permission::SEND_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Send Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::DelSimMessage interfaceManager nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + if (!CheckSimMessageIndexValid(slotId, msgIndex)) { + TELEPHONY_LOGE("SmsService::DelSimMessage msgIndex inValid"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + + return interfaceManager->DelSimMessage(msgIndex); +} + +int32_t SmsService::UpdateSimMessage(int32_t slotId, uint32_t msgIndex, SimMessageStatus newStatus, + const std::u16string &pdu, const std::u16string &smsc) +{ + if (!TelephonyPermission::CheckPermission(Permission::RECEIVE_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Receive Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + if (!TelephonyPermission::CheckPermission(Permission::SEND_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Send Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::UpdateSimMessage interfaceManager nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + std::string pduData = StringUtils::ToUtf8(pdu); + std::string smscData = StringUtils::ToUtf8(smsc); + if (!CheckSimMessageIndexValid(slotId, msgIndex)) { + TELEPHONY_LOGE("SmsService::UpdateSimMessage msgIndex inValid"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + if (pdu.empty() || pduData.empty()) { + TELEPHONY_LOGE("SmsService::UpdateSimMessage pdu empty error"); + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + return interfaceManager->UpdateSimMessage(msgIndex, newStatus, pduData, smscData); +} + +int32_t SmsService::GetAllSimMessages(int32_t slotId, std::vector &message) +{ + if (!TelephonyPermission::CheckPermission(Permission::RECEIVE_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Receive Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::GetAllSimMessages interfaceManager nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + return interfaceManager->GetAllSimMessages(message); +} + +bool SmsService::CheckSimMessageIndexValid(int32_t slotId, uint32_t msgIndex) +{ + std::vector totalMessages; + int32_t result = GetAllSimMessages(slotId, totalMessages); + if (result != TELEPHONY_ERR_SUCCESS) { + TELEPHONY_LOGE("SmsService::CheckSimMessageIndexValid get result fail"); + return false; + } + + if (msgIndex < 0 || totalMessages.size() == 0) { + TELEPHONY_LOGE("SmsService::CheckSimMessageIndexValid msgIndex error"); + return false; + } + for (auto message : totalMessages) { + if (message.GetIndexOnSim() == static_cast(msgIndex)) { + return true; + } + } + TELEPHONY_LOGI("SmsService::CheckSimMessageIndexValid msgIndex not founded"); + return false; +} + +int32_t SmsService::SetCBConfig(int32_t slotId, bool enable, uint32_t fromMsgId, uint32_t toMsgId, uint8_t netType) +{ + if (!TelephonyPermission::CheckPermission(Permission::RECEIVE_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Receive Messages Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::SetCBConfig interfaceManager nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + return interfaceManager->SetCBConfig(enable, fromMsgId, toMsgId, netType); +} + +bool SmsService::SetImsSmsConfig(int32_t slotId, int32_t enable) +{ + if (!TelephonyPermission::CheckPermission(Permission::SET_TELEPHONY_STATE)) { + TELEPHONY_LOGE("Check permission failed."); + return false; + } + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::SetImsSmsConfig interfaceManager nullptr error."); + return false; + } + return interfaceManager->SetImsSmsConfig(slotId, enable); +} + +int32_t SmsService::SetDefaultSmsSlotId(int32_t slotId) +{ + if (!TelephonyPermission::CheckPermission(Permission::SET_TELEPHONY_STATE)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Set State Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + std::shared_ptr interfaceManager = GetSmsInterfaceManager(); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::SetDefaultSmsSlotId interfaceManager nullptr error."); + return TELEPHONY_ERR_LOCAL_PTR_NULL; + } + return interfaceManager->SetDefaultSmsSlotId(slotId); +} + +int32_t SmsService::GetDefaultSmsSlotId() +{ + std::shared_ptr interfaceManager = GetSmsInterfaceManager(); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::GetDefaultSmsSlotId interfaceManager nullptr error."); + return TELEPHONY_ERROR; + } + return interfaceManager->GetDefaultSmsSlotId(); +} + +int32_t SmsService::SplitMessage(const std::u16string &message, std::vector &splitMessage) +{ + if (!TelephonyPermission::CheckPermission(Permission::SEND_MESSAGES)) { + TELEPHONY_LOGE("Check Permission Failed, No Has Telephony Get State Permisson."); + return TELEPHONY_ERR_PERMISSION_ERR; + } + + if (message.empty()) { + return TELEPHONY_ERR_ARGUMENT_INVALID; + } + int32_t slotId = GetDefaultSmsSlotId(); + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("SmsService::SplitMessage interfaceManager nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + std::string messageData = StringUtils::ToUtf8(message); + return interfaceManager->SplitMessage(messageData, splitMessage); +} + +int32_t SmsService::GetSmsSegmentsInfo( + int32_t slotId, const std::u16string &message, bool force7BitCode, ISmsServiceInterface::SmsSegmentsInfo &info) +{ + if (message.empty()) { + return TELEPHONY_ERR_ARGUMENT_NULL; + } + std::shared_ptr interfaceManager = GetSmsInterfaceManager(slotId); + if (interfaceManager == nullptr) { + TELEPHONY_LOGE("GetSmsSegmentsInfo interfaceManager is nullptr error."); + return TELEPHONY_ERR_SLOTID_INVALID; + } + std::string messageData = StringUtils::ToUtf8(message); + LengthInfo result; + int32_t ret = interfaceManager->GetSmsSegmentsInfo(messageData, force7BitCode, result); + if (ret != TELEPHONY_ERR_SUCCESS) { + return ret; + } + info.msgSegCount = static_cast(result.msgSegCount); + info.msgEncodingCount = static_cast(result.msgEncodeCount); + info.msgRemainCount = static_cast(result.msgRemainCount); + SmsSegmentsInfo::SmsSegmentCodeScheme dcs = static_cast(result.dcs); + switch (dcs) { + case SmsSegmentsInfo::SmsSegmentCodeScheme::SMS_ENCODING_7BIT: + case SmsSegmentsInfo::SmsSegmentCodeScheme::SMS_ENCODING_8BIT: + case SmsSegmentsInfo::SmsSegmentCodeScheme::SMS_ENCODING_16BIT: + info.msgCodeScheme = dcs; + break; + default: + info.msgCodeScheme = SmsSegmentsInfo::SmsSegmentCodeScheme::SMS_ENCODING_UNKNOWN; + break; + } + return TELEPHONY_ERR_SUCCESS; +} + +int32_t SmsService::GetServiceRunningState() +{ + return static_cast(state_); +} + +int64_t SmsService::GetEndTime() +{ + return endTime_; +} + +bool SmsService::ValidDestinationAddress(std::string desAddr) +{ + // Allow address start with '+' and number, Address length range 3 to 20 + std::regex regexMode("^([0-9_+]{1})([0-9]{2,19})$"); + return std::regex_match(desAddr, regexMode); +} + +int64_t SmsService::GetSpendTime() +{ + spendTime_ = endTime_ - bindTime_; + return spendTime_; +} + +int32_t SmsService::CreateMessage(std::string pdu, std::string specification, ShortMessage &message) +{ + std::shared_ptr baseMessage; + if (specification == "3gpp") { + baseMessage = GsmSmsMessage::CreateMessage(pdu); + } else if (specification == "3gpp2") { + baseMessage = CdmaSmsMessage::CreateMessage(pdu); + } + + if (baseMessage == nullptr) { + return TELEPHONY_ERR_LOCAL_PTR_NULL; + } + message.visibleMessageBody_ = StringUtils::ToUtf16(baseMessage->GetVisibleMessageBody()); + message.visibleRawAddress_ = StringUtils::ToUtf16(baseMessage->GetVisibleOriginatingAddress()); + message.messageClass_ = static_cast(baseMessage->GetMessageClass()); + message.scAddress_ = StringUtils::ToUtf16(baseMessage->GetSmscAddr()); + message.scTimestamp_ = baseMessage->GetScTimestamp(); + message.isReplaceMessage_ = baseMessage->IsReplaceMessage(); + message.status_ = baseMessage->GetStatus(); + message.isSmsStatusReportMessage_ = baseMessage->IsSmsStatusReportMessage(); + message.hasReplyPath_ = baseMessage->HasReplyPath(); + message.protocolId_ = baseMessage->GetProtocolId(); + message.pdu_ = baseMessage->GetRawPdu(); + return TELEPHONY_ERR_SUCCESS; +} + +bool SmsService::GetBase64Encode(std::string src, std::string &dest) +{ + MsgTextConvert *textCvt = MsgTextConvert::Instance(); + if (textCvt == nullptr) { + return false; + } + + textCvt->Base64Encode(src, dest); + return true; +} + +bool SmsService::GetBase64Decode(std::string src, std::string &dest) +{ + MsgTextConvert *textCvt = MsgTextConvert::Instance(); + if (textCvt == nullptr) { + return false; + } + + textCvt->Base64Decode(src, dest); + return true; +} + +bool SmsService::GetEncodeStringFunc( + std::string &encodeString, uint32_t charset, uint32_t valLength, std::string strEncodeString) +{ + MsgTextConvert *textCvt = MsgTextConvert::Instance(); + if (textCvt == nullptr) { + return false; + } + + textCvt->GetEncodeString(encodeString, charset, valLength, strEncodeString); + return true; +} +} // namespace Telephony +} // namespace OHOS \ No newline at end of file diff --git a/rejectAndSendMessage/sms_service.h b/rejectAndSendMessage/sms_service.h new file mode 100644 index 0000000..79aa220 --- /dev/null +++ b/rejectAndSendMessage/sms_service.h @@ -0,0 +1,316 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SMS_SERVICE_H +#define SMS_SERVICE_H + +#include + +#include "sms_interface_stub.h" +#include "sms_state_handler.h" +#include "system_ability.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Telephony { +enum ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +class SmsService : public SystemAbility, public SmsInterfaceStub, public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(SmsService) + DECLARE_SYSTEM_ABILITY(SmsService) // necessary +public: + void OnStart() override; + void OnStop() override; + int32_t Dump(std::int32_t fd, const std::vector &args) override; + std::string GetBindTime(); + + /** + * Sends a text Type SMS message. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param desAddr Indicates the destination address + * @param scAddr Indicates the sms center address + * @param text Indicates sms content + * @param sendCallback Indicates callback for send out + * @param deliverCallback Indicates callback for delivery to destination user + * @return Returns {@code 0} if send message success. + */ + int32_t SendMessage(int32_t slotId, const std::u16string desAddr, const std::u16string scAddr, + const std::u16string text, const sptr &sendCallback, + const sptr &deliveryCallback) override; + + /** + * Sends a data Type SMS message. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param desAddr Indicates the destination address + * @param scAddr Indicates the sms center address + * @param port Indicates the port of data sms + * @param data Indicates the array of data sms + * @param dataLen Indicates the array length of data sms + * @param sendCallback Indicates callback for send out + * @param deliverCallback Indicates callback for delivery to destination user + * @return Returns {@code 0} if send message success. + */ + int32_t SendMessage(int32_t slotId, const std::u16string desAddr, const std::u16string scAddr, uint16_t port, + const uint8_t *data, uint16_t dataLen, const sptr &sendCallback, + const sptr &deliveryCallback) override; + + /** + * Sets the address for the Short Message Service Center (SMSC) based on a + * specified slot ID + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param scAddr Indicates the sms center address + * @return Returns {@code 0} if set smsc success + */ + int32_t SetSmscAddr(int32_t slotId, const std::u16string &scAddr) override; + + /** + * @brief GetSmscAddr + * Obtains the SMSC address based on a specified slot ID. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param smscAddress [out] + * @return Returns {@code 0} if get smsc success. + */ + int32_t GetSmscAddr(int32_t slotId, std::u16string &smscAddress) override; + + /** + * @brief AddSimMessage + * Add a sms to sim card. + * @param slotId [in] + * @param smsc [in] + * @param pdu [in] + * @param status [in] + * @return Returns {@code true} if add sim success; returns {@code false} + + */ + int32_t AddSimMessage( + int32_t slotId, const std::u16string &smsc, const std::u16string &pdu, SimMessageStatus status) override; + + /** + * @brief DelSimMessage + * Delete a sms in the sim card. + * @param slotId [in] + * @param msgIndex [in] + * @return Returns {@code true} if delete sim success; returns {@code false} + */ + int32_t DelSimMessage(int32_t slotId, uint32_t msgIndex) override; + + /** + * @brief UpdateSimMessage + * Update a sms in the sim card. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param msgIndex Indicates the sim sms index in sim card + * @param newStatusIndicates the sms status, read or not + * @param pdu Indicates the sms pdu data + * @param smsc Indicates the sms center address + * @return Returns {@code 0} if update sim success + */ + int32_t UpdateSimMessage(int32_t slotId, uint32_t msgIndex, SimMessageStatus newStatus, const std::u16string &pdu, + const std::u16string &smsc) override; + + /** + * @brief GetAllSimMessages + * Get sim card all the sms. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param message Indicates all SMS messages of sim card + * @return Returns {@code 0} if get all sim messages success + */ + int32_t GetAllSimMessages(int32_t slotId, std::vector &message) override; + + /** + * @brief SetCBConfig + * Configure a cell broadcast in a certain band range. + * @param slotId [in] + * @param enable [in] + * @param fromMsgId [in] + * @param toMsgId [in] + * @param netType [in] + * @return Returns {@code 0} if set CB config success + */ + int32_t SetCBConfig(int32_t slotId, bool enable, uint32_t fromMsgId, uint32_t toMsgId, uint8_t netType) override; + + /** + * @brief SetImsSmsConfig enable or disable IMS SMS. + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by the device. + * @param enable Indicates enable or disable Ims sms + * ranging {@code 0} disable Ims sms {@code 1} enable Ims sms + * @return Returns {@code true} if enable or disable Ims Sms success; returns {@code false} otherwise. + */ + bool SetImsSmsConfig(int32_t slotId, int32_t enable) override; + + /** + * @brief SetDefaultSmsSlotId + * Set the Default Sms Slot Id To SmsService + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @return Returns {@code 0} if set default sms slot id success + */ + int32_t SetDefaultSmsSlotId(int32_t slotId) override; + + /** + * @brief GetDefaultSmsSlotId + * Get the Default Sms Slot Id From SmsService + * @return int32_t + */ + int32_t GetDefaultSmsSlotId() override; + + /** + * @brief SplitMessage + * calculate Sms Message Split Segment count + * @param Indicates input message + * @param splitMessage Indicates the split information + * @return Returns {@code 0} if split message success + */ + int32_t SplitMessage(const std::u16string &message, std::vector &splitMessage) override; + + /** + * @brief GetSmsSegmentsInfo + * calculate the Sms Message Segments Info + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param message Indicates input message + * @param force7BitCode Indicates sms encode type, 7bit or not + * @param info Indicates output sms segment + * @return Returns {@code 0} if get sms segments info + */ + int32_t GetSmsSegmentsInfo(int32_t slotId, const std::u16string &message, bool force7BitCode, + ISmsServiceInterface::SmsSegmentsInfo &info) override; + + /** + * @brief IsImsSmsSupported + * Check Sms Is supported Ims newtwork + * Hide this for inner system use + * @param slotId Indicates the card slot index number, + * ranging from {@code 0} to the maximum card slot index number supported by + * the device + * @param isSupported Whether ims SMS is supported + * @return Returns {@code 0} if successful + */ + int32_t IsImsSmsSupported(int32_t slotId, bool &isSupported) override; + + /** + * @brief GetImsShortMessageFormat + * Get the Ims Short Message Format 3gpp/3gpp2 + * Hide this for inner system use + * @return int32_t + */ + int32_t GetImsShortMessageFormat(std::u16string &format) override; + + /** + * @brief HasSmsCapability + * Check whether it is supported Sms Capability + * @return true + * @return false + */ + bool HasSmsCapability() override; + + /** + * @brief GetServiceRunningState + * Get service running state + * @return ServiceRunningState + */ + int32_t GetServiceRunningState(); + + /** + * @brief GetSpendTime + * Get service start spend time + * @return Spend time + */ + int64_t GetSpendTime(); + + /** + * @brief GetEndTime + * Get service start finish time + * @return Spend time + */ + int64_t GetEndTime(); + + /** + * create a short message + * @param pdu Indicates pdu code, + * @param specification Indicates 3gpp or 3gpp2 + * @param ShortMessage Indicates a short message object + * @return Returns {@code 0} if CreateMessage success + */ + int32_t CreateMessage(std::string pdu, std::string specification, ShortMessage &message) override; + + /** + * mms base64 encode + * @param src Indicates source string, + * @param dest Indicates destination string + * @return Returns {@code true} if encode success; returns {@code false} otherwise + */ + bool GetBase64Encode(std::string src, std::string &dest) override; + + /** + * mms base64 decode + * @param src Indicates source string, + * @param dest Indicates destination string + * @return Returns {@code true} if decode success; returns {@code false} otherwise + */ + bool GetBase64Decode(std::string src, std::string &dest) override; + + /** + * Get Encode String + * @param encodeString Indicates output string, + * @param charset Indicates character set, + * @param valLength Indicates input string length, + * @param strEncodeString Indicates input string + * @return Returns {@code true} if decode success; returns {@code false} otherwise + */ + bool GetEncodeStringFunc( + std::string &encodeString, uint32_t charset, uint32_t valLength, std::string strEncodeString) override; + +private: + bool Init(); + void WaitCoreServiceToInit(); + bool NoPermissionOrParametersCheckFail( + int32_t slotId, const std::u16string desAddr, const sptr &sendCallback); + bool ValidDestinationAddress(std::string desAddr); + void TrimSmscAddr(std::string &sca); + void InsertSessionAndDetail(int32_t slotId, const std::string &telephone, const std::string &text); + void InsertSmsMmsInfo(int32_t slotId, uint16_t sessionId, const std::string &number, const std::string &text); + bool InsertSession(bool isNewSession, uint16_t messageCount, const std::string &number, const std::string &text); + bool QuerySessionByTelephone(const std::string &telephone, uint16_t §ionId, uint16_t &messageCount); + bool CheckSimMessageIndexValid(int32_t slotId, uint32_t msgIndex); + +private: + int64_t bindTime_ = 0; + int64_t endTime_ = 0; + int64_t spendTime_ = 0; + bool registerToService_ = false; + ServiceRunningState state_ = ServiceRunningState::STATE_NOT_START; + std::shared_ptr smsStateHandler_; + const std::string SMS_MMS_INFO = "datashare:///com.ohos.smsmmsability/sms_mms/sms_mms_info"; + const std::string SESSION = "datashare:///com.ohos.smsmmsability/sms_mms/session"; + const std::string COM_OHOS_MMS = "100050"; +}; +} // namespace Telephony +} // namespace OHOS +#endif \ No newline at end of file