~aleteoryx/muditaos

ref: 17c9d3ee7b68de75710823b8366ea56dac63f8d0 muditaos/module-apps/application-messages/ApplicationMessages.cpp -rw-r--r-- 11.0 KiB
17c9d3ee — Mateusz Grzywacz [feature] use .isValid() to validate all interface entires 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
#include "ApplicationMessages.hpp"

#include "application-messages/data/SMSTextToSearch.hpp"
#include "windows/MessagesMainWindow.hpp"
#include "windows/NewMessage.hpp"
#include "windows/OptionsMessages.hpp"
#include "windows/OptionsWindow.hpp"
#include "windows/ThreadViewWindow.hpp"
#include "windows/SearchStart.hpp"
#include "windows/SMSTemplatesWindow.hpp"
#include "windows/SearchResults.hpp"

#include <MessageType.hpp>
#include <Dialog.hpp>
#include <i18/i18.hpp>
#include <../module-services/service-db/messages/DBNotificationMessage.hpp>
#include <service-db/api/DBServiceAPI.hpp>
#include <cassert>
#include <time/time_conversion.hpp>

namespace app
{

    ApplicationMessages::ApplicationMessages(std::string name, std::string parent, bool startBackgound)
        : Application(name, parent, startBackgound, 4096 * 2)
    {
        busChannels.push_back(sys::BusChannels::ServiceDBNotifications);
    }

    ApplicationMessages::~ApplicationMessages()
    {}

    // Invoked upon receiving data message
    sys::Message_t ApplicationMessages::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp)
    {
        auto retMsg = Application::DataReceivedHandler(msgl);
        // if message was handled by application's template there is no need to process further.
        if (reinterpret_cast<sys::ResponseMessage *>(retMsg.get())->retCode == sys::ReturnCodes::Success) {
            return retMsg;
        }

        if (msgl->messageType == MessageType::DBServiceNotification) {
            auto msg = dynamic_cast<db::NotificationMessage *>(msgl);
            LOG_DEBUG("Received multicast");
            if (msg != nullptr) {
                // window-specific actions
                for (auto &[name, window] : windows) {
                    window->onDatabaseMessage(msg);
                }
                // app-wide actions
                // <none>
                return std::make_shared<sys::ResponseMessage>();
            }
        }

        // this variable defines whether message was processed.
        bool handled = false;

        // handle database response
        if (resp != nullptr) {
            handled = true;
            switch (resp->responseTo) {
            case MessageType::DBThreadGetLimitOffset:
            case MessageType::DBQuery:
            case MessageType::DBSMSTemplateGetLimitOffset: {
                if (getCurrentWindow()->onDatabaseMessage(resp))
                    refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST);
            } break;
            default:
                break;
            }
        }

        if (handled)
            return std::make_shared<sys::ResponseMessage>();
        else
            return std::make_shared<sys::ResponseMessage>(sys::ReturnCodes::Unresolved);
    }

    // Invoked during initialization
    sys::ReturnCodes ApplicationMessages::InitHandler()
    {

        auto ret = Application::InitHandler();
        if (ret != sys::ReturnCodes::Success)
            return ret;

        createUserInterface();

        setActiveWindow(gui::name::window::main_window);

        return ret;
    }

    sys::ReturnCodes ApplicationMessages::DeinitHandler()
    {
        return sys::ReturnCodes::Success;
    }

    void ApplicationMessages::createUserInterface()
    {
        windowOptions = gui::newOptionWindow(this);

        windows.insert({gui::name::window::main_window, new gui::MessagesMainWindow(this)});
        windows.insert({gui::name::window::thread_view, new gui::ThreadViewWindow(this)});
        windows.insert({gui::name::window::new_sms, new gui::NewSMS_Window(this)});
        windows.insert({windowOptions->getName(), windowOptions});
        windows.insert(
            {gui::name::window::dialog, new gui::Dialog(this, gui::name::window::dialog, gui::Dialog::Meta())});
        windows.insert(
            {gui::name::window::dialog_confirm, new gui::DialogConfirm(this, gui::name::window::dialog_confirm)});
        windows.insert(
            {gui::name::window::dialog_yes_no, new gui::DialogYesNo(this, gui::name::window::dialog_yes_no)});
        windows.insert({gui::name::window::thread_sms_search, new gui::SMSSearch(this)});
        windows.insert({gui::name::window::sms_templates, new gui::SMSTemplatesWindow(this)});
        windows.insert({gui::name::window::search_results, new gui::SearchResults(this)});
    }

    void ApplicationMessages::destroyUserInterface()
    {}

    bool ApplicationMessages::markSmsThreadAsRead(const uint32_t id)
    {
        using namespace db::query::smsthread;
        LOG_DEBUG("markSmsThreadAsRead");
        DBServiceAPI::GetQuery(
            this, db::Interface::Name::SMSThread, std::make_unique<MarkAsRead>(id, MarkAsRead::Read::True));
        return true;
    }

    bool ApplicationMessages::markSmsThreadAsUnread(const uint32_t id)
    {
        using namespace db::query::smsthread;
        LOG_DEBUG("markSmsThreadAsRead");
        DBServiceAPI::GetQuery(
            this, db::Interface::Name::SMSThread, std::make_unique<MarkAsRead>(id, MarkAsRead::Read::False));
        return true;
    }

    bool ApplicationMessages::removeSMS_thread(const ThreadRecord *record)
    {
        if (record == nullptr) {
            LOG_ERROR("removing null SMS thread!");
            return false;
        }
        else {
            LOG_DEBUG("Removing thread: %" PRIu32, record->ID);
            auto dialog = dynamic_cast<gui::DialogYesNo *>(windows[gui::name::window::dialog_yes_no]);
            assert(dialog != nullptr);
            auto meta   = dialog->meta;
            meta.action = [=]() -> bool {
                if (!DBServiceAPI::ThreadRemove(this, record->ID)) {
                    LOG_ERROR("ThreadRemove id=%" PRIu32 " failed", record->ID);
                    return false;
                }
                this->switchWindow(gui::name::window::main_window);
                return true;
            };
            meta.text       = utils::localize.get("app_messages_thread_delete_confirmation");
            auto contactRec = DBServiceAPI::ContactGetByID(this, record->contactID);
            auto cont       = !contactRec->empty() ? contactRec->front() : ContactRecord{};
            meta.title      = cont.getFormattedName();
            meta.icon       = "phonebook_contact_delete_trashcan";
            dialog->update(meta);
            switchWindow(dialog->getName());
            return true;
        }
    }

    bool ApplicationMessages::removeSMS(const SMSRecord &record)
    {
        LOG_DEBUG("Removing sms: %" PRIu32, record.ID);
        auto dialog = dynamic_cast<gui::DialogYesNo *>(windows[gui::name::window::dialog_yes_no]);
        assert(dialog != nullptr);

        auto meta   = dialog->meta;
        meta.action = [=]() -> bool {
            if (!DBServiceAPI::SMSRemove(this, record)) {
                LOG_ERROR("sSMSRemove id=%" PRIu32 " failed", record.ID);
                return false;
            }
            // if this was the last message in the thread, there won't be no thread. goto main window
            std::unique_ptr<ThreadRecord> threadDetails = DBServiceAPI::ThreadGet(this, record.threadID);
            if (threadDetails == nullptr || !threadDetails->isValid()) {
                this->switchWindow(gui::name::window::main_window);
                return true;
            }
            else {
                this->switchWindow(gui::name::window::thread_view);
                return true;
            }
        };
        meta.text  = utils::localize.get("app_messages_message_delete_confirmation");
        meta.title = record.body;
        meta.icon  = "phonebook_contact_delete_trashcan";
        dialog->update(meta);
        switchWindow(dialog->getName());
        return true;
    }

    bool ApplicationMessages::searchEmpty(const std::string &query)
    {
        auto dialog = dynamic_cast<gui::Dialog *>(windows[gui::name::window::dialog]);
        assert(dialog);
        auto meta  = dialog->meta;
        meta.icon  = "search_big";
        meta.text  = utils::localize.get("app_messages_thread_no_result");
        meta.title = utils::localize.get("common_results_prefix") + query;
        dialog->update(meta);
        auto data                        = std::make_unique<gui::SwitchData>();
        data->ignoreCurrentWindowOnStack = true;
        switchWindow(dialog->getName(), std::move(data));
        return true;
    }

    bool ApplicationMessages::showSearchResults(const UTF8 &title, const UTF8 &search_text)
    {
        auto name = gui::name::window::search_results;
        windows[name]->setTitle(title);
        switchWindow(name, std::make_unique<SMSTextToSearch>(search_text));
        return true;
    }

    bool ApplicationMessages::showNotification(std::function<bool()> action, bool ignoreCurrentWindowOnStack)
    {
        auto dialog = dynamic_cast<gui::DialogConfirm *>(windows[gui::name::window::dialog_confirm]);
        assert(dialog);
        auto meta   = dialog->meta;
        meta.icon   = "info_big_circle_W_G";
        meta.text   = utils::localize.get("app_messages_no_sim");
        meta.action = action;
        dialog->update(meta);
        auto switchData                        = std::make_unique<gui::SwitchData>();
        switchData->ignoreCurrentWindowOnStack = ignoreCurrentWindowOnStack;
        switchWindow(dialog->getName(), std::move(switchData));
        return true;
    }

    bool ApplicationMessages::sendSms(const utils::PhoneNumber::View &number, const UTF8 &body)
    {
        if (number.getEntered().size() == 0 || body.length() == 0) {
            LOG_WARN("Number or sms body is empty");
            return false;
        }
        SMSRecord record;
        record.number = number;
        record.body   = body;
        record.type   = SMSType::QUEUED;
        auto time     = utils::time::Timestamp();
        record.date   = time.getTime();
        return DBServiceAPI::SMSAdd(this, record) != DB_ID_NONE;
    }
    bool ApplicationMessages::resendSms(const SMSRecord &record)
    {
        auto resendRecord = record;
        resendRecord.type = SMSType::QUEUED;
        // update date sent - it will display an old, failed sms at the the bottom, but this is correct
        auto time         = utils::time::Timestamp();
        resendRecord.date = time.getTime();
        return DBServiceAPI::SMSUpdate(this, resendRecord) != DB_ID_NONE;
    }

    bool ApplicationMessages::handleSendSmsFromThread(const utils::PhoneNumber::View &number, const UTF8 &body)
    {
        if (!sendSms(number, body)) {
            return false;
        }

        if (!Store::GSM::get()->simCardInserted()) {
            auto action = [=]() -> bool {
                returnToPreviousWindow();
                return true;
            };
            return showNotification(action);
        }

        return true;
    }

    bool ApplicationMessages::newMessageOptions(const std::string &requestingWindow, gui::Text *text)
    {
        LOG_INFO("New message options");
        if (windowOptions != nullptr) {
            windowOptions->clearOptions();
            windowOptions->addOptions(newMessageWindowOptions(this, requestingWindow, text));
            switchWindow(windowOptions->getName(), nullptr);
        }
        return true;
    }

} /* namespace app */