~aleteoryx/muditaos

ref: 80bdde9c9629b946454439871b77dee94d57ef75 muditaos/module-services/service-desktop/endpoints/calendarEvents/CalendarEventsHelper.cpp -rw-r--r-- 12.8 KiB
80bdde9c — Marcin Smoczyński ADd changelog for v0.53.1 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
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "EventsRecord.hpp"
#include "CalendarEventsHelper.hpp"
#include "Common/Query.hpp"
#include <parser/ParserUtils.hpp>
#include "Service/Common.hpp"
#include <service-db/DBServiceAPI.hpp>
#include "log/log.hpp"
#include "json/json11.hpp"
#include <queries/calendar/QueryEventsGetAll.hpp>
#include <queries/calendar/QueryEventsGet.hpp>
#include <queries/calendar/QueryEventsAdd.hpp>
#include <queries/calendar/QueryEventsEdit.hpp>
#include <queries/calendar/QueryEventsEditICS.hpp>
#include <queries/calendar/QueryEventsRemove.hpp>
#include <queries/calendar/QueryEventsRemoveICS.hpp>
#include <queries/calendar/QueryEventsGetAllLimited.hpp>
#include <variant>

namespace parserFSM
{
    namespace ical
    {
        namespace duration
        {
            const inline auto five_minutes_before    = Duration(0, 0, 0, 5);
            const inline auto fifteen_minutes_before = Duration(0, 0, 0, 15);
            const inline auto thirty_minutes_before  = Duration(0, 0, 0, 30);
            const inline auto one_hour_before        = Duration(0, 0, 1, 0);
            const inline auto two_hours_before       = Duration(0, 0, 2, 0);
            const inline auto one_day_before         = Duration(0, 1, 0, 0);
            const inline auto two_days_before        = Duration(0, 2, 0, 0);
            const inline auto one_week_before        = Duration(1, 0, 0, 0);
            const inline auto event_time             = Duration(0, 0, 0, 0);
        } // namespace duration
    }     // namespace ical

    namespace json::calendar::events
    {
        constexpr inline auto UID         = "UID";
        constexpr inline auto data        = "data";
        constexpr inline auto offset      = "offset";
        constexpr inline auto limit       = "limit";
        constexpr inline auto count       = "count";
        constexpr inline auto total_count = "total_count";

        constexpr inline auto providers = "providers";
        namespace provider
        {
            constexpr inline auto type    = "provider_type";
            constexpr inline auto id      = "provider_id";
            constexpr inline auto iCalUid = "provider_iCalUid";
        } // namespace provider
    }     // namespace json::calendar::events
} // namespace parserFSM
using namespace parserFSM;

auto CalendarEventsHelper::frequencyFromCustomRepeat(Repeat repeat) const -> Frequency
{
    return Frequency(static_cast<uint32_t>(repeat));
}

auto CalendarEventsHelper::recurrenceRuleFrom(Repeat repeat) const -> RecurrenceRule
{
    if (repeat > Repeat::yearly) {
        uint32_t count = 1, interval = 1;
        return RecurrenceRule(frequencyFromCustomRepeat(repeat), count, interval);
    }
    switch (repeat) {
    case Repeat::never: {
        return RecurrenceRule();
    }
    case Repeat::daily: {
        uint32_t count = 7, interval = 1;
        return RecurrenceRule(Frequency::daily, count, interval);
    }
    case Repeat::weekly: {
        uint32_t count = 4, interval = 1;
        return RecurrenceRule(Frequency::weekly, count, interval);
    }
    case Repeat::biweekly: {
        uint32_t count = 4, interval = 2;
        return RecurrenceRule(Frequency::weekly, count, interval);
    }
    case Repeat::monthly: {
        uint32_t count = 12, interval = 1;
        return RecurrenceRule(Frequency::monthly, count, interval);
    }
    case Repeat::yearly: {
        uint32_t count = 4, interval = 1;
        return RecurrenceRule(Frequency::yearly, count, interval);
    }
    }

    return RecurrenceRule();
}

auto CalendarEventsHelper::alarmFrom(Reminder reminder) const -> Alarm
{
    switch (reminder) {
    case Reminder::never: {
        return Alarm();
    }
    case Reminder::five_min_before: {
        auto beforeEvent = ical::duration::five_minutes_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::fifteen_min_before: {
        auto beforeEvent = ical::duration::fifteen_minutes_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::thirty_min_before: {
        auto beforeEvent = ical::duration::thirty_minutes_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::one_hour_before: {
        auto beforeEvent = ical::duration::one_hour_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::two_hour_before: {
        auto beforeEvent = ical::duration::two_hours_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::one_day_before: {
        auto beforeEvent = ical::duration::one_day_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::two_days_before: {
        auto beforeEvent = ical::duration::two_days_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::one_week_before: {
        auto beforeEvent = ical::duration::one_week_before;
        return Alarm(beforeEvent, Action::display);
    }
    case Reminder::event_time: {
        auto beforeEvent = ical::duration::event_time;
        return Alarm(beforeEvent, Action::display);
    }
    }
    return Alarm();
}

auto CalendarEventsHelper::icalEventFrom(const EventsRecord &record) const -> ICalEvent
{

    auto event = Event(record.title, record.date_from, record.date_till, record.UID);
    auto alarm = alarmFrom(Reminder(record.reminder));
    auto rrule = recurrenceRuleFrom(Repeat(record.repeat));
    return ICalEvent{event, alarm, rrule};
}

auto CalendarEventsHelper::requestDataFromDB(Context &context) -> sys::ReturnCodes
{
    auto obj        = context.getBody();
    uint32_t offset = obj[json::calendar::events::offset].int_value();
    uint32_t limit  = obj[json::calendar::events::limit].int_value();
    auto query      = std::make_unique<db::query::events::GetAllLimited>(offset, limit);

    auto listener = std::make_unique<db::EndpointListener>(
        [&](db::QueryResult *result, Context context) {
            if (auto EventsResult = dynamic_cast<db::query::events::GetAllLimitedResult *>(result)) {
                auto records        = EventsResult->getResult();
                uint32_t totalCount = EventsResult->getCountResult();
                auto parser         = std::make_unique<ParserICS>();
                std::vector<ICalEvent> icalEvents;
                for (auto rec : records) {
                    icalEvents.push_back(icalEventFrom(rec));
                }
                parser->importEvents(icalEvents);
                auto jsonObj =
                    json11::Json::object({{json::calendar::events::data, parser->getIcsData()},
                                          {json::calendar::events::count, std::to_string(records.size())},
                                          {json::calendar::events::total_count, std::to_string(totalCount)}});

                context.setResponseBody(jsonObj);
                MessageHandler::putToSendQueue(context.createSimpleResponse());
                return true;
            }
            return false;
        },
        context);

    query->setQueryListener(std::move(listener));
    auto ret = DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));

    if (ret) {
        return sys::ReturnCodes::Success;
    }
    else {
        return sys::ReturnCodes::Failure;
    }
}

auto CalendarEventsHelper::frequencyToCustomRepeat(Frequency freq) const -> uint32_t
{
    return static_cast<uint32_t>(freq);
}

auto CalendarEventsHelper::repeatFrom(RecurrenceRule &rrule) const -> Repeat
{
    auto freq = rrule.getFrequencyValue();
    switch (freq) {
    case Frequency::daily: {
        return Repeat::daily;
    }
    case Frequency::weekly: {
        if (rrule.getIntervalValue() == 1) {
            return Repeat::weekly;
        }
        else if (rrule.getIntervalValue() == 2) {
            return Repeat::biweekly;
        }
        else {
            LOG_ERROR("Interval invalid");
            return Repeat::never;
        }
    }
    case Frequency::monthly: {
        return Repeat::monthly;
    }
    case Frequency::yearly: {
        return Repeat::yearly;
    }
    case Frequency::invalid: {
        LOG_ERROR("Frequency invalid");
        return Repeat::never;
    }
    }
    return Repeat::never;
}

auto CalendarEventsHelper::eventsRecordFrom(ICalEvent &icalEvent) const -> EventsRecord
{

    auto record      = EventsRecord();
    record.UID       = icalEvent.event.getUID();
    record.title     = icalEvent.event.getSummary();
    record.date_from = icalEvent.event.getDTStartTimePoint();
    record.date_till = icalEvent.event.getDTEndTimePoint();
    if (icalEvent.rrule.getFrequencyValue() > Frequency::yearly) {
        record.repeat = frequencyToCustomRepeat(icalEvent.rrule.getFrequencyValue());
    }
    record.repeat   = static_cast<uint32_t>(repeatFrom(icalEvent.rrule));
    record.reminder = icalEvent.alarm.getTriggerValue().getDurationInMinutes();

    return record;
}

auto CalendarEventsHelper::createDBEntry(Context &context) -> sys::ReturnCodes
{
    auto parser = std::make_shared<ParserICS>();
    parser->loadData(context.getBody()[json::calendar::events::data].string_value());
    auto icalEvents = parser->exportEvents();

    bool ret = true;
    for (auto event : icalEvents) {
        auto UID    = event.event.getUID();
        auto record = eventsRecordFrom(event);
        auto query  = std::make_unique<db::query::events::Add>(record);

        auto listener = std::make_unique<db::EndpointListener>(
            [=](db::QueryResult *result, Context context) {
                if (auto EventResult = dynamic_cast<db::query::events::AddResult *>(result)) {

                    auto jsonObj = json11::Json::object(
                        {{json::calendar::events::data, parser->getIcsData()}, {json::calendar::events::UID, UID}});

                    context.setResponseBody(jsonObj);
                    context.setResponseStatus(EventResult->getResult() ? http::Code::OK
                                                                       : http::Code::InternalServerError);

                    MessageHandler::putToSendQueue(context.createSimpleResponse());
                    return true;
                }
                return false;
            },
            context);

        query->setQueryListener(std::move(listener));
        ret = ret && DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));
    }

    if (ret) {
        return sys::ReturnCodes::Success;
    }
    else {
        return sys::ReturnCodes::Failure;
    }
}

auto CalendarEventsHelper::updateDBEntry(Context &context) -> sys::ReturnCodes
{
    auto parser = std::make_unique<ParserICS>();
    parser->loadData(context.getBody()[json::calendar::events::data].string_value());
    auto icalEvents = parser->exportEvents();

    bool ret = true;
    for (auto event : icalEvents) {

        auto record   = eventsRecordFrom(event);
        auto query    = std::make_unique<db::query::events::EditICS>(record);
        auto listener = std::make_unique<db::EndpointListener>(
            [](db::QueryResult *result, Context context) {
                if (auto EventResult = dynamic_cast<db::query::events::EditICSResult *>(result)) {
                    context.setResponseStatus(EventResult->getResult() ? http::Code::OK
                                                                       : http::Code::InternalServerError);
                    MessageHandler::putToSendQueue(context.createSimpleResponse());
                    return true;
                }
                return false;
            },
            context);

        query->setQueryListener(std::move(listener));
        ret = ret && DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));
    }
    if (ret) {
        return sys::ReturnCodes::Success;
    }
    else {
        return sys::ReturnCodes::Failure;
    }
}

auto CalendarEventsHelper::deleteDBEntry(Context &context) -> sys::ReturnCodes
{
    auto UID      = context.getBody()[json::calendar::events::UID].string_value();
    auto query    = std::make_unique<db::query::events::RemoveICS>(UID);
    auto listener = std::make_unique<db::EndpointListener>(
        [=](db::QueryResult *result, Context context) {
            if (auto EventResult = dynamic_cast<db::query::events::RemoveICSResult *>(result)) {
                context.setResponseStatus(EventResult->getResult() ? http::Code::OK : http::Code::InternalServerError);
                MessageHandler::putToSendQueue(context.createSimpleResponse());
                return true;
            }
            return false;
        },
        context);

    query->setQueryListener(std::move(listener));
    auto ret = DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));

    if (ret) {
        return sys::ReturnCodes::Success;
    }
    else {
        return sys::ReturnCodes::Failure;
    }
}