Signed-off-by: jiangbinghan <jiangbinghan@huawei.com>
This commit is contained in:
jiangbinghan 2023-05-06 09:43:43 +08:00
parent 47001d0999
commit 9cbf828983
45 changed files with 4305 additions and 4326 deletions

View File

@ -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

View File

@ -1,6 +1,11 @@
{
"apiType": 'stageMode',
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/workers/base/Worker.ts"
]
}
},
"targets": [
{

View File

@ -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) => {

View File

@ -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);

View File

@ -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<void> {
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<LooseObject> = [];
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<number> {
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<LooseObject> = 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<LooseObject> = [];
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));
});
}
}

View File

@ -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
},
}

View File

@ -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-No1-Yes integer
isRead: "is_read", // Read or Not 0-Read1-Unread integer
isRead: "is_read", // Read or Not
isCollect: "is_collect", //Favorites 0-Not favorited1-Favorites integer
sessionType: "session_type", //Session Type 0 - Common 1 - broadcast 2 - Group Sending integer
retryNumber: "retry_number", //Retry Times integer

View File

@ -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;
}
}

View File

@ -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<void> {
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<LooseObject> = [];
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<void> {
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<void> {
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<LooseObject> = [];
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<void> {
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<void> {
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<void> {
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<LooseObject> = [];
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<string> {
// part of contact_data table columns
return [
mmsTable.contactDataColumns.detailInfo,
mmsTable.contactDataColumns.displayName,
];
}
private buildContactTablePartColumns(): Array<string> {
// part of contact table columns
return [
mmsTable.contactColumns.id
];
}
private buildRawContactTablePartColumns(): Array<string> {
// part of raw_contact table columns
return [
mmsTable.contactDataColumns.id
];
}
private buildRawContactViewPartColumns(): Array<string> {
// 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;
}
}

View File

@ -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<void> {
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<void> {
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<void> {
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<void> {
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<LooseObject> = [];
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<void> {
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<string> {
let sessionTableColumns: Array<string> = [
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;
}
}

View File

@ -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<void> {
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<void> {
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<void> {
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<void> {
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<LooseObject> = [];
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<void> {
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<void> {
let dataHelper = await dataShare.createDataShareHelper(context, common.string.URI_MESSAGE_LOG);
let resultColumns: Array<string> = ["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<string> = [
"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<string> {
let resultColumns: Array<string> = [
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;
}
}

View File

@ -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();

View File

@ -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;
}

View File

@ -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 })

View File

@ -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<LooseObject> = <Array<LooseObject>>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<LooseObject> = [];
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<LooseObject> = [];
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, () => {
});
}
}

View File

@ -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<any> = [];
// List of search results
searchResultList: LooseObject = {
sessionList: [],
contentList: []
"sessionList": [],
"contentList": []
};
// Search Results Queue
searchResultListQueue: Array<any> = [];
@ -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<LooseObject> = [];
let threadIds: Array<number> = [];
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<number> = [];
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<LooseObject> = 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<LooseObject> = 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;
}

View File

@ -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 })
}
}

View File

@ -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<any> = [];
@ -88,7 +84,6 @@ export default class InfoMsgController {
// Number of unread notifications.
unreadTotalOfInfo: number = 0;
messageList: Array<any> = [];
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<number> = [];
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<LooseObject> = 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<LooseObject> = [];
let threadIds: Array<number> = [];
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;
}

View File

@ -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%")

View File

@ -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 })

View File

@ -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

View File

@ -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<any> = [];
contactsList: Array<any> = [];
// List of contents forwarded by multiple messages
transmitContentList: Array<any> = [];
// 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<any> = [];
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',

View File

@ -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

View File

@ -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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<LooseObject> = 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<LooseObject> = [];
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<LooseObject> {
let contactList: Array<LooseObject> = [];
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;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -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);
}
};

View File

@ -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) {

View File

@ -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) {

View File

@ -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<number> {
let groupIds: Array<number> = [];
if (resultList != null) {
for (let item of resultList) {
if (item.groupId != null) {
groupIds.push(item.groupId);
}
}
}
return groupIds;
}
}
// Singleton
export default new StringUtil();

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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);
})
})

View File

@ -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) {

View File

@ -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;
}
}

View File

@ -37,7 +37,7 @@ export default class WorkFactory {
let data = <WorkerMessage> 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();

View File

@ -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<string, (result?: any) => 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();
}

View File

@ -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": "转自 我:"},

View File

@ -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:"},

View File

@ -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": "转自 我:"},

View File

@ -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

View File

@ -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<DataShare::DataShareHelper> 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<DataShare::DataShareHelper> 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<DataShare::DataShareHelper> 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 &sectionId,
uint16_t &messageCount)
{
std::shared_ptr<DataShare::DataShareHelper> helper = CreateDataShareHelper(SMS_URI);
if (helper == nullptr) {
TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed.");
return false;
}
Uri uri(SESSION);
std::vector<std::string> 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<DataShare::DataShareHelper> 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<SmsReceiveIndexer> &indexers)
{
std::shared_ptr<DataShare::DataShareHelper> helper = CreateDataShareHelper(SMS_URI);
if (helper == nullptr) {
TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed.");
return false;
}
Uri uri(SMS_SUBSECTION);
std::vector<std::string> 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<DataShare::DataShareHelper> helper = CreateDataShareHelper(SMS_URI);
if (helper == nullptr) {
TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed.");
return false;
}
Uri uri(SMS_MMS_INFO);
std::vector<std::string> 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<DataShare::DataShareHelper> 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<DataShare::DataShareHelper> helper = CreateDataShareHelper(CONTACT_URI);
if (helper == nullptr) {
TELEPHONY_LOGE("Create Data Ability Helper nullptr Failed.");
return false;
}
Uri uri(CONTACT_BLOCK);
std::vector<std::string> 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<DataShare::DataShareResultSet> &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<DataShare::DataShareResultSet> &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<DataShare::DataShareResultSet> &resultSet)
{
ConvertIntToIndexer(info, resultSet);
ConvertStringToIndexer(info, resultSet);
}
} // namespace Telephony
} // namespace OHOS

View File

@ -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<SmsReceiveIndexer> &indexers);
bool QueryMaxGroupId(DataShare::DataSharePredicates &predicates, uint16_t &maxGroupId);
bool QuerySession(DataShare::DataSharePredicates &predicates, uint16_t &sectionId, 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<DataShare::DataShareHelper> CreateDataShareHelper(std::string uri);
void ResultSetConvertToIndexer(
SmsReceiveIndexer &info, const std::shared_ptr<DataShare::DataShareResultSet> &resultSet);
void ConvertIntToIndexer(
SmsReceiveIndexer &info, const std::shared_ptr<DataShare::DataShareResultSet> &resultSet);
void ConvertStringToIndexer(
SmsReceiveIndexer &info, const std::shared_ptr<DataShare::DataShareResultSet> &resultSet);
};
} // namespace Telephony
} // namespace OHOS
#endif

View File

@ -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 <regex>
#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<SmsService>::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::milliseconds>(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::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count();
TELEPHONY_LOGI("SmsService::OnStart start service Exit.");
}
bool SmsService::Init()
{
DelayedSingleton<ImsSmsClient>::GetInstance()->Init();
if (!registerToService_) {
bool ret = Publish(DelayedSingleton<SmsService>::GetInstance().get());
if (!ret) {
TELEPHONY_LOGE("SmsService::Init Publish failed!");
return false;
}
registerToService_ = true;
WaitCoreServiceToInit();
}
DelayedSingleton<SmsStateHandler>::GetInstance()->Init();
return true;
}
void SmsService::OnStop()
{
state_ = ServiceRunningState::STATE_NOT_START;
registerToService_ = false;
DelayedSingleton<ImsSmsClient>::GetInstance()->UnInit();
DelayedSingleton<SmsStateHandler>::GetInstance()->UnInit();
TELEPHONY_LOGI("SmsService::OnStop stop service.");
}
int32_t SmsService::Dump(std::int32_t fd, const std::vector<std::u16string> &args)
{
if (fd < 0) {
TELEPHONY_LOGE("dump fd invalid");
return TELEPHONY_ERR_FAIL;
}
std::vector<std::string> 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<ISendShortMessageCallback> &sendCallback, const sptr<IDeliveryShortMessageCallback> &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<SmsInterfaceManager> 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 &sectionId, uint16_t &messageCount)
{
DataShare::DataSharePredicates predicates;
predicates.EqualTo(Session::TELEPHONE, telephone);
return DelayedSingleton<SmsPersistHelper>::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<SmsPersistHelper>::GetInstance()->QueryMaxGroupId(predicates, maxGroupId);
auto now = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(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<SmsPersistHelper>::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<std::chrono::milliseconds>(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<SmsPersistHelper>::GetInstance()->Update(predicates, sessionBucket);
}
sessionBucket.Put(Session::MESSAGE_COUNT, "1");
return DelayedSingleton<SmsPersistHelper>::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<ISendShortMessageCallback> &sendCallback,
const sptr<IDeliveryShortMessageCallback> &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<SmsInterfaceManager> 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<ISendShortMessageCallback> &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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<ShortMessage> &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<SmsInterfaceManager> 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<ShortMessage> 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<int32_t>(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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<std::u16string> &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<SmsInterfaceManager> 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<SmsInterfaceManager> 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<int32_t>(result.msgSegCount);
info.msgEncodingCount = static_cast<int32_t>(result.msgEncodeCount);
info.msgRemainCount = static_cast<int32_t>(result.msgRemainCount);
SmsSegmentsInfo::SmsSegmentCodeScheme dcs = static_cast<SmsSegmentsInfo::SmsSegmentCodeScheme>(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<int32_t>(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<SmsBaseMessage> 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<ShortMessage::SmsMessageClass>(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

View File

@ -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 <memory>
#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<SmsService> {
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<std::u16string> &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<ISendShortMessageCallback> &sendCallback,
const sptr<IDeliveryShortMessageCallback> &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<ISendShortMessageCallback> &sendCallback,
const sptr<IDeliveryShortMessageCallback> &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<ShortMessage> &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<std::u16string> &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<ISendShortMessageCallback> &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 &sectionId, 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> 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