• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "map_mse_resource.h"
17 #include <iomanip>
18 #include <sstream>
19 #include <algorithm>
20 
21 namespace OHOS {
22 namespace bluetooth {
23 const std::string MapMseResource::XML_TAG_CONVO_LISTING = "MAP-convo-listing";
24 const std::string MapMseResource::XML_ATT_ENCODING = "encoding";
25 const std::string MapMseResource::XML_ATT_VERSION = "version";
26 const std::string MapMseResource::XML_TAG_CONVERSATION = "conversation";
27 const std::string MapMseResource::XML_ATT_LAST_ACTIVITY = "last_activity";
28 const std::string MapMseResource::XML_ATT_NAME = "name";
29 const std::string MapMseResource::XML_ATT_ID = "id";
30 const std::string MapMseResource::XML_ATT_READ = "read_status";
31 const std::string MapMseResource::XML_ATT_VERSION_COUNTER = "version_counter";
32 const std::string MapMseResource::XML_ATT_SUMMARY = "summary";
33 const std::string MapMseResource::XML_TAG_PARTICIPANT = "participant";
34 const std::string MapMseResource::XML_ATT_UCI = "uci";
35 const std::string MapMseResource::XML_ATT_DISPLAY_NAME = "display_name";
36 const std::string MapMseResource::XML_ATT_CHAT_STATE = "chat_state";
37 const std::string MapMseResource::XML_ATT_PRIORITY = "priority";
38 const std::string MapMseResource::XML_ATT_PRESENCE_TEXT = "presence_text";
39 const std::string MapMseResource::XML_ATT_PRESENCE_AVAILABILITY = "presence_availability";
40 const std::string MapMseResource::XML_ATT_X_BT_UID = "x_bt_uid";
41 const std::string MapMseResource::TYPE_NEW = "NewMessage";
42 const std::string MapMseResource::TYPE_DELETE = "MessageDeleted";
43 const std::string MapMseResource::TYPE_SHIFT = "MessageShift";
44 const std::string MapMseResource::TYPE_SENDING_SUCCESS = "SendingSuccess";
45 const std::string MapMseResource::TYPE_SENDING_FAILURE = "SendingFailure";
46 const std::string MapMseResource::TYPE_DELIVERY_SUCCESS = "DeliverySuccess";
47 const std::string MapMseResource::TYPE_DELIVERY_FAILURE = "DeliveryFailure";
48 const std::string MapMseResource::TYPE_MEMORY_FULL = "MemoryFull";
49 const std::string MapMseResource::TYPE_MEMORY_AVAILABLE = "MemoryAvailable";
50 const std::string MapMseResource::TYPE_READ_STATUS = "ReadStatusChanged";
51 const std::string MapMseResource::TYPE_CONVERSATION = "ConversationChanged";
52 const std::string MapMseResource::TYPE_PRESENCE = "ParticipantPresenceChanged";
53 const std::string MapMseResource::TYPE_CHAT_STATE = "ParticipantChatStateChanged";
54 const std::string MapMseResource::TYPE_EXTENDED_DATA = "MessageExtendedDataChanged";
55 const std::string MapMseResource::TYPE_REMOVED = "MessageRemoved";
56 
MapMseResource(MapMseMnscli & mnsClient,utility::Dispatcher & dispatcher,MapMseInstance & instance)57 MapMseResource::MapMseResource(MapMseMnscli &mnsClient, utility::Dispatcher &dispatcher, MapMseInstance &instance)
58     : mnsClient_(&mnsClient), dispatcher_(dispatcher), instance_(instance), reportVersion_(MAP_EVENT_REPORT_V10)
59 {
60     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
61     masId_ = instance_.GetMasId();
62     observerMap_[masId_] = std::make_unique<EventObserver>(*this);
63     for (auto iter = observerMap_.begin(); iter != observerMap_.end(); iter++) {
64         stub::MapService::GetInstance()->RegisterObserver(
65             (stub::MapServiceObserver *)observerMap_[masId_].get(), masId_);
66     }
67 }
68 
~MapMseResource()69 MapMseResource::~MapMseResource()
70 {
71     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
72     for (auto iter = observerMap_.begin(); iter != observerMap_.end(); iter++) {
73         stub::MapService::GetInstance()->DeregisterObserver(iter->second.get(), masId_);
74     }
75     observerMap_.clear();
76 }
77 
GetParticipantSql(const MapMseParams & appParameter)78 std::string MapMseResource::GetParticipantSql(const MapMseParams &appParameter)
79 {
80     std::string sql = "select uci, display_name, chat_state, last_activity, x_bt_uid, name, presence_availability, "
81                       "presence_text, priority from Participant where convo_id = ? ";
82 
83     if (appParameter.filterRecipient_ != "") {
84         std::string recpt = appParameter.filterRecipient_;
85         if (recpt.find('*') == std::string::npos) {
86             sql.append(" and (convo_id like '%' || ? || '%' or name like '%' || ? || '%')");
87         } else {
88             std::size_t i = recpt.find('*');
89             std::string left = recpt.substr(0, i);
90             std::string right = recpt.substr(i + 1);
91             if (left != "") {
92                 sql.append(" and (convo_id like ? || '%' or name like ? || '%')");
93             } else if (right != "") {
94                 sql.append(" and (convo_id like '%' || ? or name like '%' || ?)");
95             }
96         }
97     }
98     return sql;
99 }
100 
GetCvslistSql(const MapMseParams & appParameter)101 std::string MapMseResource::GetCvslistSql(const MapMseParams &appParameter)
102 {
103     std::string sql = "select convo_id, name, last_activity, read_status, version_counter,"
104                       "summary from Conversation where 1 = 1";
105 
106     if (appParameter.filterLastActivityBegin_ != "") {
107         sql.append(" and last_activity >= ?");
108     }
109     if (appParameter.filterLastActivityEnd_ != "") {
110         sql.append(" and last_activity <= ?");
111     }
112     if (appParameter.filterReadStatus_ != nullptr) {
113         if (*appParameter.filterReadStatus_ == 0x1 || *appParameter.filterReadStatus_ == 0x2) {
114             sql.append(" and read_status = ?");
115         }
116     }
117     if (appParameter.conversationId_ != "") {
118         sql.append(" and convo_id = ?");
119     }
120     sql.append(" order by id desc");
121     if (appParameter.maxListCount_ != 0x0) {
122         sql.append(" limit ?");
123         sql.append(" offset ?");
124     }
125     return sql;
126 }
127 
SetParticipantParam(IDataStatement & ids,const MapMseParams & appParameter,const std::string & convoId)128 void MapMseResource::SetParticipantParam(
129     IDataStatement &ids, const MapMseParams &appParameter, const std::string &convoId)
130 {
131     ids.ClearParams();
132     int index = 1;
133     ids.SetParamString(index++, convoId);
134     if (appParameter.filterRecipient_ != "") {
135         if (appParameter.filterRecipient_.find('*') == std::string::npos) {
136             ids.SetParamString(index++, appParameter.filterRecipient_);
137             ids.SetParamString(index++, appParameter.filterRecipient_);
138         } else {
139             std::string recpt = appParameter.filterRecipient_;
140             std::size_t i = recpt.find('*');
141             std::string left = recpt.substr(0, i);
142             std::string right = recpt.substr(i + 1);
143             if (left != "") {
144                 ids.SetParamString(index++, left);
145                 ids.SetParamString(index++, left);
146             } else if (right != "") {
147                 ids.SetParamString(index++, right);
148                 ids.SetParamString(index++, right);
149             }
150         }
151     }
152 }
153 
SetCvslistParam(IDataStatement & ids,const MapMseParams & appParameter)154 void MapMseResource::SetCvslistParam(IDataStatement &ids, const MapMseParams &appParameter)
155 {
156     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
157 
158     int index = 1;
159     if (appParameter.filterLastActivityBegin_ != "") {
160         ids.SetParamString(index++, appParameter.filterLastActivityBegin_);
161     }
162     if (appParameter.filterLastActivityEnd_ != "") {
163         ids.SetParamString(index++, appParameter.filterLastActivityEnd_);
164     }
165     if (appParameter.filterReadStatus_ != nullptr) {
166         if (*appParameter.filterReadStatus_ == 0x1) {
167             ids.SetParamInt(index++, 0);
168         } else if (*appParameter.filterReadStatus_ == 0x2) {
169             ids.SetParamInt(index++, 1);
170         }
171     }
172     if (appParameter.conversationId_ != "") {
173         ids.SetParamString(index++, appParameter.conversationId_);
174     }
175     if (appParameter.maxListCount_ != 0x0) {
176         ids.SetParamInt(index++, appParameter.maxListCount_);
177         ids.SetParamInt(index++, appParameter.listStartOffSet_);
178     }
179 }
180 
GetConvoLstCount(const MapMseParams & appParameter)181 int MapMseResource::GetConvoLstCount(const MapMseParams &appParameter)
182 {
183     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
184 
185     int count = 0;
186     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE);
187     if (!dataProvider) {
188         return count;
189     }
190     std::string sql = GetCvslistSql(appParameter);
191     auto stmt = dataProvider->CreateStatement(sql);
192     if (!stmt) {
193         return count;
194     }
195     SetCvslistParam(*stmt, appParameter);
196     auto dataResult = stmt->Query();
197     std::string tempId;
198     while (dataResult->Next()) {
199         if (tempId != dataResult->GetString(0)) {
200             tempId = dataResult->GetString(0);
201             count++;
202         }
203     }
204     return count;
205 }
206 
GetParticipantContent(IDataStatement & ids,const MapMseParams & appParameter,const std::string & convoId)207 std::vector<MseParticipant> MapMseResource::GetParticipantContent(
208     IDataStatement &ids, const MapMseParams &appParameter, const std::string &convoId)
209 {
210     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
211 
212     SetParticipantParam(ids, appParameter, convoId);
213     auto dataResult = ids.Query();
214     std::vector<MseParticipant> contacts;
215     while (dataResult->Next()) {
216         MseParticipant contact;
217         contact.uci_ = dataResult->GetString(0);
218         contact.displayName_ = dataResult->GetString(0x1);
219         if (dataResult->IsNotNull(0x2)) {
220             contact.chatState_ = dataResult->GetInt(0x2);
221         }
222         contact.lastActy_ = dataResult->GetString(0x3);
223         contact.btUid_ = dataResult->GetString(0x4);
224         contact.name_ = dataResult->GetString(0x5);
225         if (dataResult->IsNotNull(0x6)) {
226             contact.presenceAvailability_ = dataResult->GetInt(0x6);
227         }
228         contact.presenceText_ = dataResult->GetString(0x7);
229         if (dataResult->IsNotNull(0x8)) {
230             contact.priority_ = dataResult->GetInt(0x8);
231         }
232         contacts.push_back(contact);
233         MSE_LOG_INFO("contacts : %{public}zu Enter", contacts.size());
234     }
235     return contacts;
236 }
237 
GetConvoLstContent(const MapMseParams & appParameter)238 std::vector<std::unique_ptr<MseConvoLstElement>> MapMseResource::GetConvoLstContent(const MapMseParams &appParameter)
239 {
240     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
241 
242     std::vector<std::unique_ptr<MseConvoLstElement>> convoList;
243     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE);
244     if (!dataProvider) {
245         return convoList;
246     }
247     std::string sql = GetCvslistSql(appParameter);
248     auto stmt = dataProvider->CreateStatement(sql);
249     SetCvslistParam(*stmt, appParameter);
250     auto dataResult = stmt->Query();
251     std::unordered_map<std::string, std::unique_ptr<MseConvoLstElement>> convoElementMap;
252     std::vector<std::string> convoIds;
253     while (dataResult->Next()) {
254         std::string convId = dataResult->GetString(0);
255         auto convoElement = std::make_unique<MseConvoLstElement>();
256         convoElement->convoId_ = convId;
257         convoElement->name_ = dataResult->GetString(0x1);
258         convoElement->lastActivity_ = dataResult->GetString(0x2);
259         if (dataResult->IsNotNull(0x3))
260             convoElement->readStatus_ = dataResult->GetInt(0x3);
261         convoElement->versionCounter_ = dataResult->GetString(0x4);
262         convoElement->summary_ = dataResult->GetString(0x5);
263         convoElementMap[convId] = std::move(convoElement);
264         convoIds.push_back(convId);
265     }
266 
267     std::string sql2 = GetParticipantSql(appParameter);
268     auto stmt2 = dataProvider->CreateStatement(sql2);
269     for (auto &iter : convoIds) {
270         auto contacts = GetParticipantContent(*stmt2, appParameter, iter);
271         MSE_LOG_INFO("contacts : %{public}zu Enter", contacts.size());
272         convoElementMap[iter]->contacts_ = contacts;
273         convoList.push_back(std::move(convoElementMap[iter]));
274     }
275     return convoList;
276 }
277 
ParticipantsToXml(xmlNodePtr & node,std::vector<MseParticipant> & contacts,long paraMask)278 void MapMseResource::ParticipantsToXml(xmlNodePtr &node, std::vector<MseParticipant> &contacts, long paraMask)
279 {
280     for (auto &contact : contacts) {
281         xmlNodePtr subNode = xmlNewNode(NULL, BAD_CAST XML_TAG_PARTICIPANT.c_str());
282         xmlAddChild(node, subNode);
283         if (CheckParameterMask(PARTI_UCI_MASK, contact.uci_, paraMask, true)) {
284             xmlNewProp(subNode, BAD_CAST XML_ATT_UCI.c_str(), BAD_CAST contact.uci_.c_str());
285         }
286         if (CheckParameterMask(PARTI_DISPLAY_NAME_MASK, contact.displayName_, paraMask, true)) {
287             xmlNewProp(subNode, BAD_CAST XML_ATT_DISPLAY_NAME.c_str(), BAD_CAST contact.displayName_.c_str());
288         }
289         if (CheckParameterMask(PARTI_CHAT_STATE_MASK, std::to_string(contact.chatState_), paraMask, true)) {
290             xmlNewProp(subNode,
291                 BAD_CAST XML_ATT_CHAT_STATE.c_str(),
292                 BAD_CAST std::to_string(contact.chatState_).c_str());
293         }
294         if (CheckParameterMask(PARTI_LAST_ACTIVITY_MASK, contact.lastActy_, paraMask, true)) {
295             xmlNewProp(subNode, BAD_CAST XML_ATT_LAST_ACTIVITY.c_str(), BAD_CAST contact.lastActy_.c_str());
296         }
297         if (CheckParameterMask(PARTI_X_BT_UID_MASK, contact.btUid_, paraMask)) {
298             xmlNewProp(subNode, BAD_CAST XML_ATT_X_BT_UID.c_str(), BAD_CAST contact.btUid_.c_str());
299         }
300         if (CheckParameterMask(PARTI_NAME_MASK, contact.name_, paraMask)) {
301             xmlNewProp(subNode, BAD_CAST XML_ATT_NAME.c_str(), BAD_CAST contact.name_.c_str());
302         }
303         if (CheckParameterMask(PARTI_PRESENCE_AVAIL_MASK, std::to_string(contact.presenceAvailability_), paraMask)) {
304             xmlNewProp(subNode,
305                 BAD_CAST XML_ATT_PRESENCE_AVAILABILITY.c_str(),
306                 BAD_CAST std::to_string(contact.presenceAvailability_).c_str());
307         }
308         if (CheckParameterMask(PARTI_PRESENCE_TEXT_MASK, contact.presenceText_, paraMask)) {
309             xmlNewProp(subNode, BAD_CAST XML_ATT_PRESENCE_TEXT.c_str(), BAD_CAST contact.presenceText_.c_str());
310         }
311         if (CheckParameterMask(PARTI_PRIORITY_MASK, std::to_string(contact.priority_), paraMask)) {
312             xmlNewProp(subNode, BAD_CAST XML_ATT_PRIORITY.c_str(), BAD_CAST std::to_string(contact.priority_).c_str());
313         }
314     }
315 }
316 
GetCvslistBodyXml(const MapMseParams & appParameter,uint16_t & size)317 std::string MapMseResource::GetCvslistBodyXml(const MapMseParams &appParameter, uint16_t &size)
318 {
319     long paraMask = appParameter.convParameterMask_;
320     auto convoList = GetConvoLstContent(appParameter);
321     size = convoList.size();
322 
323     xmlChar *xmlbuff;
324     int buffersize;
325     std::ostringstream oss;
326 
327     xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
328     xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST XML_TAG_CONVO_LISTING.c_str());
329     xmlDocSetRootElement(doc, root_node);
330     xmlNewProp(root_node, BAD_CAST "version", BAD_CAST MAP_V10.c_str());
331 
332     for (auto &iter : convoList) {
333         xmlNodePtr node = xmlNewNode(NULL, BAD_CAST XML_TAG_CONVERSATION.c_str());
334         xmlAddChild(root_node, node);
335         xmlNewProp(node, BAD_CAST XML_ATT_ID.c_str(), BAD_CAST iter->convoId_.c_str());
336 
337         if (CheckParameterMask(CONVO_LISTING_NAME_MASK, iter->name_, paraMask, true)) {
338             xmlNewProp(node, BAD_CAST XML_ATT_NAME.c_str(), BAD_CAST iter->name_.c_str());
339         }
340         if (CheckParameterMask(CONVO_LAST_ACTIVITY_MASK, iter->lastActivity_, paraMask, true)) {
341             xmlNewProp(node, BAD_CAST XML_ATT_LAST_ACTIVITY.c_str(), BAD_CAST iter->lastActivity_.c_str());
342         }
343         std::string read = (iter->readStatus_ == 1) ? "yes" : "no";
344         if (CheckParameterMask(CONVO_READ_STATUS_MASK, read, paraMask, true)) {
345             xmlNewProp(node, BAD_CAST XML_ATT_READ.c_str(), BAD_CAST read.c_str());
346         }
347         if (CheckParameterMask(CONVO_VERSION_COUNTER_MASK, iter->versionCounter_, paraMask, true)) {
348             xmlNewProp(node, BAD_CAST XML_ATT_VERSION_COUNTER.c_str(), BAD_CAST iter->versionCounter_.c_str());
349         }
350         if (CheckParameterMask(CONVO_SUMMARY_MASK, iter->summary_, paraMask)) {
351             xmlNewProp(node, BAD_CAST XML_ATT_SUMMARY.c_str(), BAD_CAST iter->summary_.c_str());
352         }
353         if (CheckParameterMask(PARTI_MASK, "Participants", paraMask) || paraMask == -1) {
354             ParticipantsToXml(node, iter->contacts_, paraMask);
355         }
356     }
357     xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
358     oss << xmlbuff;
359     xmlFree(xmlbuff);
360     xmlFreeDoc(doc);
361 
362     return oss.str();
363 }
364 
AddWhereSql(const MapMseParams & appParameter,std::string & sql)365 void MapMseResource::AddWhereSql(const MapMseParams &appParameter, std::string &sql)
366 {
367     if (appParameter.filterOriginator_ != "" && appParameter.filterOriginator_ != "*") {
368         std::string recpt = appParameter.filterOriginator_;
369         sql.append(" and m.handle in ( select v.handle from Vcard v where v.is_originator = 1");
370         if (recpt.find('*') == std::string::npos) {
371             sql.append(" and (v.name like '%' || ? || '%' or v.phone_numbers like '%' || ? || '%' or v.email_addresses "
372                        "like '%' || ? || '%'))");
373         } else {
374             std::size_t i = recpt.find('*');
375             std::string left = recpt.substr(0, i);
376             std::string right = recpt.substr(i + 1);
377             if (left != "") {
378                 sql.append(" and (v.name like ? || '%' or v.phone_numbers like ? || '%' or v.email_addresses like "
379                            "? || '%'))");
380             } else if (right != "") {
381                 sql.append(" and (v.name like '%' || ? or v.phone_numbers like '%' || ? or v.email_addresses like "
382                            "'%' || ?))");
383             }
384         }
385     }
386     if (appParameter.filterRecipient_ != "" && appParameter.filterRecipient_ != "*") {
387         std::string recpt = appParameter.filterRecipient_;
388         sql.append(" and m.handle in ( select v2.handle from Vcard v2 where v2.is_originator = 0");
389         if (recpt.find('*') == std::string::npos) {
390             sql.append(
391                 " and (v2.name like '%' || ? || '%' or v2.phone_numbers like '%' || ? || '%' or v2.email_addresses "
392                 "like '%' || ? || '%'))");
393         } else {
394             std::size_t i = recpt.find('*');
395             std::string left = recpt.substr(0, i);
396             std::string right = recpt.substr(i + 1);
397             if (left != "") {
398                 sql.append(" and (v2.name like ? || '%' or v2.phone_numbers like ? || '%' or v2.email_addresses like "
399                            "? || '%'))");
400             } else if (right != "") {
401                 sql.append(" and (v2.name like '%' || ? or v2.phone_numbers like '%' || ? or v2.email_addresses like "
402                            "'%' || ?))");
403             }
404         }
405     }
406     sql.append(" order by m.datetime desc");
407     if (appParameter.maxListCount_ != 0x0) {
408         sql.append(" limit ?");
409         sql.append(" offset ?");
410     }
411 }
412 
GetMsglistSql(const MapMseParams & appParameter,const std::string & folderName)413 std::string MapMseResource::GetMsglistSql(const MapMseParams &appParameter, const std::string &folderName)
414 {
415     std::string sql = "select m.handle,m.subject,m.datetime,m.sender_name,m.sender_addressing,m.replyto_addressing,"
416           "m.recipient_name,m.recipient_addressing,m.type,m.size,m.text,m.reception_status,m.attachment_size,"
417           "m.priority,m.read,m.sent,m.protected,m.delivery_status,m.conversation_id,m.conversation_name,"
418           "m.direction,m.attachment_mime_types from MessageList m where 1 = 1";
419     if (folderName != "") {
420         sql.append(" and m.folder = ?");
421     }
422     if (appParameter.filterMessageHandle_ != "") {
423         sql.append(" and m.handle = ?");
424     }
425     if (appParameter.conversationId_ != "") {
426         sql.append(" and m.conversation_id = ?");
427     }
428     if (appParameter.filterMessageType_ != nullptr) {
429         int count = GetMsgTypeParam(*appParameter.filterMessageType_).size();
430         for (int i = 0; i < count; i++) {
431             if (i == 0) {
432                 sql.append(" and m.type not in (");
433             }
434             sql.append(" ?");
435             if (i == count - 1) {
436                 sql.append(" )");
437             } else {
438                 sql.append(" ,");
439             }
440         }
441     }
442     if (appParameter.filterPeriodBegin_ != "") {
443         sql.append(" and ? <= m.datetime");
444     }
445     if (appParameter.filterPeriodEnd_ != "") {
446         sql.append(" and m.datetime <= ?");
447     }
448     if (appParameter.filterReadStatus_ != nullptr) {
449         if (*appParameter.filterReadStatus_ == 1 || *appParameter.filterReadStatus_ == 0x2) {
450             sql.append(" and m.read = ?");
451         }
452     }
453     if (appParameter.filterPriority_ != nullptr) {
454         if (*appParameter.filterPriority_ == 1 || *appParameter.filterPriority_ == 0x2) {
455             sql.append(" and m.priority = ?");
456         }
457     }
458     AddWhereSql(appParameter, sql);
459     return sql;
460 }
461 
SetContacts(IDataStatement & ids,const MapMseParams & appParameter,int & index)462 void MapMseResource::SetContacts(IDataStatement &ids, const MapMseParams &appParameter, int &index)
463 {
464     if (appParameter.filterOriginator_ != "") {
465         if (appParameter.filterOriginator_.find('*') == std::string::npos) {
466             ids.SetParamString(index++, appParameter.filterOriginator_);
467             ids.SetParamString(index++, appParameter.filterOriginator_);
468             ids.SetParamString(index++, appParameter.filterOriginator_);
469         } else {
470             std::string recpt = appParameter.filterOriginator_;
471             std::size_t i = recpt.find('*');
472             std::string left = recpt.substr(0, i);
473             std::string right = recpt.substr(i + 1);
474             if (left != "") {
475                 ids.SetParamString(index++, left);
476                 ids.SetParamString(index++, left);
477                 ids.SetParamString(index++, left);
478             } else if (right != "") {
479                 ids.SetParamString(index++, right);
480                 ids.SetParamString(index++, right);
481                 ids.SetParamString(index++, right);
482             }
483         }
484     }
485     if (appParameter.filterRecipient_ != "") {
486         if (appParameter.filterRecipient_.find('*') == std::string::npos) {
487             ids.SetParamString(index++, appParameter.filterRecipient_);
488             ids.SetParamString(index++, appParameter.filterRecipient_);
489             ids.SetParamString(index++, appParameter.filterRecipient_);
490         } else {
491             std::string recpt = appParameter.filterRecipient_;
492             std::size_t i = recpt.find('*');
493             std::string left = recpt.substr(0, i);
494             std::string right = recpt.substr(i + 1);
495             if (left != "") {
496                 ids.SetParamString(index++, left);
497                 ids.SetParamString(index++, left);
498                 ids.SetParamString(index++, left);
499             } else if (right != "") {
500                 ids.SetParamString(index++, right);
501                 ids.SetParamString(index++, right);
502                 ids.SetParamString(index++, right);
503             }
504         }
505     }
506 }
507 
GetMsgTypeParam(uint8_t mask)508 std::vector<int> MapMseResource::GetMsgTypeParam(uint8_t mask)
509 {
510     std::vector<int> ret {};
511     if (mask == 0) {
512         return ret;
513     }
514     if ((MASK_MSG_SMS_GSM & mask) > 0) {
515         ret.push_back(0x2);
516     }
517     if ((MASK_MSG_SMS_CDMA & mask) > 0) {
518         ret.push_back(0x3);
519     }
520     if ((MASK_MSG_MMS & mask) > 0) {
521         ret.push_back(0x4);
522     }
523     if ((MASK_MSG_IM & mask) > 0) {
524         ret.push_back(0x5);
525     }
526     if ((MASK_MSG_EMAIL & mask) > 0) {
527         ret.push_back(0x1);
528     }
529     return ret;
530 }
531 
SetMsglistParam(IDataStatement & ids,const MapMseParams & appParameter,const std::string & folderName)532 void MapMseResource::SetMsglistParam(
533     IDataStatement &ids, const MapMseParams &appParameter, const std::string &folderName)
534 {
535     int index = 1;
536     ids.ClearParams();
537     if (folderName != "") {
538         ids.SetParamString(index++, folderName);
539     }
540     if (appParameter.filterMessageHandle_ != "") {
541         ids.SetParamString(index++, appParameter.filterMessageHandle_);
542     }
543     if (appParameter.conversationId_ != "") {
544         ids.SetParamString(index++, appParameter.conversationId_);
545     }
546     if (appParameter.filterMessageType_ != nullptr) {
547         for (auto &iter : GetMsgTypeParam(*appParameter.filterMessageType_)) {
548             ids.SetParamInt(index++, iter);
549         }
550     }
551     if (appParameter.filterPeriodBegin_ != "") {
552         ids.SetParamString(index++, appParameter.filterPeriodBegin_);
553     }
554     if (appParameter.filterPeriodEnd_ != "") {
555         ids.SetParamString(index++, appParameter.filterPeriodEnd_);
556     }
557     if (appParameter.filterReadStatus_ != nullptr) {
558         if (*appParameter.filterReadStatus_ == 0x1) {
559             ids.SetParamInt(index++, 0);
560         } else if (*appParameter.filterReadStatus_ == 0x2) {
561             ids.SetParamInt(index++, 1);
562         }
563     }
564     if (appParameter.filterPriority_ != nullptr) {
565         if (*appParameter.filterPriority_ == 0x1) {
566             ids.SetParamInt(index++, 1);
567         } else if (*appParameter.filterPriority_ == 0x2) {
568             ids.SetParamInt(index++, 0);
569         }
570     }
571     SetContacts(ids, appParameter, index);
572     if (appParameter.maxListCount_ != 0x0) {
573         ids.SetParamInt(index++, appParameter.maxListCount_);
574         ids.SetParamInt(index++, appParameter.listStartOffSet_);
575     }
576 }
577 
GetMessageListContent(const std::string & folderName,const MapMseParams & appParameter)578 std::vector<std::unique_ptr<MseMessageElement>> MapMseResource::GetMessageListContent(
579     const std::string &folderName, const MapMseParams &appParameter)
580 {
581     std::vector<std::unique_ptr<MseMessageElement>> messageList;
582     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE);
583     if (!dataProvider) {
584         return messageList;
585     }
586     std::string sql = GetMsglistSql(appParameter, folderName);
587     auto stmt = dataProvider->CreateStatement(sql);
588     if (!stmt) {
589         return messageList;
590     }
591     SetMsglistParam(*stmt, appParameter, folderName);
592     auto dataResult = stmt->Query();
593     while (dataResult->Next()) {
594         auto messageEle = std::make_unique<MseMessageElement>();
595         int index = 0;
596         messageEle->handle_ = dataResult->GetString(index++);
597         std::string subject = dataResult->GetString(index++);
598         if (appParameter.subjectLength_ != nullptr) {
599             std::size_t end = *appParameter.subjectLength_;
600             subject = subject.substr(0, end);
601         }
602         messageEle->subject_ = subject;
603         messageEle->dateTime_ = dataResult->GetString(index++);
604         messageEle->senderName_ = dataResult->GetString(index++);
605         messageEle->senderAddressing_ = dataResult->GetString(index++);
606         messageEle->replytoAddressing_ = dataResult->GetString(index++);
607         messageEle->recipientName_ = dataResult->GetString(index++);
608         messageEle->recipientAddressing_ = dataResult->GetString(index++);
609         messageEle->type = MessageType(dataResult->GetInt(index++));
610         messageEle->size_ = dataResult->GetInt(index++);
611         messageEle->text_ = (dataResult->GetInt(index++) == 1) ? "yes" : "no";
612         messageEle->receptionStatus_ = dataResult->GetString(index++);
613         messageEle->attachmentSize_ = dataResult->GetInt(index++);
614         messageEle->priority_ = (dataResult->GetInt(index++) == 1) ? "yes" : "no";
615         messageEle->read_ = (dataResult->GetInt(index++) == 1) ? true : false;
616         messageEle->sent_ = (dataResult->GetInt(index++) == 1) ? "yes" : "no";
617         messageEle->protected_ = (dataResult->GetInt(index++) == 1) ? "yes" : "no";
618         messageEle->deliveryStatus_ = dataResult->GetString(index++);  // Messages-Listing Format Version 1.1
619         messageEle->conversationId_ = dataResult->GetString(index++);
620         messageEle->conversationName_ = dataResult->GetString(index++);
621         messageEle->direction_ = dataResult->GetString(index++);
622         messageEle->attachmentMimeTypes_ = dataResult->GetString(index++);
623         messageList.push_back(std::move(messageEle));
624     }
625     return messageList;
626 }
627 
GetBodyXml(const std::string & folderName,const MapMseParams & appParameter,const std::string & version,uint16_t & listSize,uint8_t & unRead)628 std::string MapMseResource::GetBodyXml(const std::string &folderName, const MapMseParams &appParameter,
629     const std::string &version, uint16_t &listSize, uint8_t &unRead)
630 {
631     auto messageList = GetMessageListContent(folderName, appParameter);
632     listSize = messageList.size();
633     if (listSize == 0) {
634         return "";
635     }
636     return GetPrivateBodyXml(messageList, version, unRead, appParameter.parameterMask_);
637 }
638 
AddVer10Node(xmlNodePtr & node,MseMessageElement & msg,uint8_t & unRead,long paraMask)639 void MapMseResource::AddVer10Node(xmlNodePtr &node, MseMessageElement &msg, uint8_t &unRead, long paraMask)
640 {
641     xmlNewProp(node, BAD_CAST "handle", BAD_CAST msg.handle_.c_str());
642     if (CheckParameterMask(SUBJECT_MASK, msg.subject_, paraMask, true))
643         xmlNewProp(node, BAD_CAST "subject", BAD_CAST msg.subject_.c_str());
644     if (CheckParameterMask(DATETIME_MASK, msg.dateTime_, paraMask, true))
645         xmlNewProp(node, BAD_CAST "datetime", BAD_CAST msg.dateTime_.c_str());
646     if (CheckParameterMask(SENDER_NAME_MASK, msg.senderName_, paraMask))
647         xmlNewProp(node, BAD_CAST "sender_name", BAD_CAST msg.senderName_.c_str());
648     if (CheckParameterMask(SENDER_ADDRESSING_MASK, msg.senderAddressing_, paraMask))
649         xmlNewProp(node, BAD_CAST "sender_addressing", BAD_CAST msg.senderAddressing_.c_str());
650     if (CheckParameterMask(REPLYTO_ADDRESSING, msg.replytoAddressing_, paraMask))
651         xmlNewProp(node, BAD_CAST "replyto_addressing", BAD_CAST msg.replytoAddressing_.c_str());
652     if (CheckParameterMask(RECIPIENT_NAME_MASK, msg.recipientName_, paraMask))
653         xmlNewProp(node, BAD_CAST "recipient_name", BAD_CAST msg.recipientName_.c_str());
654     if (CheckParameterMask(RECIPIENT_ADDRESSING_MASK, msg.recipientAddressing_, paraMask, true))
655         xmlNewProp(node, BAD_CAST "recipient_addressing", BAD_CAST msg.recipientAddressing_.c_str());
656     if (static_cast<int>(msg.type) > 0) {
657         if (CheckParameterMask(TYPE_MASK, std::to_string(static_cast<int>(msg.type)), paraMask, true))
658             xmlNewProp(node, BAD_CAST "type", BAD_CAST ChangeType(msg.type).c_str());
659     }
660     if (CheckParameterMask(SIZE_MASK, std::to_string(msg.size_), paraMask, true))
661         xmlNewProp(node, BAD_CAST "size", BAD_CAST std::to_string(msg.size_).c_str());
662     if (CheckParameterMask(TEXT_MASK, msg.text_, paraMask))
663         xmlNewProp(node, BAD_CAST "text", BAD_CAST msg.text_.c_str());
664     if (CheckParameterMask(RECEPTION_STATUS_MASK, msg.receptionStatus_, paraMask, true))
665         xmlNewProp(node, BAD_CAST "reception_status", BAD_CAST msg.receptionStatus_.c_str());
666     if (CheckParameterMask(ATTACHMENT_SIZE_MASK, std::to_string(msg.attachmentSize_), paraMask, true))
667         xmlNewProp(node, BAD_CAST "attachment_size", BAD_CAST std::to_string(msg.attachmentSize_).c_str());
668     if (CheckParameterMask(PRIORITY_MASK, msg.priority_, paraMask))
669         xmlNewProp(node, BAD_CAST "priority", BAD_CAST msg.priority_.c_str());
670     std::string read = msg.read_ ? "yes" : "no";
671     unRead = msg.read_ ? 0 : 1;
672     if (CheckParameterMask(READ_MASK, read, paraMask))
673         xmlNewProp(node, BAD_CAST "read", BAD_CAST read.c_str());
674     if (CheckParameterMask(SENT_MASK, msg.sent_, paraMask))
675         xmlNewProp(node, BAD_CAST "sent", BAD_CAST msg.sent_.c_str());
676     if (CheckParameterMask(PROTECTED_MASK, msg.protected_, paraMask))
677         xmlNewProp(node, BAD_CAST "protected", BAD_CAST msg.protected_.c_str());
678 }
679 
ChangeType(MessageType type)680 std::string MapMseResource::ChangeType(MessageType type)
681 {
682     if (type == MessageType::EMAIL) {
683         return "EMAIL";
684     } else if (type == MessageType::IM) {
685         return "IM";
686     } else if (type == MessageType::MMS) {
687         return "MMS";
688     } else if (type == MessageType::SMS_GSM) {
689         return "SMS_GSM";
690     } else if (type == MessageType::SMS_CDMA) {
691         return "SMS_CDMA";
692     } else {
693         return "NONE";
694     }
695 }
696 
GetPrivateBodyXml(std::vector<std::unique_ptr<MseMessageElement>> & messageList,const std::string & version,uint8_t & unRead,long paraMask)697 std::string MapMseResource::GetPrivateBodyXml(std::vector<std::unique_ptr<MseMessageElement>> &messageList,
698     const std::string &version, uint8_t &unRead, long paraMask)
699 {
700     xmlChar *xmlbuff;
701     int buffersize;
702     std::ostringstream oss;
703 
704     xmlDocPtr doc = xmlNewDoc(BAD_CAST MAP_V10.c_str());
705     xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST "MAP-msg-listing");
706     xmlDocSetRootElement(doc, root_node);
707     xmlNewProp(root_node, BAD_CAST "version", BAD_CAST version.c_str());
708 
709     for (auto &iter : messageList) {
710         xmlNodePtr node = xmlNewNode(NULL, BAD_CAST"msg");
711         xmlAddChild(root_node, node);
712 
713         AddVer10Node(node, *iter, unRead, paraMask);
714         if (MAP_V11 == version) {
715             if (CheckParameterMask(DELIVERY_STATUS_MASK, iter->deliveryStatus_, paraMask))
716                 xmlNewProp(node, BAD_CAST"delivery_status", BAD_CAST iter->deliveryStatus_.c_str());
717             if (CheckParameterMask(CONVERSATION_ID_MASK, iter->conversationId_, paraMask, true))
718                 xmlNewProp(node, BAD_CAST"conversation_id", BAD_CAST iter->conversationId_.c_str());
719             if (CheckParameterMask(CONVERSATION_NAME_MASK, iter->conversationName_, paraMask))
720                 xmlNewProp(node, BAD_CAST"conversation_name", BAD_CAST iter->conversationName_.c_str());
721             if (CheckParameterMask(DIRECTION_MASK, iter->direction_, paraMask, true))
722                 xmlNewProp(node, BAD_CAST"direction", BAD_CAST iter->direction_.c_str());
723             if (CheckParameterMask(ATTACHMENT_NIME_MASK, iter->attachmentMimeTypes_, paraMask))
724                 xmlNewProp(node, BAD_CAST"attachment_mime_types", BAD_CAST iter->attachmentMimeTypes_.c_str());
725         }
726     }
727     xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
728     oss << xmlbuff;
729     xmlFree(xmlbuff);
730     xmlFreeDoc(doc);
731 
732     return oss.str();
733 }
734 
CheckParameterMask(uint32_t mask,std::string para,long paraMask,bool required)735 bool MapMseResource::CheckParameterMask(uint32_t mask, std::string para, long paraMask, bool required)
736 {
737     if (para.size() > 0) {
738         if (required) {
739             return true;
740         }
741         if (paraMask != -1) {
742             if (paraMask == 0 || ((static_cast<uint32_t>(paraMask) & mask) > 0)) {
743                 return true;
744             }
745         }
746     }
747     return false;
748 }
749 
GetListingSize(const std::string & folderName,const MapMseParams & appParameter,uint16_t & listSize,uint8_t & unRead)750 void MapMseResource::GetListingSize(
751     const std::string &folderName, const MapMseParams &appParameter, uint16_t &listSize, uint8_t &unRead)
752 {
753     auto messagesList = GetMessageListContent(folderName, appParameter);
754     listSize = messagesList.size();
755     bool isExist = std::any_of(messagesList.begin(), messagesList.end(),
756         [](const std::unique_ptr<bluetooth::MseMessageElement>& item) {return !item->read_;});
757     if (isExist) {
758         unRead = 1;
759     }
760 }
761 
GetMessage(const std::string handle,const MapMseParams & appParameter,const std::string & version)762 std::string MapMseResource::GetMessage(
763     const std::string handle, const MapMseParams &appParameter, const std::string &version)
764 {
765     MapMseBmsg data;
766     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE);
767     if (!dataProvider) {
768         return "";
769     }
770     std::string sql = "select body, status, type, folder_path, extended_data, part_id, encoding, "
771                       "conent_charset, language, content_length from Message where handle = ?";
772     auto stmt = dataProvider->CreateStatement(sql);
773     if (!stmt) {
774         return "";
775     }
776     stmt->SetParamString(1, handle);
777     auto dataResult = stmt->Query();
778     while (dataResult->Next()) {
779         int index = 0;
780         data.SetMsgBody(dataResult->GetString(index++));
781         data.SetVersion(version);
782         data.SetStatus(dataResult->GetString(index++));
783         data.SetMsgTypeName(dataResult->GetString(index++));
784         data.SetFolder(dataResult->GetString(index++));
785         data.SetExtendedData(dataResult->GetString(index++));
786         data.SetPartId(std::atoi(dataResult->GetString(index++).data()));
787         data.SetEncoding(dataResult->GetString(index++));
788         data.SetCharset(dataResult->GetString(index++));
789         data.SetLanguage(dataResult->GetString(index++));
790         data.SetBmsgLength(std::atoi(dataResult->GetString(index++).data()));
791         data.SetOriginators(GetVCardData(dataProvider, handle, 1));
792         data.SetRecipients(GetVCardData(dataProvider, handle));
793     }
794     return data.ToBmessageString();
795 }
796 
GetVCardData(std::unique_ptr<DataAccess> & dataAccess,const std::string handle,const int isOriginator)797 std::vector<MapMseVcard> MapMseResource::GetVCardData(
798     std::unique_ptr<DataAccess> &dataAccess, const std::string handle, const int isOriginator)
799 {
800     std::vector<MapMseVcard> result;
801     std::string sql = "select version, name, formatted_name, phone_numbers, email_addresses, x_bt_uid, "
802                       "x_bt_ucis, env_level from Vcard where handle = ? and is_originator = ?";
803     auto stmt = dataAccess->CreateStatement(sql);
804     if (!stmt) {
805         return result;
806     }
807     stmt->SetParamString(1, handle);
808     stmt->SetParamInt(0x2, isOriginator);
809     auto dataResult = stmt->Query();
810     while (dataResult->Next()) {
811         int index = 0;
812         MseVcard3 vcard3;
813         vcard3.version_ = dataResult->GetString(index++);
814         vcard3.name_ = dataResult->GetString(index++);
815         vcard3.formattedName_ = dataResult->GetString(index++);
816         vcard3.phoneNumbers_.push_back(dataResult->GetString(index++));
817         vcard3.emailAddresses_.push_back(dataResult->GetString(index++));
818         vcard3.btUids_.push_back(dataResult->GetString(index++));
819         vcard3.btUcis_.push_back(dataResult->GetString(index++));
820         vcard3.envLevel_ = dataResult->GetInt(index++);
821         if (vcard3.version_ != "3.0") {
822             vcard3.version_ = "2.1";
823         }
824         MapMseVcard vcd(vcard3);
825         result.push_back(vcd);
826     }
827     return result;
828 }
829 
SetNotificationRegistration(const RawAddress & remoteAddr,const int status)830 void MapMseResource::SetNotificationRegistration(const RawAddress &remoteAddr, const int status)
831 {
832     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
833 
834     if (NotificationStatus(status) == NotificationStatus::ON) {
835         mnsClient_->Connect(remoteAddr, masId_);
836     } else {
837         mnsClient_->DisConnect(remoteAddr, masId_);
838     }
839 }
840 
SetNotificationFilter(const RawAddress & remoteAddr,uint32_t filter)841 void MapMseResource::SetNotificationFilter(const RawAddress &remoteAddr, uint32_t filter)
842 {
843     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
844     MSE_LOG_INFO("Notification Filter value : %u", filter);
845     std::string addr = remoteAddr.GetAddress();
846     eventFilterMaskMap_[addr] = filter;
847 }
848 
SetRemoteFeatureMask(uint32_t features)849 void MapMseResource::SetRemoteFeatureMask(uint32_t features)
850 {
851     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
852     remoteFeatures_ = features;
853 }
854 
SendEventReport(const std::string & addr,const std::string & event,const std::string & type)855 void MapMseResource::SendEventReport(const std::string &addr, const std::string &event, const std::string &type)
856 {
857     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
858 
859     bool has = false;
860     if (type == TYPE_NEW) {
861         has = CheckEventFilterMask(addr, FILTER_MASK_NEW_MESSAGE);
862     } else if (type == TYPE_DELETE) {
863         has = CheckEventFilterMask(addr, FILTER_MASK_MESSAGE_DELETED);
864     } else if (type == TYPE_SHIFT) {
865         has = CheckEventFilterMask(addr, FILTER_MASK_MESSAGE_SHIFT);
866     } else if (type == TYPE_SENDING_SUCCESS) {
867         has = CheckEventFilterMask(addr, FILTER_MASK_SENDING_SUCCESS);
868     } else if (type == TYPE_SENDING_FAILURE) {
869         has = CheckEventFilterMask(addr, FILTER_MASK_SENDING_FAILURE);
870     } else if (type == TYPE_DELIVERY_SUCCESS) {
871         has = CheckEventFilterMask(addr, FILTER_MASK_DELIVERY_SUCCESS);
872     } else if (type == TYPE_DELIVERY_FAILURE) {
873         has = CheckEventFilterMask(addr, FILTER_MASK_DELIVERY_FAILURE);
874     } else if (type == TYPE_MEMORY_FULL) {
875         has = CheckEventFilterMask(addr, FILTER_MASK_MEMORY_FULL);
876     } else if (type == TYPE_MEMORY_AVAILABLE) {
877         has = CheckEventFilterMask(addr, FILTER_MASK_MEMORY_AVAILABLE);
878     } else if (type == TYPE_READ_STATUS) {
879         has = CheckEventFilterMask(addr, FILTER_MASK_READ_STATUS_CHANGED);
880     } else if (type == TYPE_CONVERSATION) {
881         has = CheckEventFilterMask(addr, FILTER_MASK_CONVERSATION_CHANGED);
882     } else if (type == TYPE_PRESENCE) {
883         has = CheckEventFilterMask(addr, FILTER_MASK_PARTICIPANT_PRESENCE_CHANGED);
884     } else if (type == TYPE_CHAT_STATE) {
885         has = CheckEventFilterMask(addr, FILTER_MASK_PARTICIPANT_CHATSTATE_CHANGED);
886     } else if (type == TYPE_EXTENDED_DATA) {
887         has = CheckEventFilterMask(addr, FILTER_MASK_EXTENDED_DATA_CHANGED);
888     } else if (type == TYPE_REMOVED) {
889         has = CheckEventFilterMask(addr, FILTER_MASK_MESSAGE_REMOVED);
890     }
891     if (!has) {
892         return;
893     }
894     MSE_LOG_INFO("Event body: %{public}s ", event.c_str());
895     mnsClient_->SendEvent(RawAddress(addr), event, event.size(), masId_);
896 }
897 
CheckEventFilterMask(const std::string & addr,const uint32_t bit)898 bool MapMseResource::CheckEventFilterMask(const std::string &addr, const uint32_t bit)
899 {
900     bool ret = false;
901     if (eventFilterMaskMap_.find(addr) == eventFilterMaskMap_.end()) {
902         MSE_LOG_INFO("set notification filter function is not used, then all event will be sent to the MCE.");
903         ret = true;
904     } else {
905         if ((eventFilterMaskMap_[addr] & bit) > 0) {
906             ret = true;
907         }
908     }
909     return ret;
910 }
911 
EventObserver(MapMseResource & observer)912 MapMseResource::EventObserver::EventObserver(MapMseResource &observer) : observer_(observer)
913 {
914     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
915 }
916 
OnNotifyingEvent(const std::string & addr,stub::EventInfo & event)917 void MapMseResource::EventObserver::OnNotifyingEvent(const std::string &addr, stub::EventInfo &event)
918 {
919     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
920 
921     observer_.SendEvent(addr, event);
922 }
923 
OnUpdateDbIdCounter(void)924 void MapMseResource::EventObserver::OnUpdateDbIdCounter(void)
925 {
926     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
927 
928     observer_.UpdateDbIdCounter();
929 }
930 
OnUpdateVerIdCounter(void)931 void MapMseResource::EventObserver::OnUpdateVerIdCounter(void)
932 {
933     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
934 
935     observer_.UpdateVerIdCounter();
936 }
937 
OnUpdateConvoVerIdCounter(void)938 void MapMseResource::EventObserver::OnUpdateConvoVerIdCounter(void)
939 {
940     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
941 
942     observer_.UpdateConvoVerIdCounter();
943 }
944 
UpdateDbIdCounter(void)945 void MapMseResource::UpdateDbIdCounter(void)
946 {
947     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
948 
949     instance_.UpdateDatabaseIdentifier();
950 }
951 
UpdateVerIdCounter(void)952 void MapMseResource::UpdateVerIdCounter(void)
953 {
954     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
955 
956     instance_.UpdateFolderVersionCounter();
957 }
958 
UpdateConvoVerIdCounter(void)959 void MapMseResource::UpdateConvoVerIdCounter(void)
960 {
961     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
962 
963     instance_.UpdateConversationVersionCounter();
964 }
965 
SendEvent(const std::string & addr,const stub::EventInfo & event)966 void MapMseResource::SendEvent(const std::string &addr, const stub::EventInfo &event)
967 {
968     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
969 
970     uint32_t feature = GetRemoteFeatureMask(addr);
971     if ((MAP_FEATURE_EVENT_REPORT_V12_BIT & feature) != 0) {
972         reportVersion_ = MAP_EVENT_REPORT_V12;
973     } else if ((MAP_FEATURE_EXTENDED_EVENT_REPORT_11_BIT & feature) != 0) {
974         reportVersion_ = MAP_EVENT_REPORT_V11;
975     }
976     dispatcher_.PostTask(std::bind(&MapMseResource::SendEventNative, this, addr, event));
977 }
978 
SendEventNative(const std::string & addr,const stub::EventInfo & event)979 void MapMseResource::SendEventNative(const std::string &addr, const stub::EventInfo &event)
980 {
981     switch (event.eventType) {
982         case stub::EventType::NEW_MESSAGE:
983             SendNewMessageEvent(addr, event);
984             break;
985         case stub::EventType::MESSAGE_DELETED:
986             SendMessageEvent(TYPE_DELETE, addr, event);
987             break;
988         case stub::EventType::MESSAGE_REMOVED:
989             SendMessageRemovedEvent(addr, event);
990             break;
991         case stub::EventType::MESSAGE_SHIFT:
992             SendMessageShiftEvent(addr, event);
993             break;
994         case stub::EventType::DELIVERY_SUCCESS:
995             SendMessageEvent(TYPE_DELIVERY_SUCCESS, addr, event);
996             break;
997         case stub::EventType::SENDING_SUCCESS:
998             SendMessageEvent(TYPE_SENDING_SUCCESS, addr, event);
999             break;
1000         case stub::EventType::SENDING_FAILURE:
1001             SendingFailureEvent(addr, event);
1002             break;
1003         case stub::EventType::DELIVERY_FAILURE:
1004             SendMessageEvent(TYPE_DELIVERY_FAILURE, addr, event);
1005             break;
1006         case stub::EventType::READ_STATUS_CHANGED:
1007             SendReadStatusChangedEvent(addr, event);
1008             break;
1009         case stub::EventType::CONVERSATION_CHANGED:
1010             SendConversationChangedEvent(addr, event);
1011             break;
1012         case stub::EventType::PARTICIPANT_PRESENCE_CHANGED:
1013             SendParticipantPresenceChangedEvent(addr, event);
1014             break;
1015         case stub::EventType::PARTICIPANT_CHAT_STATE_CHANGED:
1016             SendParticipantChatStateChangedEvent(addr, event);
1017             break;
1018         case stub::EventType::MESSAGE_EXTENDED_DATA_CHANGED:
1019             SendMessageExtendedDataChangedEvent(addr, event);
1020             break;
1021         case stub::EventType::MEMORY_FULL:
1022             SendMemoryFullEvent(addr, event);
1023             break;
1024         case stub::EventType::MEMORY_AVAILABLE:
1025             SendMemoryAvailableEvent(addr, event);
1026             break;
1027         default:
1028             break;
1029     }
1030 }
1031 
GetRemoteFeatureMask(const std::string & addr)1032 uint32_t MapMseResource::GetRemoteFeatureMask(const std::string &addr)
1033 {
1034     MSE_LOG_INFO("remoteFeatures_: %{public}d ", remoteFeatures_);
1035 
1036     return remoteFeatures_ & mnsClient_->GetRemoteFeatures(addr);
1037 }
1038 
SendNewMessageEvent(const std::string & addr,const stub::EventInfo & event)1039 void MapMseResource::SendNewMessageEvent(const std::string &addr, const stub::EventInfo &event)
1040 {
1041     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1042 
1043     std::string body;
1044     if (reportVersion_ == MAP_EVENT_REPORT_V10) {
1045         MapMseEvent report(TYPE_NEW, event.handle, event.folder, MessageType(event.msgType));
1046         body = report.ToReportXml();
1047     } else if (reportVersion_ == MAP_EVENT_REPORT_V11) {
1048         MseEventType11 eventTmp;
1049         eventTmp.eventType_ = TYPE_NEW;
1050         eventTmp.handle_ = event.handle;
1051         eventTmp.folder_ = event.folder;
1052         eventTmp.msgType_ = MessageType(event.msgType);
1053         eventTmp.datetime_ = event.datetime;
1054         eventTmp.subject_ = event.subject;
1055         eventTmp.senderName_ = event.senderName;
1056         eventTmp.priority_ = event.priority;
1057         MapMseEvent report(eventTmp);
1058         body = report.ToReportXml();
1059     } else {
1060         MseEventType122 eventTmp;
1061         eventTmp.eventType_ = TYPE_NEW;
1062         eventTmp.handle_ = event.handle;
1063         eventTmp.folder_ = event.folder;
1064         eventTmp.msgType_ = MessageType(event.msgType);
1065         eventTmp.datetime_ = event.datetime;
1066         eventTmp.subject_ = event.subject;
1067         eventTmp.senderName_ = event.senderName;
1068         eventTmp.priority_ = event.priority;
1069         eventTmp.conversationID_ = event.conversationID;
1070         eventTmp.conversationName_ = event.conversationName;
1071         eventTmp.participantUci_ = event.participantUci;
1072         eventTmp.contactUid_ = event.contactUid;
1073         MapMseEvent report(eventTmp);
1074         report.SetReadStatus(event.readStatus);
1075         body = report.ToReportXml();
1076     }
1077     SendEventReport(addr, body, TYPE_NEW);
1078 }
1079 
SendMessageEvent(const std::string type,const std::string & addr,const stub::EventInfo & event)1080 void MapMseResource::SendMessageEvent(const std::string type, const std::string &addr, const stub::EventInfo &event)
1081 {
1082     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1083 
1084     std::string body;
1085     if (reportVersion_ == MAP_EVENT_REPORT_V10 || reportVersion_ == MAP_EVENT_REPORT_V11) {
1086         MapMseEvent report(type, event.handle, event.folder, MessageType(event.msgType));
1087         body = report.ToReportXml();
1088     } else {
1089         MseEventType121 eventTmp;
1090         eventTmp.eventType_ = type;
1091         eventTmp.handle_ = event.handle;
1092         eventTmp.folder_ = event.folder;
1093         eventTmp.msgType_ = MessageType(event.msgType);
1094         eventTmp.datetime_ = "";
1095         eventTmp.subject_ = "";
1096         eventTmp.senderName_ = "";
1097         eventTmp.priority_ = -1;
1098         eventTmp.conversationID_ = event.conversationID;
1099         eventTmp.conversationName_ = event.conversationName;
1100         MapMseEvent report(eventTmp);
1101         body = report.ToReportXml();
1102     }
1103     SendEventReport(addr, body, type);
1104 }
1105 
SendMessageShiftEvent(const std::string & addr,const stub::EventInfo & event)1106 void MapMseResource::SendMessageShiftEvent(const std::string &addr, const stub::EventInfo &event)
1107 {
1108     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1109 
1110     std::string body;
1111     if (reportVersion_ == MAP_EVENT_REPORT_V10 || reportVersion_ == MAP_EVENT_REPORT_V11) {
1112         MapMseEvent report(TYPE_SHIFT, event.handle, event.folder, event.oldFolder, MessageType(event.msgType));
1113         body = report.ToReportXml();
1114     } else {
1115         MseEventType121 eventTmp;
1116         eventTmp.eventType_ = TYPE_SHIFT;
1117         eventTmp.handle_ = event.handle;
1118         eventTmp.folder_ = event.folder;
1119         eventTmp.msgType_ = MessageType(event.msgType);
1120         eventTmp.datetime_ = "";
1121         eventTmp.subject_ = "";
1122         eventTmp.senderName_ = "";
1123         eventTmp.priority_ = -1;
1124         eventTmp.conversationID_ = event.conversationID;
1125         eventTmp.conversationName_ = event.conversationName;
1126         MapMseEvent report(eventTmp);
1127         body = report.ToReportXml();
1128     }
1129     SendEventReport(addr, body, TYPE_SHIFT);
1130 }
1131 
SendMessageRemovedEvent(const std::string & addr,const stub::EventInfo & event)1132 void MapMseResource::SendMessageRemovedEvent(const std::string &addr, const stub::EventInfo &event)
1133 {
1134     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1135 
1136     std::string body;
1137     if (reportVersion_ != MAP_EVENT_REPORT_V12) {
1138         MSE_LOG_ERROR("MessageRemoved event is not exist.");
1139         return;
1140     } else {
1141         MseEventType121 eventTmp;
1142         eventTmp.eventType_ = TYPE_REMOVED;
1143         eventTmp.handle_ = event.handle;
1144         eventTmp.folder_ = event.folder;
1145         eventTmp.msgType_ = MessageType(event.msgType);
1146         eventTmp.datetime_ = "";
1147         eventTmp.subject_ = "";
1148         eventTmp.senderName_ = "";
1149         eventTmp.priority_ = -1;
1150         eventTmp.conversationID_ = event.conversationID;
1151         eventTmp.conversationName_ = event.conversationName;
1152         MapMseEvent report(eventTmp);
1153         body = report.ToReportXml();
1154     }
1155     SendEventReport(addr, body, TYPE_REMOVED);
1156 }
1157 
SendingFailureEvent(const std::string & addr,const stub::EventInfo & event)1158 void MapMseResource::SendingFailureEvent(const std::string &addr, const stub::EventInfo &event)
1159 {
1160     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1161 
1162     std::string body;
1163     if (reportVersion_ == MAP_EVENT_REPORT_V10 || reportVersion_ == MAP_EVENT_REPORT_V11) {
1164         MapMseEvent report(TYPE_SENDING_FAILURE, event.handle, event.folder, MessageType(event.msgType));
1165         body = report.ToReportXml();
1166     } else {
1167         MseEventType121 eventTmp;
1168         eventTmp.eventType_ = TYPE_SENDING_FAILURE;
1169         eventTmp.handle_ = event.handle;
1170         eventTmp.folder_ = event.folder;
1171         eventTmp.msgType_ = MessageType(event.msgType);
1172         eventTmp.datetime_ = "";
1173         eventTmp.subject_ = "";
1174         eventTmp.senderName_ = "";
1175         eventTmp.priority_ = -1;
1176         eventTmp.conversationID_ = event.conversationID;
1177         eventTmp.conversationName_ = "";
1178         MapMseEvent report(eventTmp);
1179         body = report.ToReportXml();
1180     }
1181     SendEventReport(addr, body, TYPE_SENDING_FAILURE);
1182 }
1183 
SendReadStatusChangedEvent(const std::string & addr,const stub::EventInfo & event)1184 void MapMseResource::SendReadStatusChangedEvent(const std::string &addr, const stub::EventInfo &event)
1185 {
1186     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1187 
1188     std::string body;
1189     if (reportVersion_ == MAP_EVENT_REPORT_V10) {
1190         MSE_LOG_ERROR("MessageRemoved event is not exist.");
1191         return;
1192     } else if (reportVersion_ == MAP_EVENT_REPORT_V11) {
1193         MapMseEvent report(TYPE_READ_STATUS, event.handle, event.folder, MessageType(event.msgType));
1194         body = report.ToReportXml();
1195     } else {
1196         MseEventType121 eventTmp;
1197         eventTmp.eventType_ = TYPE_READ_STATUS;
1198         eventTmp.handle_ = event.handle;
1199         eventTmp.folder_ = event.folder;
1200         eventTmp.msgType_ = MessageType(event.msgType);
1201         eventTmp.datetime_ = "";
1202         eventTmp.subject_ = "";
1203         eventTmp.senderName_ = "";
1204         eventTmp.priority_ = -1;
1205         eventTmp.conversationID_ = event.conversationID;
1206         eventTmp.conversationName_ = event.conversationName;
1207         MapMseEvent report(eventTmp);
1208         report.SetReadStatus(event.readStatus);
1209         body = report.ToReportXml();
1210     }
1211     SendEventReport(addr, body, TYPE_READ_STATUS);
1212 }
1213 
SendConversationChangedEvent(const std::string & addr,const stub::EventInfo & event)1214 void MapMseResource::SendConversationChangedEvent(const std::string &addr, const stub::EventInfo &event)
1215 {
1216     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1217 
1218     std::string body;
1219     if (reportVersion_ != MAP_EVENT_REPORT_V12) {
1220         MSE_LOG_ERROR("ConversationChanged event is not exist.");
1221         return;
1222     } else {
1223         MseEventType124 eventTmp;
1224         eventTmp.eventType_ = TYPE_CONVERSATION;
1225         eventTmp.senderName_ = "";
1226         eventTmp.conversationID_ = event.conversationID;
1227         eventTmp.conversationName_ = event.conversationName;
1228         eventTmp.presenceState_ = event.presenceAvailability;
1229         eventTmp.presenceStatus_ = event.presenceText;
1230         eventTmp.lastActivity_ = event.lastActivity;
1231         eventTmp.chatState_ = event.chatState;
1232         eventTmp.extendedData_ = event.extendedData;
1233         eventTmp.participantUci_ = event.participantUci;
1234         eventTmp.contactUid_ = event.contactUid;
1235         MapMseEvent report(eventTmp);
1236         body = report.ToReportXml();
1237     }
1238     SendEventReport(addr, body, TYPE_CONVERSATION);
1239 }
1240 
SendParticipantPresenceChangedEvent(const std::string & addr,const stub::EventInfo & event)1241 void MapMseResource::SendParticipantPresenceChangedEvent(const std::string &addr, const stub::EventInfo &event)
1242 {
1243     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1244 
1245     std::string body;
1246     if (reportVersion_ != MAP_EVENT_REPORT_V12) {
1247         MSE_LOG_ERROR("ConversationChanged event is not exist.");
1248         return;
1249     } else {
1250         MseEventType124 eventTmp;
1251         eventTmp.eventType_ = TYPE_PRESENCE;
1252         eventTmp.senderName_ = event.senderName;
1253         eventTmp.conversationID_ = event.conversationID;
1254         eventTmp.conversationName_ = event.conversationName;
1255         eventTmp.presenceState_ = event.presenceAvailability;
1256         eventTmp.presenceStatus_ = event.presenceText;
1257         eventTmp.lastActivity_ = event.lastActivity;
1258         eventTmp.chatState_ = -1;
1259         eventTmp.extendedData_ = "";
1260         eventTmp.participantUci_ = event.participantUci;
1261         eventTmp.contactUid_ = event.contactUid;
1262         MapMseEvent report(eventTmp);
1263         body = report.ToReportXml();
1264     }
1265     SendEventReport(addr, body, TYPE_PRESENCE);
1266 }
1267 
SendParticipantChatStateChangedEvent(const std::string & addr,const stub::EventInfo & event)1268 void MapMseResource::SendParticipantChatStateChangedEvent(const std::string &addr, const stub::EventInfo &event)
1269 {
1270     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1271 
1272     std::string body;
1273     if (reportVersion_ != MAP_EVENT_REPORT_V12) {
1274         MSE_LOG_ERROR("ConversationChanged event is not exist.");
1275         return;
1276     } else {
1277         MseEventType124 eventTmp;
1278         eventTmp.eventType_ = TYPE_CHAT_STATE;
1279         eventTmp.senderName_ = event.senderName;
1280         eventTmp.conversationID_ = event.conversationID;
1281         eventTmp.conversationName_ = event.conversationName;
1282         eventTmp.presenceState_ = -1;
1283         eventTmp.presenceStatus_ = "";
1284         eventTmp.lastActivity_ = event.lastActivity;
1285         eventTmp.chatState_ = event.chatState;
1286         eventTmp.extendedData_ = "";
1287         eventTmp.participantUci_ = event.participantUci;
1288         eventTmp.contactUid_ = event.contactUid;
1289         MapMseEvent report(eventTmp);
1290         body = report.ToReportXml();
1291     }
1292     SendEventReport(addr, body, TYPE_CHAT_STATE);
1293 }
1294 
SendMessageExtendedDataChangedEvent(const std::string & addr,const stub::EventInfo & event)1295 void MapMseResource::SendMessageExtendedDataChangedEvent(const std::string &addr, const stub::EventInfo &event)
1296 {
1297     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1298 
1299     std::string body;
1300     if (reportVersion_ != MAP_EVENT_REPORT_V12) {
1301         MSE_LOG_ERROR("ConversationChanged event is not exist.");
1302         return;
1303     } else {
1304         MseEventType123 eventTmp;
1305         eventTmp.eventType_ = TYPE_EXTENDED_DATA;
1306         eventTmp.handle_ = event.handle;
1307         eventTmp.folder_ = event.folder;
1308         eventTmp.msgType_ = MessageType(event.msgType);
1309         eventTmp.datetime_ = event.senderName;
1310         eventTmp.senderName_ = event.senderName;
1311         eventTmp.conversationID_ = event.conversationID;
1312         eventTmp.conversationName_ = event.conversationName;
1313         eventTmp.extendedData_ = event.extendedData;
1314         eventTmp.participantUci_ = event.participantUci;
1315         eventTmp.contactUid_ = event.contactUid;
1316         MapMseEvent report(eventTmp);
1317         body = report.ToReportXml();
1318     }
1319     SendEventReport(addr, body, TYPE_EXTENDED_DATA);
1320 }
1321 
SendMemoryFullEvent(const std::string & addr,const stub::EventInfo & event)1322 void MapMseResource::SendMemoryFullEvent(const std::string &addr, const stub::EventInfo &event)
1323 {
1324     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1325 
1326     MapMseEvent report(TYPE_MEMORY_FULL, "", "", MessageType::NONE);
1327     std::string body = report.ToReportXml();
1328     SendEventReport(addr, body, TYPE_MEMORY_FULL);
1329 }
1330 
SendMemoryAvailableEvent(const std::string & addr,const stub::EventInfo & event)1331 void MapMseResource::SendMemoryAvailableEvent(const std::string &addr, const stub::EventInfo &event)
1332 {
1333     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1334 
1335     MapMseEvent report(TYPE_MEMORY_AVAILABLE, "", "", MessageType::NONE);
1336     std::string body = report.ToReportXml();
1337     SendEventReport(addr, body, TYPE_MEMORY_AVAILABLE);
1338 }
1339 
SetMessageStatusDeleted(std::string handle,MessageType type,std::string path,uint8_t status)1340 bool MapMseResource::SetMessageStatusDeleted(
1341     std::string handle, MessageType type, std::string path, uint8_t status)
1342 {
1343     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1344 
1345     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1346     if (!dataProvider) {
1347         return false;
1348     }
1349     std::string sql = "update MessageList set folder = ? where handle = ? and folder = ?";
1350     auto stmt = dataProvider->CreateStatement(sql);
1351     if (!stmt) {
1352         return false;
1353     }
1354     stmt->SetParamString(0x1, MAP_MSE_FOLDER_NAME_DELETED);
1355     stmt->SetParamString(0x2, handle);
1356     std::string folderName = MAP_MSE_FOLDER_NAME_INBOX;
1357     if (type == MessageType::EMAIL) {
1358         folderName = path;
1359     }
1360     stmt->SetParamString(0x3, folderName);
1361     auto ret = stmt->Update();
1362     if (ret != 1) {
1363         return false;
1364     }
1365     return true;
1366 }
1367 
SetMessageStatusRead(std::string handle,MessageType type,std::string path,uint8_t status)1368 bool MapMseResource::SetMessageStatusRead(
1369     std::string handle, MessageType type, std::string path, uint8_t status)
1370 {
1371     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1372 
1373     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1374     if (!dataProvider) {
1375         return false;
1376     }
1377     std::string sql = "update MessageList set read = ? where handle = ? and folder = ?";
1378     auto stmt = dataProvider->CreateStatement(sql);
1379     if (!stmt) {
1380         return false;
1381     }
1382     stmt->SetParamInt(0x1, status);
1383     stmt->SetParamString(0x2, handle);
1384     std::string folderName = MAP_MSE_FOLDER_NAME_INBOX;
1385     if (type == MessageType::EMAIL) {
1386         folderName = path;
1387     }
1388     stmt->SetParamString(0x3, folderName);
1389     auto ret = stmt->Update();
1390     if (ret != 1) {
1391         return false;
1392     }
1393     return true;
1394 }
1395 
SetExtendedData(std::string handle,std::string data)1396 bool MapMseResource::SetExtendedData(std::string handle, std::string data)
1397 {
1398     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1399 
1400     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1401     if (!dataProvider) {
1402         return false;
1403     }
1404     std::string sql = "update Message set extended_data = ? where handle = ?";
1405     auto stmt = dataProvider->CreateStatement(sql);
1406     if (!stmt) {
1407         return false;
1408     }
1409     stmt->SetParamString(0x1, data);
1410     stmt->SetParamString(0x2, handle);
1411     auto ret = stmt->Update();
1412     if (ret != 1) {
1413         return false;
1414     }
1415     return true;
1416 }
1417 
SentOrForwardedMessage(MapMseBmsg & bmessage,MapMseParams & appParameter,const std::string & handle)1418 void MapMseResource::SentOrForwardedMessage(
1419     MapMseBmsg &bmessage, MapMseParams &appParameter, const std::string &handle)
1420 {
1421     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1422 
1423     UpdateData(bmessage, appParameter, handle);
1424     NotifySendMessage(bmessage, appParameter);
1425 }
1426 
UpdateData(MapMseBmsg & bmessage,MapMseParams & appParameter,const std::string & handle)1427 std::string MapMseResource::UpdateData(
1428     MapMseBmsg &bmessage, MapMseParams &appParameter, const std::string &handle)
1429 {
1430     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1431 
1432     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1433     if (!dataProvider) {
1434         return "";
1435     }
1436     try {
1437         if (!dataProvider->BeginTransaction()) {
1438             return "";
1439         }
1440         if (UpdateMessage(dataProvider, bmessage, handle) != RET_NO_ERROR) {
1441             dataProvider->Rollback();
1442             return "";
1443         }
1444         if (UpdateMessageList(dataProvider, handle) != RET_NO_ERROR) {
1445             dataProvider->Rollback();
1446             return "";
1447         }
1448         dataProvider->Commit();
1449     } catch (const std::exception &e) {
1450         dataProvider->Rollback();
1451     }
1452     return handle;
1453 }
1454 
UpdateMessage(std::unique_ptr<DataAccess> & dataAccess,const MapMseBmsg & bmessage,const std::string & handle)1455 int MapMseResource::UpdateMessage(
1456     std::unique_ptr<DataAccess> &dataAccess, const MapMseBmsg &bmessage, const std::string &handle)
1457 {
1458     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1459 
1460     std::string sql = "update Message set body = ? where handle = ? ";
1461     auto stmt = dataAccess->CreateStatement(sql);
1462     if (!stmt) {
1463         return RET_BAD_STATUS;
1464     }
1465     stmt->SetParamString(0x1, bmessage.GetMsgBody());
1466     stmt->SetParamString(0x2, handle);
1467     auto ret = stmt->Update();
1468     if (ret != 1) {
1469         return RET_BAD_STATUS;
1470     }
1471     return RET_NO_ERROR;
1472 }
1473 
UpdateMessageList(std::unique_ptr<DataAccess> & dataAccess,const std::string & handle)1474 int MapMseResource::UpdateMessageList(std::unique_ptr<DataAccess> &dataAccess, const std::string &handle)
1475 {
1476     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1477 
1478     std::string sql = "update MessageList set datetime = ?, folder = ? where handle = ? ";
1479     auto stmt = dataAccess->CreateStatement(sql);
1480     if (!stmt) {
1481         return RET_BAD_STATUS;
1482     }
1483     stmt->SetParamString(0x1, GetDateTime());
1484     stmt->SetParamString(0x2, "outbox");
1485     stmt->SetParamString(0x3, handle);
1486     auto ret = stmt->Insert();
1487     if (ret != 1) {
1488         return RET_BAD_STATUS;
1489     }
1490     return RET_NO_ERROR;
1491 }
1492 
SentConversationMessage(MapMseBmsg & bmessage,MapMseParams & appParameter,const std::string & folderName)1493 std::string MapMseResource::SentConversationMessage(
1494     MapMseBmsg &bmessage, MapMseParams &appParameter, const std::string &folderName)
1495 {
1496     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1497 
1498     auto handle = InsertConvData(bmessage, appParameter, folderName);
1499     if (handle == "") {
1500         return "";
1501     }
1502     NotifySendMessage(bmessage, appParameter);
1503     return handle;
1504 }
1505 
InsertConvData(MapMseBmsg & bmessage,MapMseParams & appParameter,const std::string & folderName)1506 std::string MapMseResource::InsertConvData(
1507     MapMseBmsg &bmessage, MapMseParams &appParameter, const std::string &folderName)
1508 {
1509     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1510     if (!dataProvider) {
1511         return "";
1512     }
1513     uint64_t tempHandle = GetMessageHandle(bmessage.GetType());
1514     std::stringstream ss;
1515     int index = 0x10;
1516     ss << std::uppercase << std::hex << std::setw(index) << std::setfill('0') << tempHandle;
1517     std::string handle = ss.str();
1518     try {
1519         if (!dataProvider->BeginTransaction()) {
1520             dataProvider->Rollback();
1521             return "";
1522         }
1523         if (InsertMessage(dataProvider, appParameter, bmessage, handle) != RET_NO_ERROR) {
1524             dataProvider->Rollback();
1525             return "";
1526         }
1527         if (InsertMessageList(dataProvider, appParameter, bmessage, handle, folderName) != RET_NO_ERROR) {
1528             dataProvider->Rollback();
1529             return "";
1530         }
1531         for (auto &iter : bmessage.GetOriginators()) {
1532             if (InsertVCard(dataProvider, iter, true, handle) != RET_NO_ERROR) {
1533                 dataProvider->Rollback();
1534                 return "";
1535             }
1536         }
1537         for (auto &iter : bmessage.GetRecipients()) {
1538             if (InsertVCard(dataProvider, iter, false, handle) != RET_NO_ERROR) {
1539                 dataProvider->Rollback();
1540                 return "";
1541             }
1542         }
1543         if (UpdateConvMessage(dataProvider, appParameter.conversationId_, handle) != RET_NO_ERROR) {
1544             dataProvider->Rollback();
1545             return "";
1546         }
1547         if (UpdateConvMessageList(dataProvider, appParameter.conversationId_, handle) != RET_NO_ERROR) {
1548             dataProvider->Rollback();
1549             return "";
1550         }
1551         dataProvider->Commit();
1552     } catch (const std::exception &e) {
1553         dataProvider->Rollback();
1554     }
1555     return handle;
1556 }
1557 
UpdateConvMessage(std::unique_ptr<DataAccess> & dataAccess,const std::string & conversationId,const std::string & handle)1558 int MapMseResource::UpdateConvMessage(
1559     std::unique_ptr<DataAccess> &dataAccess, const std::string &conversationId, const std::string &handle)
1560 {
1561     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1562 
1563     std::string sql = "update Message set conversation_id = ? where handle = ? ";
1564     auto stmt = dataAccess->CreateStatement(sql);
1565     if (!stmt) {
1566         return RET_BAD_STATUS;
1567     }
1568     stmt->SetParamString(0x1, conversationId);
1569     stmt->SetParamString(0x2, handle);
1570     auto ret = stmt->Update();
1571     if (ret != 1) {
1572         return RET_BAD_STATUS;
1573     }
1574     return RET_NO_ERROR;
1575 }
1576 
UpdateConvMessageList(std::unique_ptr<DataAccess> & dataAccess,const std::string & conversationId,const std::string & handle)1577 int MapMseResource::UpdateConvMessageList(
1578     std::unique_ptr<DataAccess> &dataAccess, const std::string &conversationId, const std::string &handle)
1579 {
1580     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1581 
1582     std::string sql = "update MessageList set conversation_id = ? where handle = ? ";
1583     auto stmt = dataAccess->CreateStatement(sql);
1584     if (!stmt) {
1585         return RET_BAD_STATUS;
1586     }
1587     stmt->SetParamString(0x1, conversationId);
1588     stmt->SetParamString(0x2, handle);
1589     auto ret = stmt->Insert();
1590     if (ret != 1) {
1591         return RET_BAD_STATUS;
1592     }
1593     return RET_NO_ERROR;
1594 }
1595 
NotifySendMessage(const MapMseBmsg & bmessage,const MapMseParams & appParameter)1596 void MapMseResource::NotifySendMessage(const MapMseBmsg &bmessage, const MapMseParams &appParameter)
1597 {
1598     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1599 
1600     std::vector<MapMseVcard> recipients = bmessage.GetRecipients();
1601     std::string body = bmessage.GetMsgBody();
1602     for (auto &recipient : recipients) {
1603         if (recipient.GetEnvLevel() == 0) {
1604             stub::MsgInfo msgInfo;
1605             msgInfo.phoneNumber = recipient.GetFirstPhoneNumber();
1606             msgInfo.emailAddress = recipient.GetFirstEmail();
1607             if (appParameter.retry_) {
1608                 msgInfo.retry = *appParameter.retry_;
1609             }
1610             if (appParameter.transparent_) {
1611                 msgInfo.transparent = *appParameter.transparent_;
1612             }
1613             msgInfo.msgType = static_cast<int>(bmessage.GetType());
1614 
1615             stub::MapService::GetInstance()->SendMessage(msgInfo, body, masId_);
1616         }
1617     }
1618 }
1619 
SentNewMessage(MapMseBmsg & bmessage,std::string & folderName,MapMseParams & appParameter)1620 std::string MapMseResource::SentNewMessage(
1621     MapMseBmsg &bmessage, std::string &folderName, MapMseParams &appParameter)
1622 {
1623     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1624 
1625     auto handle = DataInsert(bmessage, appParameter, folderName);
1626     if (handle == "") {
1627         return "";
1628     }
1629     NotifySendMessage(bmessage, appParameter);
1630     return handle;
1631 }
1632 
DataInsert(MapMseBmsg & bmessage,MapMseParams & appParameter,const std::string & folderName)1633 std::string MapMseResource::DataInsert(
1634     MapMseBmsg &bmessage, MapMseParams &appParameter, const std::string &folderName)
1635 {
1636     auto dataProvider = DataAccess::GetConnection(DEFAULT_MAP_MSE_DB_FILE, false);
1637     if (!dataProvider) {
1638         return "";
1639     }
1640     uint64_t tempHandle = GetMessageHandle(bmessage.GetType());
1641     std::stringstream ss;
1642     int index = 0x10;
1643     ss << std::uppercase << std::hex << std::setw(index) << std::setfill('0') << tempHandle;
1644     std::string handle = ss.str();
1645     try {
1646         if (!dataProvider->BeginTransaction()) {
1647             return "";
1648         }
1649         if (InsertMessage(dataProvider, appParameter, bmessage, handle) != RET_NO_ERROR) {
1650             return "";
1651         }
1652         if (InsertMessageList(dataProvider, appParameter, bmessage, handle, folderName) != RET_NO_ERROR) {
1653             dataProvider->Rollback();
1654             return "";
1655         }
1656         for (auto &iter : bmessage.GetOriginators()) {
1657             if (InsertVCard(dataProvider, iter, true, handle) != RET_NO_ERROR) {
1658                 dataProvider->Rollback();
1659                 return "";
1660             }
1661         }
1662         for (auto &iter : bmessage.GetRecipients()) {
1663             if (InsertVCard(dataProvider, iter, false, handle) != RET_NO_ERROR) {
1664                 dataProvider->Rollback();
1665                 return "";
1666             }
1667         }
1668         dataProvider->Commit();
1669     } catch (const std::exception &e) {
1670         dataProvider->Rollback();
1671     }
1672     return handle;
1673 }
1674 
InsertMessageList(std::unique_ptr<DataAccess> & dataAccess,MapMseParams & appParameter,const MapMseBmsg & bmessage,const std::string & handle,const std::string & folderName)1675 int MapMseResource::InsertMessageList(std::unique_ptr<DataAccess> &dataAccess, MapMseParams &appParameter,
1676     const MapMseBmsg &bmessage, const std::string &handle, const std::string &folderName)
1677 {
1678     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1679 
1680     std::string sql =
1681         "insert into MessageList(handle, subject, datetime, sender_name, sender_addressing, recipient_name, "
1682         "recipient_addressing, type, size, text, reception_status, attachment_size, priority, read, sent, protected, "
1683         "folder, delivery_status, direction) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
1684     auto stmt = dataAccess->CreateStatement(sql);
1685     if (!stmt) {
1686         return RET_BAD_STATUS;
1687     }
1688     int index = 1;
1689     stmt->SetParamString(index++, handle);
1690     stmt->SetParamString(index++, "");
1691     stmt->SetParamString(index++, GetDateTime());
1692     std::string name = "";
1693     std::string addr = "";
1694     GetNameAddress(bmessage.GetType(), bmessage.GetOriginators(), name, addr);
1695     stmt->SetParamString(index++, name);
1696     stmt->SetParamString(index++, addr);
1697     GetNameAddress(bmessage.GetType(), bmessage.GetRecipients(), name, addr);
1698     stmt->SetParamString(index++, name);
1699     stmt->SetParamString(index++, addr);
1700     stmt->SetParamInt(index++, (int)bmessage.GetType());
1701     stmt->SetParamInt(index++, bmessage.GetMsgBody().size());
1702     stmt->SetParamInt(index++, 1);
1703     stmt->SetParamString(index++, "complete");
1704     stmt->SetParamInt(index++, 0);
1705     stmt->SetParamInt(index++, 0);
1706     int read = (bmessage.GetStatus() == "READ") ? 1 : 0;
1707     stmt->SetParamInt(index++, read);
1708     stmt->SetParamInt(index++, 1);
1709     stmt->SetParamInt(index++, 0);
1710     stmt->SetParamString(index++, folderName);
1711     stmt->SetParamString(index++, "sent");
1712     stmt->SetParamString(index++, "outgoing");
1713     auto ret = stmt->Insert();
1714     if (ret != 1)
1715         return RET_BAD_STATUS;
1716     return RET_NO_ERROR;
1717 }
1718 
GetNameAddress(MessageType type,std::vector<MapMseVcard> vcard,std::string & name,std::string & sender)1719 void MapMseResource::GetNameAddress(
1720     MessageType type, std::vector<MapMseVcard> vcard, std::string &name, std::string &sender)
1721 {
1722     name = "";
1723     sender = "";
1724     if (vcard.size() > 0) {
1725         name = vcard.front().GetName();
1726         if (type == MessageType::EMAIL) {
1727             sender = vcard.front().GetFirstEmail();
1728         } else {
1729             sender = vcard.front().GetFirstPhoneNumber();
1730         }
1731     }
1732 }
1733 
InsertMessage(std::unique_ptr<DataAccess> & dataAccess,MapMseParams & appParameter,const MapMseBmsg & bmessage,const std::string & handle)1734 int MapMseResource::InsertMessage(std::unique_ptr<DataAccess> &dataAccess, MapMseParams &appParameter,
1735     const MapMseBmsg &bmessage, const std::string &handle)
1736 {
1737     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1738 
1739     std::string sql = "insert into Message(transparent, retry, char_set, handle, body, version, status, type, "
1740                       "folder_path, extended_data, part_id, encoding, conent_charset, language, content_length"
1741                       ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
1742     auto stmt = dataAccess->CreateStatement(sql);
1743     if (!stmt) {
1744         return RET_BAD_STATUS;
1745     }
1746     int transparent = 0;
1747     if (appParameter.transparent_) {
1748         transparent = *appParameter.transparent_;
1749     }
1750     int retry = 1;
1751     if (appParameter.retry_) {
1752         retry = *appParameter.retry_;
1753     }
1754     int index = 1;
1755     stmt->SetParamInt(index++, transparent);
1756     stmt->SetParamInt(index++, retry);
1757     stmt->SetParamInt(index++, (int)*appParameter.charSet_);
1758     stmt->SetParamString(index++, handle);
1759     stmt->SetParamString(index++, bmessage.GetMsgBody());
1760     stmt->SetParamString(index++, bmessage.GetVersion());
1761     stmt->SetParamString(index++, bmessage.GetStatus());
1762     stmt->SetParamString(index++, GetMessageNameByType(bmessage.GetType()));
1763     stmt->SetParamString(index++, bmessage.GetFolder());
1764     stmt->SetParamString(index++, bmessage.GetExtendedData());
1765     stmt->SetParamString(index++, bmessage.GetPartId());
1766     stmt->SetParamString(index++, bmessage.GetEncoding());
1767     stmt->SetParamString(index++, bmessage.GetCharset());
1768     stmt->SetParamString(index++, bmessage.GetLanguage());
1769     stmt->SetParamString(index++, bmessage.GetBmsgLength());
1770     auto ret = stmt->Insert();
1771     if (ret != 1) {
1772         return RET_BAD_STATUS;
1773     }
1774     return RET_NO_ERROR;
1775 }
1776 
InsertVCard(std::unique_ptr<DataAccess> & dataAccess,const MapMseVcard & vcard,const int isOriginator,const std::string & handle)1777 int MapMseResource::InsertVCard(
1778     std::unique_ptr<DataAccess> &dataAccess, const MapMseVcard &vcard, const int isOriginator,
1779     const std::string &handle)
1780 {
1781     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
1782 
1783     std::string sql = "insert into Vcard(name, version, formatted_name, phone_numbers, email_addresses, x_bt_uid, "
1784                       "x_bt_ucis, env_level, is_originator, handle) values (?,?,?,?,?,?,?,?,?,?)";
1785     auto stmt = dataAccess->CreateStatement(sql);
1786     if (!stmt) {
1787         return RET_BAD_STATUS;
1788     }
1789     int index = 1;
1790     stmt->SetParamString(index++, vcard.GetName());
1791     stmt->SetParamString(index++, vcard.GetVersion());
1792     stmt->SetParamString(index++, vcard.GetFormattedName());
1793     stmt->SetParamString(index++, vcard.GetPhoneNumbersText());
1794     stmt->SetParamString(index++, vcard.GetEmailAddressesText());
1795     stmt->SetParamString(index++, vcard.GetBtUidsText());
1796     stmt->SetParamString(index++, vcard.GetBtUcisText());
1797     stmt->SetParamInt(index++, vcard.GetEnvLevel());
1798     stmt->SetParamInt(index++, isOriginator);
1799     stmt->SetParamString(index++, handle);
1800     auto ret = stmt->Insert();
1801     if (ret != 1) {
1802         return RET_BAD_STATUS;
1803     }
1804     return RET_NO_ERROR;
1805 }
1806 
GetDateTime()1807 std::string MapMseResource::GetDateTime()
1808 {
1809     time_t currTime;
1810     time(&currTime);
1811     struct tm utctm;
1812     gmtime_r(&currTime, &utctm);
1813     char buff[16] = "";
1814     strftime(buff, sizeof(buff), "%Y%m%{public}d%H%M%{public}s%Z", &utctm);
1815     return std::string(buff);
1816 }
1817 
GetMessageHandle(MessageType type)1818 uint64_t MapMseResource::GetMessageHandle(MessageType type)
1819 {
1820     uint64_t handle = std::strtoul(GetDateTime().c_str(), nullptr, 0x10);
1821     if (type == MessageType::EMAIL) {
1822         return handle | MESSAGE_HANDLE_EMAIL_MASK;
1823     } else if (type == MessageType::IM) {
1824         return handle | MESSAGE_HANDLE_IM_MASK;
1825     } else if (type == MessageType::MMS) {
1826         return handle | MESSAGE_HANDLE_MMS_MASK;
1827     } else if (type == MessageType::SMS_GSM) {
1828         return handle | MESSAGE_HANDLE_SMS_GSM_MASK;
1829     } else if (type == MessageType::SMS_CDMA) {
1830         return handle | MESSAGE_HANDLE_SMS_CDMA_MASK;
1831     } else {
1832         MSE_LOG_INFO("Message type is not supported.");
1833         return 0x0;
1834     }
1835 }
1836 
GetMessageNameByType(MessageType type)1837 std::string MapMseResource::GetMessageNameByType(MessageType type)
1838 {
1839     if (type == MessageType::EMAIL) {
1840         return "EMAIL";
1841     } else if (type == MessageType::IM) {
1842         return "IM";
1843     } else if (type == MessageType::MMS) {
1844         return "MMS";
1845     } else if (type == MessageType::SMS_GSM) {
1846         return "SMS_GSM";
1847     } else if (type == MessageType::SMS_CDMA) {
1848         return "SMS_CDMA";
1849     } else {
1850         return "NONE";
1851     }
1852 }
1853 }  // namespace bluetooth
1854 }  // namespace OHOS
1855