~aleteoryx/muditaos

ref: 9095333b2c10af0127725c41c854c53453f41787 muditaos/module-db/Interface/SMSRecord.cpp -rw-r--r-- 15.5 KiB
9095333b — Bartek Cichocki [EGD-3502] PR fixes 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#include "SMSRecord.hpp"
#include "Common/Query.hpp"
#include "ContactRecord.hpp"
#include "ThreadRecord.hpp"
#include "queries/sms/QuerySMSGet.hpp"
#include "queries/sms/QuerySMSGetByContactID.hpp"
#include "queries/sms/QuerySMSGetByID.hpp"
#include "queries/sms/QuerySMSGetByText.hpp"
#include "queries/sms/QuerySMSGetCount.hpp"
#include "queries/sms/QuerySMSSearch.hpp"
#include "queries/sms/QuerySMSRemove.hpp"
#include "queries/sms/QuerySMSSearchByType.hpp"
#include <log/log.hpp>

#include <PhoneNumber.hpp>
#include <optional>

SMSRecord::SMSRecord(const SMSTableRow &w, const utils::PhoneNumber::View &num)
    : date(w.date), dateSent(w.dateSent), errorCode(w.errorCode), body(w.body), type(w.type), threadID(w.threadID),
      contactID(w.contactID), number(num)
{
    this->ID = w.ID;
}

SMSRecordInterface::SMSRecordInterface(SmsDB *smsDb, ContactsDB *contactsDb) : smsDB(smsDb), contactsDB(contactsDb)
{}

bool SMSRecordInterface::Add(const SMSRecord &rec)
{
    ContactRecordInterface contactInterface(contactsDB);
    auto contactRec = contactInterface.MatchByNumber(rec.number, ContactRecordInterface::CreateTempContact::True);
    if (contactRec == std::nullopt) {
        LOG_ERROR("Cannot find contact, for number %s", rec.number.getFormatted().c_str());
        return false;
    }
    uint32_t contactID = contactRec->ID;
    // Search for a thread with specified contactID
    ThreadRecordInterface threadInterface(smsDB, contactsDB);
    auto threadRec =
        threadInterface.GetLimitOffsetByField(0, 1, ThreadRecordField::ContactID, std::to_string(contactID).c_str());

    // Thread not found, create one
    if (threadRec->size() == 0) {

        ThreadRecord re;
        re.contactID = contactID;
        if (!threadInterface.Add(re)) {
            LOG_ERROR("Cannot create new thread");
            return false;
        }

        threadRec = threadInterface.GetLimitOffsetByField(
            0, 1, ThreadRecordField::ContactID, std::to_string(contactID).c_str());
        if (threadRec->size() == 0) {
            LOG_ERROR("Thread not found");
            return false;
        }
    }
    auto thread = (*threadRec)[0];

    // Create SMS
    if (!smsDB->sms.add(SMSTableRow{{.ID = DB_ID_NONE}, // the entry is not yet in the DB
                                    .threadID  = thread.ID,
                                    .contactID = contactID,
                                    .date      = rec.date,
                                    .dateSent  = rec.dateSent,
                                    .errorCode = rec.errorCode,
                                    .body      = rec.body,
                                    .type      = rec.type

        })) {
        LOG_ERROR("Cannot add sms");
        return false;
    }

    // TODO: error check

    // Update thread
    UpdateThreadSummary(thread, rec);

    thread.msgCount++;
    if (rec.type == SMSType::INBOX) {
        thread.unreadMsgCount++;
        LOG_DEBUG("unreadMsgCount = %" PRIu32 " for thread = %" PRIu32, thread.unreadMsgCount, thread.ID);
    }

    if (!threadInterface.Update(thread)) {
        LOG_ERROR("Cannot update thread");
        return false;
    }

    return true;
}
uint32_t SMSRecordInterface::GetCount()
{
    return smsDB->sms.count();
}

uint32_t SMSRecordInterface::GetLastID(void)
{
    return smsDB->getLastInsertRowId();
}
std::unique_ptr<std::vector<SMSRecord>> SMSRecordInterface::GetLimitOffsetByField(uint32_t offset,
                                                                                  uint32_t limit,
                                                                                  SMSRecordField field,
                                                                                  const char *str)
{
    auto records = std::make_unique<std::vector<SMSRecord>>();

    std::vector<SMSTableRow> smses;

    switch (field) {
    case SMSRecordField ::ContactID:
        smses = smsDB->sms.getLimitOffsetByField(offset, limit, SMSTableFields::ContactID, str);
        break;

    case SMSRecordField ::ThreadID:
        smses = smsDB->sms.getLimitOffsetByField(offset, limit, SMSTableFields::ThreadID, str);
        break;

    default:
        LOG_ERROR("SMS thread get - wrong selection: %d", static_cast<int>(field));
        return records;
    }

    LOG_INFO("Get: %u SMS by selection: %d", static_cast<unsigned int>(smses.size()), static_cast<int>(field));

    ContactRecordInterface contactInterface(contactsDB);
    for (const auto &w : smses) {

        auto contactRec = contactInterface.GetByID(w.contactID);

        if (contactRec.numbers.size() != 0) {
            // TODO: or numberUser? or other number?
            records->push_back({w, contactRec.numbers[0].number});
        }
    }

    return records;
}

std::unique_ptr<std::vector<SMSRecord>> SMSRecordInterface::GetLimitOffset(uint32_t offset, uint32_t limit)
{
    auto smses = smsDB->sms.getLimitOffset(offset, limit);

    auto records = std::make_unique<std::vector<SMSRecord>>();

    ContactRecordInterface contactInterface(contactsDB);
    for (const auto &w : smses) {

        auto contactRec = contactInterface.GetByID(w.contactID);
        if (contactRec.numbers.size() != 0) {
            // TODO: or numberUser? or other number
            records->push_back({w, contactRec.numbers[0].number});
        }
    }

    return records;
}

bool SMSRecordInterface::Update(const SMSRecord &recUpdated)
{

    auto recCurrent = GetByID(recUpdated.ID);
    if (!recCurrent.isValid()) { // if updating non-existent entry
        return false;
    }

    smsDB->sms.update(SMSTableRow{{.ID = recCurrent.ID},
                                  .threadID  = recCurrent.threadID,
                                  .contactID = recCurrent.contactID,
                                  .date      = recUpdated.date,
                                  .dateSent  = recUpdated.dateSent,
                                  .errorCode = recUpdated.errorCode,
                                  .body      = recUpdated.body,
                                  .type      = recUpdated.type});

    // Update messages read count if necessary
    ThreadRecordInterface threadInterface(smsDB, contactsDB);
    auto thread = threadInterface.GetByID(recCurrent.threadID);

    // update thread details with the latest sms from given thread

    auto latest_vec = GetLimitOffsetByField(0, 1, SMSRecordField ::ThreadID, std::to_string(thread.ID).c_str());

    if (latest_vec->size() == 0) {
        return false;
    }
    auto recLatestInThread = (*latest_vec)[0];

    // is updated sms is the latest we need to update the summary
    if (recUpdated.ID == recLatestInThread.ID) {
        // latest is visible, so update thread details
        UpdateThreadSummary(thread, recLatestInThread);
        threadInterface.Update(thread);
    }

    return true;
}

void SMSRecordInterface::UpdateThreadSummary(ThreadRecord &threadToUpdate, const SMSRecord &rec)
{
    threadToUpdate.snippet = rec.body.substr(0, rec.body.length() >= snippetLength ? snippetLength : rec.body.length());
    threadToUpdate.date    = rec.date;
    threadToUpdate.type    = rec.type;
}

bool SMSRecordInterface::RemoveByID(uint32_t id)
{
    auto sms = smsDB->sms.getById(id);
    if (!sms.isValid()) {
        return false;
    }

    ThreadRecordInterface threadInterface(smsDB, contactsDB);
    auto threadRec = threadInterface.GetByID(sms.threadID);

    // If thread not found
    if (!threadRec.isValid()) {
        return smsDB->sms.removeById(id);
    }

    // If thread contains only one message remove it
    if (threadRec.msgCount <= 1) {
        threadInterface.RemoveByID(sms.threadID);
    }
    else {
        // update thread details if deleted SMS is the latest sms from the thread

        auto twoLatest = GetLimitOffsetByField(0, 2, SMSRecordField ::ThreadID, std::to_string(threadRec.ID).c_str());

        if (twoLatest->size() == 0) {
            LOG_ERROR("Cannot fetch no SMSes even though thread's msgCount says so (id %lu)",
                      static_cast<long unsigned int>(sms.threadID));
            threadInterface.RemoveByID(sms.threadID);
            return false; // not handled (do no change window)
        }
        else {
            // check if there is need to change thread summary
            if (sms.ID == (*twoLatest)[0].ID) {
                // there is the need
                if (twoLatest->size() < 2) {
                    LOG_ERROR("Cannot fetch another sms from a thread even though thread's msgCount says so (id %lu)",
                              static_cast<long unsigned int>(sms.threadID));
                    smsDB->sms.removeById(id);                // remove sms which triggered this function
                    threadInterface.RemoveByID(sms.threadID); // and dangling thread as well
                    return true;                              // handled (current window will be changed)
                }
                else {
                    auto newLatest = (*twoLatest)[1];
                    UpdateThreadSummary(threadRec, newLatest);
                }
            }
            threadRec.msgCount--;
            threadInterface.Update(threadRec);
            // if deleting the newest sms, refresh thread details with next sms in the column
        }
    }

    // Remove SMS
    if (smsDB->sms.removeById(id) == false) {
        return false;
    }

    return true;
}

bool SMSRecordInterface::RemoveByField(SMSRecordField field, const char *str)
{
    switch (field) {
    case SMSRecordField ::ContactID:
        return smsDB->sms.removeByField(SMSTableFields::ContactID, str);

    case SMSRecordField ::ThreadID:
        return smsDB->sms.removeByField(SMSTableFields::ThreadID, str);

    case SMSRecordField ::Number:
        return false;

    default:
        return false;
    }
}

SMSRecord SMSRecordInterface::GetByID(uint32_t id)
{
    auto sms = smsDB->sms.getById(id);

    ContactRecordInterface contactInterface(contactsDB);
    auto contactRec = contactInterface.GetByID(sms.contactID);
    // TODO: or numberUser?
    auto number = contactRec.numbers.size() != 0 ? contactRec.numbers[0].number : utils::PhoneNumber::View();

    return SMSRecord{sms, number};
}

std::unique_ptr<db::QueryResult> SMSRecordInterface::runQuery(std::shared_ptr<db::Query> query)
{
    if (typeid(*query) == typeid(db::query::SMSSearchByType)) {
        return runQueryImpl(static_cast<const db::query::SMSSearchByType *>(query.get()));
    }
    else if (typeid(*query) == typeid(db::query::SMSGetByID)) {
        return getByIDQuery(query);
    }
    else if (typeid(*query) == typeid(db::query::SMSGetByContactID)) {
        return getByContactIDQuery(query);
    }
    else if (typeid(*query) == typeid(db::query::SMSGetByText)) {
        return getByTextQuery(query);
    }
    else if (typeid(*query) == typeid(db::query::SMSGetCount)) {
        return getCountQuery(query);
    }
    else if (typeid(*query) == typeid(db::query::SMSRemove)) {
        return removeQuery(query);
    }
    else if (typeid(*query) == typeid(db::query::SMSGet)) {
        return getQuery(query);
    }

    return nullptr;
}

std::unique_ptr<db::query::SMSSearchByTypeResult> SMSRecordInterface::runQueryImpl(
    const db::query::SMSSearchByType *query)
{
    auto db_result = smsDB->sms.getManyByType(query->type, query->starting_postion, query->depth);

    auto records = std::make_unique<std::vector<SMSRecord>>();

    ContactRecordInterface contactInterface(contactsDB);
    for (const auto &w : db_result.second) {

        auto contactRec = contactInterface.GetByID(w.contactID);
        if (contactRec.numbers.size() != 0) {
            // TODO: or numberUser? or other number
            records->push_back({w, contactRec.numbers[0].number});
        }
    }
    return std::make_unique<db::query::SMSSearchByTypeResult>(db_result.first, *records);
}

std::unique_ptr<db::QueryResult> SMSRecordInterface::getByIDQuery(std::shared_ptr<db::Query> query)
{
    const auto localQuery = static_cast<const db::query::SMSGetByID *>(query.get());
    auto sms              = smsDB->sms.getById(localQuery->id);
    SMSRecord record;

    record.body      = sms.body;
    record.contactID = sms.contactID;
    record.date      = sms.date;
    record.dateSent  = sms.dateSent;
    record.errorCode = sms.errorCode;
    record.threadID  = sms.threadID;
    record.type      = sms.type;
    record.ID        = sms.ID;
    auto response    = std::make_unique<db::query::SMSGetByIDResult>(record);
    response->setRequestQuery(query);
    return response;
}

std::unique_ptr<db::QueryResult> SMSRecordInterface::getByContactIDQuery(std::shared_ptr<db::Query> query)
{
    const auto localQuery = static_cast<const db::query::SMSGetByContactID *>(query.get());
    auto smsVector        = smsDB->sms.getByContactId(localQuery->contactId);
    std::vector<SMSRecord> recordVector;
    for (auto sms : smsVector) {
        SMSRecord record;
        record.body      = sms.body;
        record.contactID = sms.contactID;
        record.date      = sms.date;
        record.dateSent  = sms.dateSent;
        record.errorCode = sms.errorCode;
        record.threadID  = sms.threadID;
        record.type      = sms.type;
        record.ID        = sms.ID;
        recordVector.emplace_back(record);
    }

    auto response = std::make_unique<db::query::SMSGetByContactIDResult>(recordVector);
    response->setRequestQuery(query);
    return response;
}
std::unique_ptr<db::QueryResult> SMSRecordInterface::getByTextQuery(std::shared_ptr<db::Query> query)
{
    const auto localQuery = static_cast<const db::query::SMSGetByText *>(query.get());
    auto smsVector        = smsDB->sms.getByText(localQuery->text);
    std::vector<SMSRecord> recordVector;
    for (auto sms : smsVector) {
        SMSRecord record;
        record.body      = sms.body;
        record.contactID = sms.contactID;
        record.date      = sms.date;
        record.dateSent  = sms.dateSent;
        record.errorCode = sms.errorCode;
        record.threadID  = sms.threadID;
        record.type      = sms.type;
        record.ID        = sms.ID;
        recordVector.emplace_back(record);
    }

    auto response = std::make_unique<db::query::SMSGetByTextResult>(recordVector);
    response->setRequestQuery(query);
    return response;
}
std::unique_ptr<db::QueryResult> SMSRecordInterface::getCountQuery(std::shared_ptr<db::Query> query)
{
    auto response = std::make_unique<db::query::SMSGetCountResult>(smsDB->sms.count());
    response->setRequestQuery(query);
    return response;
}
std::unique_ptr<db::QueryResult> SMSRecordInterface::removeQuery(std::shared_ptr<db::Query> query)
{
    const auto localQuery = static_cast<const db::query::SMSRemove *>(query.get());
    auto ret              = smsDB->sms.removeById(localQuery->id);
    auto response         = std::make_unique<db::query::SMSRemoveResult>(ret);
    response->setRequestQuery(query);
    return response;
}
std::unique_ptr<db::QueryResult> SMSRecordInterface::getQuery(std::shared_ptr<db::Query> query)
{
    const auto localQuery = static_cast<const db::query::SMSGet *>(query.get());

    auto smsVector = smsDB->sms.getLimitOffset(localQuery->getOffset(), localQuery->getLimit());
    std::vector<SMSRecord> recordVector;
    for (auto sms : smsVector) {
        SMSRecord record;
        record.body      = sms.body;
        record.contactID = sms.contactID;
        record.date      = sms.date;
        record.dateSent  = sms.dateSent;
        record.errorCode = sms.errorCode;
        record.threadID  = sms.threadID;
        record.type      = sms.type;
        record.ID        = sms.ID;
        recordVector.emplace_back(record);
    }

    auto response = std::make_unique<db::query::SMSGetResult>(recordVector);
    response->setRequestQuery(query);
    return response;
}