~aleteoryx/muditaos

ref: ed0d26dc47f77087e9f108ff6df7a6ce4913445d muditaos/module-services/service-desktop/endpoints/calendarEvents/CalendarEventsHelper.cpp -rw-r--r-- 18.7 KiB
ed0d26dc — Wojtek Cichon [EGD-6282] Add marketing-friendly test messages to Pure 4 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Copyright (c) 2017-2021, 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>
#include <utility>

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);
            const inline auto never                  = Duration(0, 0, 0, 0xFFFF);
        } // namespace duration
    }     // namespace ical

    namespace json::calendar
    {
        constexpr inline auto events = "calendar_events";
        namespace event
        {
            constexpr inline auto vevent = "VEVENT";

            constexpr inline auto uid     = "UID";
            constexpr inline auto summary = "SUMMARY";
            constexpr inline auto dtstart = "DTSTART";
            constexpr inline auto dtend   = "DTEND";

            namespace recurrence_rule
            {
                constexpr inline auto rrule = "RRULE";

                constexpr inline auto frequency = "FREQ";
                constexpr inline auto count     = "COUNT";
                constexpr inline auto interval  = "INTERVAL";
            } // namespace recurrence_rule

            namespace alarm
            {
                constexpr inline auto valarm = "VALARM";

                constexpr inline auto trigger = "TRIGGER";
                constexpr inline auto action  = "ACTION";
            } // namespace alarm

            namespace provider
            {
                constexpr inline auto provider = "provider";

                constexpr inline auto type    = "type";
                constexpr inline auto id      = "id";
                constexpr inline auto iCalUid = "iCalUid";
            } // namespace provider
        }     // namespace event
        constexpr inline auto limit  = "limit";
        constexpr inline auto offset = "offset";

    } // namespace json::calendar
} // namespace parserFSM
using namespace parserFSM;

auto CalendarEventsHelper::isICalEventValid(const ICalEvent &icalEvent) const -> bool
{
    if (!icalEvent.event.isValid) {
        LOG_ERROR("Ical event invalid!");
        return false;
    }
    if (!icalEvent.alarm.isValid) {
        LOG_ERROR("Ical alarm invalid!");
        return false;
    }
    if (!icalEvent.rrule.isValid) {
        LOG_ERROR("Ical recurrence rule invalid!");
        return false;
    }
    return true;
}

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: {
        auto beforeEvent = ical::duration::never;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::five_min_before: {
        auto beforeEvent = ical::duration::five_minutes_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::fifteen_min_before: {
        auto beforeEvent = ical::duration::fifteen_minutes_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::thirty_min_before: {
        auto beforeEvent = ical::duration::thirty_minutes_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::one_hour_before: {
        auto beforeEvent = ical::duration::one_hour_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::two_hour_before: {
        auto beforeEvent = ical::duration::two_hours_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::one_day_before: {
        auto beforeEvent = ical::duration::one_day_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::two_days_before: {
        auto beforeEvent = ical::duration::two_days_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::one_week_before: {
        auto beforeEvent = ical::duration::one_week_before;
        return Alarm(beforeEvent, Action::none);
    }
    case Reminder::event_time: {
        auto beforeEvent = ical::duration::event_time;
        return Alarm(beforeEvent, Action::none);
    }
    }
    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::eventJsonObjectFrom(const EventsRecord &record) const -> json11::Json
{
    auto icalEvent = icalEventFrom(record);
    if (!isICalEventValid(icalEvent)) {
        LOG_ERROR("Bad event record formatting  (Event UID: %s)", icalEvent.event.getUID().c_str());
    }

    auto rruleObj = json11::Json::object{
        {json::calendar::event::recurrence_rule::frequency, icalEvent.rrule.getFrequencyString().c_str()},
        {json::calendar::event::recurrence_rule::count, icalEvent.rrule.getCountString().c_str()},
        {json::calendar::event::recurrence_rule::interval, icalEvent.rrule.getIntervalString().c_str()}};

    auto alarmObj =
        json11::Json::object{{json::calendar::event::alarm::trigger, icalEvent.alarm.getTriggerString().c_str()},
                             {json::calendar::event::alarm::action, icalEvent.alarm.getActionString().c_str()}};

    auto providerObj =
        json11::Json::object{{json::calendar::event::provider::type, record.provider_type.c_str()},
                             {json::calendar::event::provider::id, record.provider_id.c_str()},
                             {json::calendar::event::provider::iCalUid, record.provider_iCalUid.c_str()}};

    auto eventObj = json11::Json::object{{json::calendar::event::dtend, icalEvent.event.getDTEndString().c_str()},
                                         {json::calendar::event::dtstart, icalEvent.event.getDTStartString().c_str()},
                                         {json::calendar::event::summary, icalEvent.event.getSummary().c_str()},
                                         {json::calendar::event::uid, icalEvent.event.getUID().c_str()},
                                         {json::calendar::event::recurrence_rule::rrule, rruleObj},
                                         {json::calendar::event::alarm::valarm, alarmObj},
                                         {json::calendar::event::provider::provider, providerObj}};

    return eventObj;
}

auto CalendarEventsHelper::requestDataFromDB(Context &context) -> sys::ReturnCodes
{
    try {
        auto &ctx          = dynamic_cast<PagedContext &>(context);
        std::size_t limit  = ctx.getBody()[json::calendar::limit].int_value();
        std::size_t offset = ctx.getBody()[json::calendar::offset].int_value();
        ctx.setRequestedLimit(limit);
        ctx.setRequestedOffset(offset);
        auto query = std::make_unique<db::query::events::GetAllLimited>(offset, std::min(ctx.getPageSize(), limit));

        auto listener = std::make_unique<db::EndpointListenerWithPages>(
            [&](db::QueryResult *result, PagedContext &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;
                    context.setTotalCount(totalCount);
                    auto eventsArray = json11::Json::array();

                    for (const auto &rec : records) {
                        auto eventObject = eventJsonObjectFrom(rec);
                        eventsArray.emplace_back(eventObject);
                    }
                    context.setResponseBody(eventsArray);
                    MessageHandler::putToSendQueue(context.createSimpleResponse(json::calendar::events));

                    return true;
                }
                return false;
            },
            ctx);

        query->setQueryListener(std::move(listener));
        DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));
    }
    catch (const std::exception &e) {
        LOG_ERROR("%s", e.what());
        return sys::ReturnCodes::Failure;
    }
    return sys::ReturnCodes::Success;
}

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::never: {
        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::ICalEventFromJson(const json11::Json &eventObj) const -> ICalEvent
{
    ICalEvent icalEvent;
    icalEvent.event.setUID(eventObj[json::calendar::event::uid].string_value());
    icalEvent.event.setSummary(eventObj[json::calendar::event::summary].string_value());
    icalEvent.event.setDTStart(eventObj[json::calendar::event::dtstart].string_value());
    icalEvent.event.setDTEnd(eventObj[json::calendar::event::dtend].string_value());

    icalEvent.rrule.setFrequency(
        eventObj[json::calendar::event::recurrence_rule::rrule][json::calendar::event::recurrence_rule::frequency]
            .string_value());
    icalEvent.rrule.setCount(
        eventObj[json::calendar::event::recurrence_rule::rrule][json::calendar::event::recurrence_rule::count]
            .string_value());
    icalEvent.rrule.setInterval(
        eventObj[json::calendar::event::recurrence_rule::rrule][json::calendar::event::recurrence_rule::interval]
            .string_value());

    icalEvent.alarm.setTrigger(
        eventObj[json::calendar::event::alarm::valarm][json::calendar::event::alarm::trigger].string_value());
    icalEvent.alarm.setAction(
        eventObj[json::calendar::event::alarm::valarm][json::calendar::event::alarm::action].string_value());

    auto record = eventsRecordFrom(icalEvent);

    return icalEvent;
}

auto CalendarEventsHelper::createDBEntry(Context &context) -> sys::ReturnCodes
{
    const auto eventsJsonObj   = context.getBody();
    const auto eventsJsonArray = eventsJsonObj[json::calendar::events].array_items();
    bool ret                   = true;
    for (const auto &event : eventsJsonArray) {

        auto icalEvent = ICalEventFromJson(event);

        if (!isICalEventValid(icalEvent)) {
            context.setResponseStatus(http::Code::BadRequest);
            MessageHandler::putToSendQueue(context.createSimpleResponse());
            return sys::ReturnCodes::Failure;
        }

        auto record = eventsRecordFrom(icalEvent);
        if (record.UID.empty()) {
            record.UID   = createUID();
            auto jsonObj = json11::Json::object({{json::calendar::event::uid, record.UID}});
            context.setResponseBody(jsonObj);
        }
        else {
            LOG_ERROR("UID should not be recieved in put event endpoint. Recieved UID: %s", record.UID.c_str());
            context.setResponseStatus(http::Code::BadRequest);
            MessageHandler::putToSendQueue(context.createSimpleResponse());
            return sys::ReturnCodes::Failure;
        }

        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)) {

                    context.setResponseStatus(eventResult->getResult() ? http::Code::OK
                                                                       : http::Code::InternalServerError);

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

        query->setQueryListener(std::move(listener));
        const auto [succeed, _] =
            DBServiceAPI::GetQuery(ownerServicePtr, db::Interface::Name::Events, std::move(query));
        ret = ret && succeed;
    }

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

auto CalendarEventsHelper::updateDBEntry(Context &context) -> sys::ReturnCodes
{
    auto eventsJsonObj = context.getBody();

    bool ret = true;
    for (const auto &event : eventsJsonObj[json::calendar::events].array_items()) {

        auto icalEvent = ICalEventFromJson(event);
        if (!isICalEventValid(icalEvent) || icalEvent.event.getUID().empty()) {
            context.setResponseStatus(http::Code::BadRequest);
            MessageHandler::putToSendQueue(context.createSimpleResponse());
            return sys::ReturnCodes::Failure;
        }

        auto record   = eventsRecordFrom(icalEvent);
        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::NoContent
                                                                       : http::Code::InternalServerError);
                    MessageHandler::putToSendQueue(context.createSimpleResponse());
                    return true;
                }
                return false;
            },
            context);

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

auto CalendarEventsHelper::deleteDBEntry(Context &context) -> sys::ReturnCodes
{
    auto UID      = context.getBody()[json::calendar::event::uid].string_value();
    auto checkUID = Event();
    checkUID.setUID(UID);
    if (!checkUID.isValid) {
        LOG_ERROR("Wrong UID format. Provided UID: %s", UID.c_str());
        context.setResponseStatus(http::Code::BadRequest);
        MessageHandler::putToSendQueue(context.createSimpleResponse());
        return sys::ReturnCodes::Failure;
    }
    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::NoContent
                                                                   : 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;
    }
}