~aleteoryx/muditaos

muditaos/module-apps/application-call/ApplicationCall.cpp -rw-r--r-- 14.6 KiB
a405cad6Aleteoryx trim readme 6 days 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
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/LICENSE.md

#include "ApplicationCall.hpp"
#include "CallSwitchData.hpp"
#include "CallWindow.hpp"
#include "EmergencyCallWindow.hpp"
#include "EnterNumberWindow.hpp"
#include "presenter/CallPresenter.hpp"

#include <apps-common/messages/DialogMetadataMessage.hpp>
#include <apps-common/windows/Dialog.hpp>
#include <apps-common/windows/DialogMetadata.hpp>
#include <apps-common/WindowsStack.hpp>
#include <log/log.hpp>
#include <module-apps/application-phonebook/data/PhonebookItemData.hpp>

#include <PhoneNumber.hpp>
#include <service-appmgr/Controller.hpp>
#include <service-appmgr/data/MmiActionsParams.hpp>
#include <service-cellular/CellularServiceAPI.hpp>
#include <time/time_conversion.hpp>
#include <WindowsPopupFilter.hpp>
#include <service-audio/AudioServiceAPI.hpp>
#include <service-db/Settings.hpp>
#include <service-db/agents/settings/SystemSettings.hpp>

#include <cassert>
#include <memory>

namespace
{
    constexpr auto applicationCallStackSize = 1024 * 8;
}

namespace app
{
    ApplicationCall::ApplicationCall(std::string name,
                                     std::string parent,
                                     StatusIndicators statusIndicators,
                                     StartInBackground startInBackground)
        : Application(std::move(name), std::move(parent), statusIndicators, startInBackground, applicationCallStackSize)
    {
        using namespace gui::status_bar;

        bus.channels.push_back(sys::BusChannel::ServiceAudioNotifications);

        getPopupFilter().addAppDependentFilter([&](const gui::PopupRequestParams &popupParams) {
            if (popupParams.getPopupId() == gui::popup::ID::Volume) {
                return gui::popup::FilterType::Show;
            }
            return gui::popup::FilterType::Show;
        });
        statusBarManager->enableIndicators(
            {Indicator::Signal, Indicator::Time, Indicator::Battery, Indicator::SimCard});

        addActionReceiver(manager::actions::Call, [this](auto &&data) {
            if (auto msg = dynamic_cast<app::CallSwitchData *>(data.get()); msg != nullptr) {
                handleCallEvent(msg->getPhoneNumber().getEntered(), ExternalRequest::True);
                return actionHandled();
            }
            return actionNotHandled();
        });
        addActionReceiver(manager::actions::Dial, [this](auto &&data) {
            switchWindow(gui::window::name::enter_number, std::forward<decltype(data)>(data));
            return actionHandled();
        });
        addActionReceiver(manager::actions::EmergencyDial, [this](auto &&data) {
            switchWindow(gui::window::name::emergency_call, std::forward<decltype(data)>(data));
            return actionHandled();
        });
        addActionReceiver(manager::actions::NotAnEmergencyNotification, [this](auto &&data) {
            auto textNoEmergency = utils::translate("app_call_wrong_emergency");
            utils::findAndReplaceAll(textNoEmergency, "$NUMBER", data->getDescription());
            showNotificationAndRestartCallFlow(NotificationType::Info, textNoEmergency);
            return actionHandled();
        });

        addActionReceiver(manager::actions::NoSimNotification, [this]([[maybe_unused]] auto &&data) {
            showNotificationAndRestartCallFlow(NotificationType::Info, utils::translate("app_call_no_sim"));
            return actionHandled();
        });
        addActionReceiver(manager::actions::NoNetworkConnectionNotification, [this]([[maybe_unused]] auto &&data) {
            showNotificationAndRestartCallFlow(NotificationType::Info,
                                               utils::translate("app_call_no_network_connection"));
            return actionHandled();
        });
        addActionReceiver(manager::actions::CallRequestGeneralErrorNotification, [this]([[maybe_unused]] auto &&data) {
            showNotificationAndRestartCallFlow(NotificationType::Failure,
                                               utils::translate("app_call_call_request_failed"));
            return actionHandled();
        });
        addActionReceiver(manager::actions::CallRejectedByOfflineNotification, [this]([[maybe_unused]] auto &&data) {
            showNotificationAndRestartCallFlow(NotificationType::Info, utils::translate("app_call_offline"));
            return actionHandled();
        });
        addActionReceiver(manager::actions::ActivateCall, [this]([[maybe_unused]] auto &&data) {
            switchWindow(gui::window::name::call);
            return actionHandled();
        });
        addActionReceiver(manager::actions::HandleOutgoingCall, [this]([[maybe_unused]] auto &&data) {
            switchWindow(gui::window::name::call);
            return actionHandled();
        });
        addActionReceiver(manager::actions::HandleIncomingCall, [this]([[maybe_unused]] auto &&data) {
            callModel->setState(call::CallState::Incoming);
            const auto window = getCurrentWindow();
            if (window->getName() != gui::window::name::call) {
                LOG_INFO("Switch to call window");
                switchWindow(gui::window::name::call);
            }
            return actionHandled();
        });
        addActionReceiver(manager::actions::HandleCallerId, [this](auto &&data) {
            const auto callParams = static_cast<app::manager::actions::CallParams *>(data.get());
            callModel->setPhoneNumber(callParams->getNumber());
            callModel->setState(call::CallState::Incoming);
            const auto window = getCurrentWindow();
            if (window->getName() != gui::window::name::call) {
                LOG_INFO("Switching to call window");
                switchWindow(gui::window::name::call);
            }
            return actionHandled();
        });

        callModel     = std::make_shared<app::call::CallModel>(this);
        callPresenter = std::make_unique<call::CallWindowContract::Presenter>(this->callModel);
    }

    bool ApplicationCall::conditionalReturnToPreviousView()
    {
        // if external request simply return to previous app
        if (externalRequest == ExternalRequest::True) {
            app::manager::Controller::switchBack(this);
            return true;
        }

        // Onboarding app should not have access to main screen so if onboarding is in progress, we pop the main window
        // from the stack
        if (!utils::getNumericValue<bool>(
                settings->getValue(settings::SystemProperties::onboardingDone, settings::SettingsScope::Global))) {
            ApplicationCommon::popWindow(gui::name::window::main_window);
        }

        returnToPreviousWindow();
        return true;
    }

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

    // Invoked during initialization
    sys::ReturnCodes ApplicationCall::InitHandler()
    {
        const auto ret = Application::InitHandler();
        if (ret != sys::ReturnCodes::Success) {
            return ret;
        }

        connect(typeid(cellular::CallDurationNotification), [&](sys::Message *request) {
            const auto message = static_cast<cellular::CallDurationNotification *>(request);
            callModel->setTime(message->callDuration);
            return sys::MessageNone{};
        });

        connect(typeid(cellular::CallActiveNotification), [&]([[maybe_unused]] sys::Message *request) {
            callModel->setState(app::call::CallState::Active);
            return sys::MessageNone{};
        });

        connect(typeid(cellular::CallMissedNotification), [&]([[maybe_unused]] sys::Message *request) {
            callModel->setState(app::call::CallState::Missed);
            app::manager::Controller::switchBack(this);
            return sys::MessageNone{};
        });

        connect(typeid(cellular::CallEndedNotification), [&]([[maybe_unused]] sys::Message *request) {
            callModel->setState(app::call::CallState::Ended);
            switchWindow(gui::window::name::call);
            return sys::MessageNone{};
        });

        connect(typeid(cellular::IsCallActive), [&]([[maybe_unused]] sys::Message *request) {
            return std::make_shared<cellular::IsCallActiveResponse>(callModel->getState() != call::CallState::None);
        });

        connect(typeid(cellular::CallStartedNotification), [&](sys::Message *request) {
            const auto message = static_cast<cellular::CallStartedNotification *>(request);
            callModel->setPhoneNumber(message->getNumber());
            callModel->setState(app::call::CallState::Outgoing);
            switchWindow(gui::window::name::call);
            return sys::MessageNone{};
        });

        connect(typeid(AudioRoutingNotification), [this](sys::Message *request) {
            const auto message = static_cast<AudioRoutingNotification *>(request);
            return handleRoutingNotification(message);
        });

        createUserInterface();

        return ret;
    }

    sys::MessagePointer ApplicationCall::handleAppClose(sys::Message *msgl)
    {
        callModel->hangUpCall();
        return ApplicationCommon::handleAppClose(msgl);
    }

    void ApplicationCall::createUserInterface()
    {
        windowsFactory.attach(
            gui::window::name::enter_number, [](ApplicationCommon *app, [[maybe_unused]] const std::string &name) {
                return std::make_unique<gui::EnterNumberWindow>(app, static_cast<ApplicationCall *>(app));
            });
        windowsFactory.attach(gui::window::name::call,
                              [this](ApplicationCommon *app, [[maybe_unused]] const std::string &name) {
                                  return std::make_unique<gui::CallWindow>(app, *callPresenter);
                              });
        windowsFactory.attach(
            gui::window::name::emergency_call, [](ApplicationCommon *app, [[maybe_unused]] const std::string &name) {
                return std::make_unique<gui::EmergencyCallWindow>(app, static_cast<ApplicationCall *>(app));
            });
        windowsFactory.attach(gui::window::name::call_dialog_confirm,
                              [](ApplicationCommon *app, const std::string &name) {
                                  return std::make_unique<gui::DialogConfirm>(app, name);
                              });
        attachPopups({gui::popup::ID::Volume,
                      gui::popup::ID::Tethering,
                      gui::popup::ID::PhoneModes,
                      gui::popup::ID::SimLock,
                      gui::popup::ID::Alarm}); // Alarm pop-up is blocked during phone call - logic is on Alarm side
    }

    bool ApplicationCall::showNotification(std::function<bool()> action,
                                           const std::string &icon,
                                           const std::string &text)
    {
        auto metaData =
            std::make_unique<gui::DialogMetadataMessage>(gui::DialogMetadata{"", icon, text, "", std::move(action)});
        switchWindow(gui::window::name::call_dialog_confirm, gui::ShowMode::GUI_SHOW_INIT, std::move(metaData));
        return true;
    }

    auto ApplicationCall::showNotificationAndRestartCallFlow(NotificationType type, const std::string &text) -> bool
    {
        const auto buttonAction = [=]() -> bool { return conditionalReturnToPreviousView(); };
        const auto icon         = type == NotificationType::Info ? "info_128px_W_G" : "fail_128px_W_G";
        callModel->clear();
        return showNotification(buttonAction, icon, text);
    }

    void ApplicationCall::destroyUserInterface()
    {}

    void ApplicationCall::handleEmergencyCallEvent(const std::string &number)
    {
        const auto state = callModel->getState();
        if (state != call::CallState::None) {
            LOG_WARN("Cannot call in %s state", c_str(state));
            return;
        }

        if (DBServiceAPI::IsContactInEmergency(this, utils::PhoneNumber(number).getView())) {
            CellularServiceAPI::DialNumber(this, utils::PhoneNumber(number));
            return;
        }

        CellularServiceAPI::DialEmergencyNumber(this, utils::PhoneNumber(number));
    }

    void ApplicationCall::handleCallEvent(const std::string &number, ExternalRequest isExternalRequest)
    {
        const auto state = callModel->getState();
        if (state != call::CallState::None) {
            LOG_WARN("Cannot call in %s state", c_str(state));
            return;
        }
        CellularServiceAPI::DialNumber(this, utils::PhoneNumber(number));
        externalRequest = isExternalRequest;
    }

    void ApplicationCall::handleAddContactEvent(const std::string &number)
    {
        LOG_INFO("Add contact information");

        auto numberView    = utils::PhoneNumber(number).getView();
        auto searchResults = DBServiceAPI::MatchContactByPhoneNumber(this, numberView);
        if (searchResults != nullptr && !searchResults->isTemporary()) {
            LOG_INFO("Found contact matching (non temporary) search num : contact ID %" PRIu32, searchResults->ID);
            auto data                     = std::make_unique<PhonebookItemData>(std::move(searchResults));
            data->nameOfSenderApplication = GetName();
            app::manager::Controller::sendAction(this, app::manager::actions::EditContact, std::move(data));
        }
        else {
            auto contactRecord = std::make_shared<ContactRecord>();
            contactRecord->numbers.emplace_back(std::move(numberView));

            auto data                        = std::make_unique<PhonebookItemData>(std::move(contactRecord));
            data->nameOfSenderApplication    = GetName();
            data->ignoreCurrentWindowOnStack = true;
            app::manager::Controller::sendAction(
                this, manager::actions::AddContact, std::move(data), manager::OnSwitchBehaviour::RunInBackground);
        }
    }

    sys::MessagePointer ApplicationCall::handleRoutingNotification(AudioRoutingNotification *message)
    {
        if (const auto window = getCurrentWindow(); window->getName() == gui::window::name::call) {
            const auto currentRouting = message->profileType;
            callPresenter->processCurrentRouting(currentRouting);
        }
        return sys::MessageNone{};
    }
} // namespace app