/
googlecalendarsyncadaptor.cpp
2622 lines (2436 loc) · 137 KB
/
googlecalendarsyncadaptor.cpp
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2013 - 2019 Jolla Ltd.
** Copyright (C) 2020 Open Mobile Platform LLC.
**
** This program/library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public License
** version 2.1 as published by the Free Software Foundation.
**
** This program/library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this program/library; if not, write to the Free
** Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
** 02110-1301 USA
**
****************************************************************************/
#include "googlecalendarsyncadaptor.h"
#include "googlecalendarincidencecomparator.h"
#include "trace.h"
#include <QtCore/QUrlQuery>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QByteArray>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonDocument>
#include <QtCore/QSettings>
#include <QtCore/QSet>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <Accounts/Account>
#include <Accounts/Manager>
#include <Accounts/Service>
//----------------------------------------------
#define QDATEONLY_FORMAT "yyyy-MM-dd"
#define RFC5545_FORMAT "yyyyMMddThhmmssZ"
#define RFC5545_FORMAT_NTZC "yyyyMMddThhmmss"
#define RFC5545_QDATE_FORMAT "yyyyMMdd"
namespace {
const int GOOGLE_CAL_SYNC_PLUGIN_VERSION = 3;
const QByteArray NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY = QByteArrayLiteral("syncToken");
const QByteArray NOTEBOOK_SERVER_ID_PROPERTY = QByteArrayLiteral("calendarServerId");
const QByteArray NOTEBOOK_EMAIL_PROPERTY = QByteArrayLiteral("userPrincipalEmail");
void errorDumpStr(const QString &str)
{
// Dump the entire string to the log.
// Note that the log cannot handle newlines,
// so we separate the string into chunks.
Q_FOREACH (const QString &chunk, str.split('\n', QString::SkipEmptyParts)) {
SOCIALD_LOG_ERROR(chunk);
}
}
void traceDumpStr(const QString &str)
{
// 8 is the minimum log level for TRACE logs
// as defined in Buteo's LogMacros.h
if (Buteo::Logger::instance()->getLogLevel() < 8) {
return;
}
// Dump the entire string to the log.
// Note that the log cannot handle newlines,
// so we separate the string into chunks.
Q_FOREACH (const QString &chunk, str.split('\n', QString::SkipEmptyParts)) {
SOCIALD_LOG_TRACE(chunk);
}
}
// returns true if the ghost-event cleanup sync has been performed.
bool ghostEventCleanupPerformed()
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(PRIVILEGED_DATA_DIR)
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
return settingsFile.value(QString::fromLatin1("cleaned"), QVariant::fromValue<bool>(false)).toBool();
}
void setGhostEventCleanupPerformed()
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(PRIVILEGED_DATA_DIR)
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
settingsFile.setValue(QString::fromLatin1("cleaned"), QVariant::fromValue<bool>(true));
settingsFile.sync();
}
void uniteIncidenceLists(const KCalendarCore::Incidence::List &first, KCalendarCore::Incidence::List *second)
{
int originalSecondSize = second->size();
bool foundMatch = false;
Q_FOREACH (KCalendarCore::Incidence::Ptr inc, first) {
foundMatch = false;
for (int i = 0; i < originalSecondSize; ++i) {
if (inc->uid() == second->at(i)->uid() && inc->recurrenceId() == second->at(i)->recurrenceId()) {
// found a match
foundMatch = true;
break;
}
}
if (!foundMatch) {
second->append(inc);
}
}
}
QString gCalEventId(KCalendarCore::Incidence::Ptr event)
{
// we abuse the comments field to store our gcal-id.
// we should use a custom property, but those are deleted on incidence deletion.
const QStringList &comments(event->comments());
Q_FOREACH (const QString &comment, comments) {
if (comment.startsWith("jolla-sociald:gcal-id:")) {
return comment.mid(22);
}
}
return QString();
}
void setGCalEventId(KCalendarCore::Incidence::Ptr event, const QString &id)
{
// we abuse the comments field to store our gcal-id.
// we should use a custom property, but those are deleted on incidence deletion.
const QStringList &comments(event->comments());
Q_FOREACH (const QString &comment, comments) {
if (comment.startsWith("jolla-sociald:gcal-id:")) {
// remove any existing gcal-id comment.
if (!event->removeComment(comment)) {
SOCIALD_LOG_DEBUG("Unable to remove comment:" << comment);
}
break;
}
}
event->addComment(QStringLiteral("jolla-sociald:gcal-id:%1").arg(id));
}
void setRemoteUidCustomField(KCalendarCore::Incidence::Ptr event, const QString &uid, const QString &id)
{
// store it also in a custom property purely for invitation lookup purposes.
if (!uid.isEmpty()) {
event->setNonKDECustomProperty("X-SAILFISHOS-REMOTE-UID", uid.toUtf8());
} else {
// Google Calendar invites are sent as invitations with uid suffixed with @google.com.
if (id.endsWith(QLatin1String("@google.com"), Qt::CaseInsensitive)) {
event->setNonKDECustomProperty("X-SAILFISHOS-REMOTE-UID", id.toUtf8());
} else {
QString suffixedId = id;
suffixedId.append(QLatin1String("@google.com"));
event->setNonKDECustomProperty("X-SAILFISHOS-REMOTE-UID", suffixedId.toUtf8());
}
}
}
QString gCalETag(KCalendarCore::Incidence::Ptr event)
{
return event->customProperty("jolla-sociald", "gcal-etag");
}
void setGCalETag(KCalendarCore::Incidence::Ptr event, const QString &etag)
{
// note: custom properties are purged on incidence deletion.
event->setCustomProperty("jolla-sociald", "gcal-etag", etag);
}
QList<QDateTime> datetimesFromExRDateStr(const QString &exrdatestr, bool *isDateOnly)
{
// possible forms:
// RDATE:19970714T123000Z
// RDATE;VALUE=DATE-TIME:19970714T123000Z
// RDATE;VALUE=DATE-TIME:19970714T123000Z,19970715T123000Z
// RDATE;TZID=America/New_York:19970714T083000
// RDATE;VALUE=PERIOD:19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H
// RDATE;VALUE=DATE:19970101,19970120
QList<QDateTime> retn;
QString str = exrdatestr;
*isDateOnly = false; // by default.
if (str.startsWith(QStringLiteral("exdate"), Qt::CaseInsensitive)) {
str.remove(0, 6);
} else if (str.startsWith(QStringLiteral("rdate"), Qt::CaseInsensitive)) {
str.remove(0, 5);
} else {
SOCIALD_LOG_ERROR("not an ex/rdate string:" << exrdatestr);
return retn;
}
if (str.startsWith(';')) {
str.remove(0,1);
if (str.startsWith("VALUE=DATE-TIME:", Qt::CaseInsensitive)) {
str.remove(0, 16);
QStringList dts = str.split(',');
Q_FOREACH (const QString &dtstr, dts) {
if (dtstr.endsWith('Z')) {
// UTC
QDateTime dt = QDateTime::fromString(dtstr, RFC5545_FORMAT);
dt.setTimeSpec(Qt::UTC);
retn.append(dt);
} else {
// Floating time
QDateTime dt = QDateTime::fromString(dtstr, RFC5545_FORMAT_NTZC);
dt.setTimeSpec(Qt::LocalTime);
retn.append(dt);
}
}
} else if (str.startsWith("VALUE=DATE:", Qt::CaseInsensitive)) {
str.remove(0, 11);
QStringList dts = str.split(',');
Q_FOREACH(const QString &dstr, dts) {
QDate date = QLocale::c().toDate(dstr, RFC5545_QDATE_FORMAT);
retn.append(QDateTime(date));
}
} else if (str.startsWith("VALUE=PERIOD:", Qt::CaseInsensitive)) {
SOCIALD_LOG_ERROR("unsupported parameter in ex/rdate string:" << exrdatestr);
// TODO: support PERIOD formats, or just switch to CalDAV for Google sync...
} else if (str.startsWith("TZID=") && str.contains(':')) {
str.remove(0, 5);
QString tzidstr = str.mid(0, str.indexOf(':')); // something like: "Australia/Brisbane"
QTimeZone tz(tzidstr.toUtf8());
str.remove(0, tzidstr.size()+1);
QStringList dts = str.split(',');
Q_FOREACH (const QString &dtstr, dts) {
QDateTime dt = QDateTime::fromString(dtstr, RFC5545_FORMAT_NTZC);
if (!dt.isValid()) {
// try parsing from alternate formats
dt = QDateTime::fromString(dtstr, Qt::ISODate);
}
if (!dt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
if (tz.isValid()) {
dt.setTimeZone(tz);
} else {
dt.setTimeSpec(Qt::LocalTime);
SOCIALD_LOG_INFO("WARNING: unknown tzid:" << tzidstr << "; assuming clock-time instead!");
}
retn.append(dt);
}
}
} else {
SOCIALD_LOG_ERROR("invalid parameter in ex/rdate string:" << exrdatestr);
}
} else if (str.startsWith(':')) {
str.remove(0,1);
QStringList dts = str.split(',');
Q_FOREACH (const QString &dtstr, dts) {
if (dtstr.endsWith('Z')) {
// UTC
QDateTime dt = QDateTime::fromString(dtstr, RFC5545_FORMAT);
if (!dt.isValid()) {
// try parsing from alternate formats
dt = QDateTime::fromString(dtstr, Qt::ISODate);
}
if (!dt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
// parsed successfully
dt.setTimeSpec(Qt::UTC);
retn.append(dt);
}
} else {
// Floating time
QDateTime dt = QDateTime::fromString(dtstr, RFC5545_FORMAT_NTZC);
if (!dt.isValid()) {
// try parsing from alternate formats
dt = QDateTime::fromString(dtstr, Qt::ISODate);
}
if (!dt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
// parsed successfully
dt.setTimeSpec(Qt::LocalTime);
retn.append(dt);
}
}
}
} else {
SOCIALD_LOG_ERROR("not a valid ex/rdate string:" << exrdatestr);
}
return retn;
}
QJsonArray recurrenceArray(KCalendarCore::Event::Ptr event, KCalendarCore::ICalFormat &icalFormat, const QList<QDateTime> &exceptions)
{
QJsonArray retn;
// RRULE
KCalendarCore::Recurrence *kcalRecurrence = event->recurrence();
Q_FOREACH (KCalendarCore::RecurrenceRule *rrule, kcalRecurrence->rRules()) {
QString rruleStr = icalFormat.toString(rrule);
rruleStr.replace("\r\n", "");
retn.append(QJsonValue(rruleStr));
}
// EXRULE
Q_FOREACH (KCalendarCore::RecurrenceRule *exrule, kcalRecurrence->exRules()) {
QString exruleStr = icalFormat.toString(exrule);
exruleStr.replace("RRULE", "EXRULE");
exruleStr.replace("\r\n", "");
retn.append(QJsonValue(exruleStr));
}
// RDATE (date)
QString rdates;
Q_FOREACH (const QDate &rdate, kcalRecurrence->rDates()) {
rdates.append(QLocale::c().toString(rdate, RFC5545_QDATE_FORMAT));
rdates.append(',');
}
if (rdates.size()) {
rdates.chop(1); // trailing comma
retn.append(QJsonValue(QString::fromLatin1("RDATE;VALUE=DATE:%1").arg(rdates)));
}
// RDATE (date-time)
QString rdatetimes;
Q_FOREACH (const QDateTime &rdatetime, kcalRecurrence->rDateTimes()) {
if (rdatetime.timeSpec() == Qt::LocalTime) {
rdatetimes.append(rdatetime.toString(RFC5545_FORMAT_NTZC));
} else {
rdatetimes.append(rdatetime.toUTC().toString(RFC5545_FORMAT));
}
rdatetimes.append(',');
}
if (rdatetimes.size()) {
rdatetimes.chop(1); // trailing comma
retn.append(QJsonValue(QString::fromLatin1("RDATE;VALUE=DATE-TIME:%1").arg(rdatetimes)));
}
// EXDATE (date)
QString exdates;
Q_FOREACH (const QDate &exdate, kcalRecurrence->exDates()) {
// mkcal adds an EXDATE for each exception event, whereas Google does not
// So we only include the EXDATE if there's no exception associated with it
if (!exceptions.contains(QDateTime(exdate))) {
exdates.append(QLocale::c().toString(exdate, RFC5545_QDATE_FORMAT));
exdates.append(',');
}
}
if (exdates.size()) {
exdates.chop(1); // trailing comma
retn.append(QJsonValue(QString::fromLatin1("EXDATE;VALUE=DATE:%1").arg(exdates)));
}
// EXDATE (date-time)
QString exdatetimes;
Q_FOREACH (const QDateTime &exdatetime, kcalRecurrence->exDateTimes()) {
// mkcal adds an EXDATE for each exception event, whereas Google does not
// So we only include the EXDATE if there's no exception associated with it
if (!exceptions.contains(exdatetime)) {
if (exdatetime.timeSpec() == Qt::LocalTime) {
exdatetimes.append(exdatetime.toString(RFC5545_FORMAT_NTZC));
} else {
exdatetimes.append(exdatetime.toUTC().toString(RFC5545_FORMAT));
}
exdatetimes.append(',');
}
}
if (exdatetimes.size()) {
exdatetimes.chop(1); // trailing comma
retn.append(QJsonValue(QString::fromLatin1("EXDATE;VALUE=DATE-TIME:%1").arg(exdatetimes)));
}
return retn;
}
QDateTime parseRecurrenceId(const QJsonObject &originalStartTime)
{
QString recurrenceIdStr = originalStartTime.value(QLatin1String("dateTime")).toVariant().toString();
QString recurrenceIdTzStr = originalStartTime.value(QLatin1String("timeZone")).toVariant().toString();
QDateTime recurrenceId = QDateTime::fromString(recurrenceIdStr, Qt::ISODate);
if (!recurrenceIdTzStr.isEmpty()) {
recurrenceId = recurrenceId.toTimeZone(QTimeZone(recurrenceIdTzStr.toLatin1()));
}
return recurrenceId;
}
QDateTime parseDateTimeString(const QString &dateTimeStr)
{
QDateTime parsedTime = QDateTime::fromString(dateTimeStr, Qt::ISODate);
if (parsedTime.isNull()) {
qWarning() << "Unable to parse date time from string:" << dateTimeStr;
return QDateTime();
}
return parsedTime.toTimeZone(QTimeZone::systemTimeZone());
}
void extractCreatedAndUpdated(const QJsonObject &eventData,
QDateTime *created,
QDateTime *updated)
{
const QString createdStr = eventData.value(QLatin1String("created")).toVariant().toString();
const QString updatedStr = eventData.value(QLatin1String("updated")).toVariant().toString();
if (!createdStr.isEmpty()) {
*created = parseDateTimeString(createdStr);
}
if (!updatedStr.isEmpty()) {
*updated = parseDateTimeString(updatedStr);
}
}
void extractStartAndEnd(const QJsonObject &eventData,
bool *startExists,
bool *endExists,
bool *startIsDateOnly,
bool *endIsDateOnly,
bool *isAllDay,
QDateTime *start,
QDateTime *end)
{
*startIsDateOnly = false, *endIsDateOnly = false;
QString startTimeString, endTimeString;
QJsonObject startTimeData = eventData.value(QLatin1String("start")).toObject();
QJsonObject endTimeData = eventData.value(QLatin1String("end")).toObject();
if (!startTimeData.value(QLatin1String("date")).toVariant().toString().isEmpty()) {
*startExists = true;
*startIsDateOnly = true; // all-day event.
startTimeString = startTimeData.value(QLatin1String("date")).toVariant().toString();
} else if (!startTimeData.value(QLatin1String("dateTime")).toVariant().toString().isEmpty()) {
*startExists = true;
startTimeString = startTimeData.value(QLatin1String("dateTime")).toVariant().toString();
} else {
*startExists = false;
}
if (!endTimeData.value(QLatin1String("date")).toVariant().toString().isEmpty()) {
*endExists = true;
*endIsDateOnly = true; // all-day event.
endTimeString = endTimeData.value(QLatin1String("date")).toVariant().toString();
} else if (!endTimeData.value(QLatin1String("dateTime")).toVariant().toString().isEmpty()) {
*endExists = true;
endTimeString = endTimeData.value(QLatin1String("dateTime")).toVariant().toString();
} else {
*endExists = false;
}
if (*startExists) {
if (!*startIsDateOnly) {
*start = parseDateTimeString(startTimeString);
} else {
*start = QDateTime(QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT));
}
}
if (*endExists) {
if (!*endIsDateOnly) {
*end = parseDateTimeString(endTimeString);
} else {
// Special handling for all-day events is required.
if (*startExists && *startIsDateOnly) {
if (QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT)
== QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT)) {
// single-day all-day event
*endExists = false;
*isAllDay = true;
} else if (QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT)
== QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT).addDays(-1)) {
// Google will send a single-day all-day event has having an end-date
// of startDate+1 to conform to iCal spec. Hence, this is actually
// a single-day all-day event, despite the difference in end-date.
*endExists = false;
*isAllDay = true;
} else {
// multi-day all-day event.
// as noted above, Google will send all-day events as having an end-date
// of real-end-date+1 in order to conform to iCal spec (exclusive end dt).
*end = QDateTime(QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT).addDays(-1));
*isAllDay = true;
}
} else {
*end = QDateTime(QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT));
*isAllDay = false;
}
}
}
}
void extractRecurrence(const QJsonArray &recurrence, KCalendarCore::Event::Ptr event, KCalendarCore::ICalFormat &icalFormat, const QList<QDateTime> &exceptions)
{
KCalendarCore::Recurrence *kcalRecurrence = event->recurrence();
kcalRecurrence->clear(); // avoid adding duplicate recurrence information
for (int i = 0; i < recurrence.size(); ++i) {
QString ruleStr = recurrence.at(i).toString();
if (ruleStr.startsWith(QString::fromLatin1("rrule"), Qt::CaseInsensitive)) {
KCalendarCore::RecurrenceRule *rrule = new KCalendarCore::RecurrenceRule;
if (!icalFormat.fromString(rrule, ruleStr.mid(6))) {
SOCIALD_LOG_DEBUG("unable to parse RRULE information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
} else {
// Set the recurrence start to be the event start
rrule->setStartDt(event->dtStart());
kcalRecurrence->addRRule(rrule);
}
} else if (ruleStr.startsWith(QString::fromLatin1("exrule"), Qt::CaseInsensitive)) {
KCalendarCore::RecurrenceRule *exrule = new KCalendarCore::RecurrenceRule;
if (!icalFormat.fromString(exrule, ruleStr.mid(7))) {
SOCIALD_LOG_DEBUG("unable to parse EXRULE information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
} else {
kcalRecurrence->addExRule(exrule);
}
} else if (ruleStr.startsWith(QString::fromLatin1("rdate"), Qt::CaseInsensitive)) {
bool isDateOnly = false;
QList<QDateTime> rdatetimes = datetimesFromExRDateStr(ruleStr, &isDateOnly);
if (!rdatetimes.size()) {
SOCIALD_LOG_DEBUG("unable to parse RDATE information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
} else {
Q_FOREACH (const QDateTime &dt, rdatetimes) {
if (isDateOnly) {
kcalRecurrence->addRDate(dt.date());
} else {
kcalRecurrence->addRDateTime(dt);
}
}
}
} else if (ruleStr.startsWith(QString::fromLatin1("exdate"), Qt::CaseInsensitive)) {
bool isDateOnly = false;
QList<QDateTime> exdatetimes = datetimesFromExRDateStr(ruleStr, &isDateOnly);
if (!exdatetimes.size()) {
SOCIALD_LOG_DEBUG("unable to parse EXDATE information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
} else {
Q_FOREACH (const QDateTime &dt, exdatetimes) {
if (isDateOnly) {
kcalRecurrence->addExDate(dt.date());
} else {
kcalRecurrence->addExDateTime(dt);
}
}
}
} else {
SOCIALD_LOG_DEBUG("unknown recurrence information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
}
}
// Add an extra EXDATE for each exception event the calendar
// Google doesn't include these as EXDATE (following the spec) whereas mkcal does
for (const QDateTime exception : exceptions) {
if (exception.time().isNull()) {
kcalRecurrence->addExDate(exception.date());
} else {
kcalRecurrence->addExDateTime(exception);
}
}
}
void extractOrganizer(const QJsonObject &creatorObj, const QJsonObject &organizerObj, KCalendarCore::Event::Ptr event)
{
if (!organizerObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
|| !organizerObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
KCalendarCore::Person organizer(
organizerObj.value(QLatin1String("displayName")).toVariant().toString(),
organizerObj.value(QLatin1String("email")).toVariant().toString());
event->setOrganizer(organizer);
} else if (!creatorObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
|| !creatorObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
KCalendarCore::Person organizer(
creatorObj.value(QLatin1String("displayName")).toVariant().toString(),
creatorObj.value(QLatin1String("email")).toVariant().toString());
event->setOrganizer(organizer);
}
}
void extractAttendees(const QJsonArray &attendees, KCalendarCore::Event::Ptr event)
{
event->clearAttendees();
for (int i = 0; i < attendees.size(); ++i) {
QJsonObject attendeeObj = attendees.at(i).toObject();
if (!attendeeObj.value(QLatin1String("organizer")).toVariant().toBool()) {
KCalendarCore::Attendee attendee(
attendeeObj.value(QLatin1String("displayName")).toVariant().toString(),
attendeeObj.value(QLatin1String("email")).toVariant().toString());
if (attendeeObj.find(QLatin1String("optional")) != attendeeObj.end()) {
if (attendeeObj.value(QLatin1String("optional")).toVariant().toBool()) {
attendee.setRole(KCalendarCore::Attendee::OptParticipant);
} else {
attendee.setRole(KCalendarCore::Attendee::ReqParticipant);
}
}
if (attendeeObj.find(QLatin1String("responseStatus")) != attendeeObj.end()) {
const QString &responseValue = attendeeObj.value(QLatin1String("responseStatus")).toVariant().toString();
if (responseValue == "needsAction") {
attendee.setStatus(KCalendarCore::Attendee::NeedsAction);
} else if (responseValue == "accepted") {
attendee.setStatus(KCalendarCore::Attendee::Accepted);
} else if (responseValue == "declined") {
attendee.setStatus(KCalendarCore::Attendee::Declined);
} else {
attendee.setStatus(KCalendarCore::Attendee::Tentative);
}
}
attendee.setRSVP(true);
event->addAttendee(attendee);
} else {
if (!event->organizer().isEmpty()) {
continue;
}
if (!attendeeObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
|| !attendeeObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
KCalendarCore::Person organizer(
attendeeObj.value(QLatin1String("displayName")).toVariant().toString(),
attendeeObj.value(QLatin1String("email")).toVariant().toString());
event->setOrganizer(organizer);
}
}
}
}
#define START_EVENT_UPDATES_IF_REQUIRED(event, changed) \
if (*changed == false) { \
event->startUpdates(); \
} \
*changed = true;
#define UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, getter, setter, newValue, changed) \
if (event->getter() != newValue) { \
START_EVENT_UPDATES_IF_REQUIRED(event, changed) \
event->setter(newValue); \
}
#define END_EVENT_UPDATES_IF_REQUIRED(event, changed, startedUpdates) \
if (*changed == false) { \
SOCIALD_LOG_DEBUG("Ignoring spurious change reported for:" << \
event->uid() << event->revision() << event->summary()); \
} else if (startedUpdates) { \
event->endUpdates(); \
}
void extractAlarms(const QJsonObject &json, KCalendarCore::Event::Ptr event, int defaultReminderStartOffset, bool *changed)
{
QSet<int> startOffsets;
if (json.contains(QStringLiteral("reminders"))) {
QJsonObject reminders = json.value(QStringLiteral("reminders")).toObject();
if (reminders.value(QStringLiteral("useDefault")).toBool()) {
if (defaultReminderStartOffset > 0) {
startOffsets.insert(defaultReminderStartOffset);
} else {
SOCIALD_LOG_DEBUG("not adding default reminder even though requested: not popup or invalid start offset.");
}
} else {
QJsonArray overrides = reminders.value(QStringLiteral("overrides")).toArray();
for (int i = 0; i < overrides.size(); ++i) {
QJsonObject override = overrides.at(i).toObject();
if (override.value(QStringLiteral("method")).toString() == QStringLiteral("popup")) {
startOffsets.insert(override.value(QStringLiteral("minutes")).toInt());
}
}
}
// search for all reminders to see if they are represented by an alarm.
bool needRemoveAndRecreate = false;
for (QSet<int>::const_iterator it = startOffsets.constBegin(); it != startOffsets.constEnd(); it++) {
const int startOffset = (*it) * -60; // convert minutes to seconds (before event)
SOCIALD_LOG_DEBUG("event needs reminder with start offset (seconds):" << startOffset);
KCalendarCore::Alarm::List alarms = event->alarms();
int alarmsCount = 0;
for (int i = 0; i < alarms.count(); ++i) {
// we don't count Procedure type alarms.
if (alarms.at(i)->type() != KCalendarCore::Alarm::Procedure) {
alarmsCount += 1;
if (alarms.at(i)->startOffset().asSeconds() == startOffset) {
SOCIALD_LOG_DEBUG("event already has reminder with start offset (seconds):" << startOffset);
} else {
SOCIALD_LOG_DEBUG("event is missing reminder with start offset (seconds):" << startOffset);
needRemoveAndRecreate = true;
}
}
}
if (alarmsCount != startOffsets.count()) {
SOCIALD_LOG_DEBUG("event has too many reminders, recreating alarms.");
needRemoveAndRecreate = true;
}
}
if (needRemoveAndRecreate) {
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
KCalendarCore::Alarm::List alarms = event->alarms();
for (int i = 0; i < alarms.count(); ++i) {
if (alarms.at(i)->type() != KCalendarCore::Alarm::Procedure) {
event->removeAlarm(alarms.at(i));
}
}
for (QSet<int>::const_iterator it = startOffsets.constBegin(); it != startOffsets.constEnd(); it++) {
const int startOffset = (*it) * -60; // convert minutes to seconds (before event)
SOCIALD_LOG_DEBUG("setting event reminder with start offset (seconds):" << startOffset);
KCalendarCore::Alarm::Ptr alarm = event->newAlarm();
alarm->setEnabled(true);
alarm->setStartOffset(KCalendarCore::Duration(startOffset));
}
}
}
if (startOffsets.isEmpty()) {
// no reminders were defined in the json received from Google.
// remove any alarms as required from the local event.
KCalendarCore::Alarm::List alarms = event->alarms();
for (int i = 0; i < alarms.count(); ++i) {
if (alarms.at(i)->type() != KCalendarCore::Alarm::Procedure) {
SOCIALD_LOG_DEBUG("removing event reminder with start offset (seconds):" << alarms.at(i)->startOffset().asSeconds());
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
event->removeAlarm(alarms.at(i));
}
}
}
}
void jsonToKCal(const QJsonObject &json, KCalendarCore::Event::Ptr event, int defaultReminderStartOffset, KCalendarCore::ICalFormat &icalFormat, const QList<QDateTime> exceptions, bool *changed)
{
Q_ASSERT(!event.isNull());
bool alreadyStarted = *changed; // if this is true, we don't need to call startUpdates/endUpdates() in this function.
const QString eventGCalETag(gCalETag(event));
const QString jsonGCalETag(json.value(QLatin1String("etag")).toVariant().toString());
if (!alreadyStarted && eventGCalETag == jsonGCalETag) {
SOCIALD_LOG_DEBUG("Ignoring non-remote-changed:" << event->uid() << ","
<< eventGCalETag << "==" << jsonGCalETag);
return; // this event has not changed server-side since we last saw it.
}
QDateTime createdTimestamp, updatedTimestamp, start, end;
bool startExists = false, endExists = false;
bool startIsDateOnly = false, endIsDateOnly = false;
bool isAllDay = false;
extractCreatedAndUpdated(json, &createdTimestamp, &updatedTimestamp);
extractStartAndEnd(json, &startExists, &endExists, &startIsDateOnly, &endIsDateOnly, &isAllDay, &start, &end);
if (gCalEventId(event) != json.value(QLatin1String("id")).toVariant().toString()) {
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
setGCalEventId(event, json.value(QLatin1String("id")).toVariant().toString());
}
if (eventGCalETag != jsonGCalETag) {
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
setGCalETag(event, jsonGCalETag);
}
setRemoteUidCustomField(event, json.value(QLatin1String("iCalUID")).toVariant().toString(), json.value(QLatin1String("id")).toVariant().toString());
extractOrganizer(json.value(QLatin1String("creator")).toObject(), json.value(QLatin1String("organizer")).toObject(), event);
extractAttendees(json.value(QLatin1String("attendees")).toArray(), event);
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, isReadOnly, setReadOnly, json.value(QLatin1String("locked")).toVariant().toBool(), changed)
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, summary, setSummary, json.value(QLatin1String("summary")).toVariant().toString(), changed)
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, description, setDescription, json.value(QLatin1String("description")).toVariant().toString(), changed)
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, location, setLocation, json.value(QLatin1String("location")).toVariant().toString(), changed)
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, revision, setRevision, json.value(QLatin1String("sequence")).toVariant().toInt(), changed)
if (createdTimestamp.isValid()) {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, created, setCreated, createdTimestamp, changed)
}
if (updatedTimestamp.isValid()) {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, lastModified, setLastModified, updatedTimestamp, changed)
}
if (startExists) {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, dtStart, setDtStart, start, changed)
}
if (endExists) {
if (!event->hasEndDate() || event->dtEnd() != end) {
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
event->setDtEnd(end);
}
}
// Recurrence rules use the event start time, so must be set after it
extractRecurrence(json.value(QLatin1String("recurrence")).toArray(), event, icalFormat, exceptions);
if (isAllDay) {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, allDay, setAllDay, true, changed)
}
extractAlarms(json, event, defaultReminderStartOffset, changed);
END_EVENT_UPDATES_IF_REQUIRED(event, changed, !alreadyStarted);
}
bool remoteModificationIsReal(const QJsonObject &json, KCalendarCore::Event::Ptr event)
{
if (gCalEventId(event) != json.value(QLatin1String("id")).toVariant().toString()) {
return true; // this event is either a partial-upsync-artifact or a new remote addition.
}
if (gCalETag(event) != json.value(QLatin1String("etag")).toVariant().toString()) {
return true; // this event has changed server-side since we last saw it.
}
return false; // this event has not changed server-side since we last saw it.
}
bool localModificationIsReal(const QJsonObject &local, const QJsonObject &remote, int defaultReminderStartOffset, KCalendarCore::ICalFormat &icalFormat)
{
bool changed = true;
KCalendarCore::Event::Ptr localEvent = KCalendarCore::Event::Ptr(new KCalendarCore::Event);
KCalendarCore::Event::Ptr remoteEvent = KCalendarCore::Event::Ptr(new KCalendarCore::Event);
jsonToKCal(local, localEvent, defaultReminderStartOffset, icalFormat, QList<QDateTime>(), &changed);
jsonToKCal(remote, remoteEvent, defaultReminderStartOffset, icalFormat, QList<QDateTime>(), &changed);
if (GoogleCalendarIncidenceComparator::incidencesEqual(localEvent, remoteEvent, true)) {
return false; // they're equal, so the local modification is not real.
}
return true;
}
// returns true if the last sync was marked as successful, and then marks the current
// sync as being unsuccessful. The sync adapter should set it to true manually
// once sync succeeds.
bool wasLastSyncSuccessful(int accountId, bool *needCleanSync)
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(PRIVILEGED_DATA_DIR)
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
if (!QFile::exists(settingsFileName)) {
SOCIALD_LOG_DEBUG("gcal.ini settings file does not exist, triggering clean sync");
*needCleanSync = true;
return false;
}
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
// needCleanSync will be true if and only if an unrecoverable error occurred during the previous sync.
*needCleanSync = settingsFile.value(QString::fromLatin1("%1-needCleanSync").arg(accountId), QVariant::fromValue<bool>(false)).toBool();
bool retn = settingsFile.value(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(false)).toBool();
settingsFile.setValue(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(false));
int pluginVersion = settingsFile.value(QString::fromLatin1("%1-pluginVersion").arg(accountId), QVariant::fromValue<int>(1)).toInt();
if (pluginVersion != GOOGLE_CAL_SYNC_PLUGIN_VERSION) {
settingsFile.setValue(QString::fromLatin1("%1-pluginVersion").arg(accountId), GOOGLE_CAL_SYNC_PLUGIN_VERSION);
SOCIALD_LOG_DEBUG("Google cal sync plugin version mismatch, force clean sync");
retn = false;
}
settingsFile.sync();
return retn;
}
void setLastSyncSuccessful(int accountId)
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(PRIVILEGED_DATA_DIR)
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
settingsFile.setValue(QString::fromLatin1("%1-needCleanSync").arg(accountId), QVariant::fromValue<bool>(false));
settingsFile.setValue(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(true));
settingsFile.sync();
}
}
GoogleCalendarSyncAdaptor::GoogleCalendarSyncAdaptor(QObject *parent)
: GoogleDataTypeSyncAdaptor(SocialNetworkSyncAdaptor::Calendars, parent)
, m_syncSucceeded(false)
, m_accountId(0)
, m_calendar(mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(QTimeZone::utc())))
, m_storage(mKCal::ExtendedCalendar::defaultStorage(m_calendar))
, m_storageNeedsSave(false)
{
setInitialActive(true);
}
GoogleCalendarSyncAdaptor::~GoogleCalendarSyncAdaptor()
{
}
QString GoogleCalendarSyncAdaptor::syncServiceName() const
{
return QStringLiteral("google-calendars");
}
void GoogleCalendarSyncAdaptor::sync(const QString &dataTypeString, int accountId)
{
m_storage->open(); // we close it in finalCleanup()
m_accountId = accountId; // needed by finalCleanup()
GoogleDataTypeSyncAdaptor::sync(dataTypeString, accountId);
}
void GoogleCalendarSyncAdaptor::finalCleanup()
{
if (m_accountId != 0) {
if (!m_syncSucceeded) {
// sync failed. check to see if we need to apply any changes to the database.
QSet<QString> calendarsRequiringChange;
for (const QString &calendarId : m_timeMinFailure) {
calendarsRequiringChange.insert(calendarId);
}
for (const QString &calendarId : m_syncTokenFailure) {
calendarsRequiringChange.insert(calendarId);
}
const QDateTime yesterdayDate = QDateTime::currentDateTimeUtc().addDays(-1);
for (const QString &calendarId : calendarsRequiringChange) {
// this codepath is hit if the server replied with HTTP 410 for the sync token or timeMin value.
if (mKCal::Notebook::Ptr notebook = notebookForCalendarId(calendarId)) {
if (m_syncTokenFailure.contains(calendarId)) {
// this sync cycle failed due to the sync token being invalidated server-side.
// trigger clean sync with wide time span on next sync.
notebook->setSyncDate(QDateTime());
} else if (m_timeMinFailure.contains(calendarId)) {
// this sync cycle failed due to the timeMin value being too far in the past.
// trigger clean sync with short time span on next sync.
notebook->setSyncDate(yesterdayDate);
}
notebook->setCustomProperty(NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY, QString());
m_storage->updateNotebook(notebook);
// Notebook operations are immediate so no need to amend m_storageNeedsSave
}
}
} else {
// sync succeeded. apply the changes to the database.
applyRemoteChangesLocally();
if (!m_syncSucceeded) {
SOCIALD_LOG_INFO("Error occurred while applying remote changes locally");
} else {
Q_FOREACH (const QString &updatedCalendarId, m_calendarsFinishedRequested) {
// Update the sync date for the notebook, to the timestamp reported by Google
// in the calendar request for the remote calendar associated with the notebook,
// if that timestamp is recent (within the last week). If it is older than that,
// update it to the current date minus one day, otherwise Google will return
// 410 GONE "UpdatedMin too old" error on subsequent requests.
mKCal::Notebook::Ptr notebook = notebookForCalendarId(updatedCalendarId);
if (!notebook) {
// may have been deleted due to a purge operation.
continue;
}
// Google doesn't use the sync date (synchronisation is handled by the token), it's
// only used by us to figure out what has changed since this sync, using either the
// lastModified or dateDeleted, both of which are set based on the client's time. We
// should therefore set the local synchronisation date to the client's time too.
// The "modified by" test inequality is inclusive, so changes from the sync have
// timestamp clamped to a second before the sync time using clampEventTimeToSync().
SOCIALD_LOG_DEBUG("Latest sync date set to: " << m_syncedDateTime.toString());
notebook->setSyncDate(m_syncedDateTime);
// also update the remote sync token in each notebook.
notebook->setCustomProperty(NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY,
m_calendarsNextSyncTokens.value(updatedCalendarId));
m_storage->updateNotebook(notebook);
// Notebook operations are immediate so no need to amend m_storageNeedsSave
}
}
}
}
if (m_storageNeedsSave) {
SOCIALD_LOG_DEBUG("Saving");
m_storage->save(mKCal::ExtendedStorage::PurgeDeleted);
}
m_storageNeedsSave = false;
if (!m_purgeList.isEmpty() && !m_storage->purgeDeletedIncidences(m_purgeList)) {
// Silently ignore failed purge action in database.
LOG_WARNING("Cannot purge from database the marked as deleted incidences.");
}
// set the success status for each of our account settings.
if (m_syncSucceeded) {
setLastSyncSuccessful(m_accountId);
}
if (!ghostEventCleanupPerformed()) {
// Delete any events which are not associated with a notebook.
// These events are ghost events, caused by a bug which previously
// existed in the sync adapter code due to mkcal deleteNotebook semantics.
// The mkcal API doesn't allow us to determine which notebook a
// given incidence belongs to, so we have to instead load
// everything and then find the ones which are ophaned.
// Note: we do this separately / after the commit above, because
// loading all events from the database is expensive.
SOCIALD_LOG_INFO("performing ghost event cleanup");
m_storage->load();
KCalendarCore::Incidence::List allIncidences;
m_storage->allIncidences(&allIncidences);
mKCal::Notebook::List allNotebooks = m_storage->notebooks();
QSet<QString> notebookIncidenceUids;
foreach (mKCal::Notebook::Ptr notebook, allNotebooks) {
KCalendarCore::Incidence::List currNbIncidences;
m_storage->allIncidences(&currNbIncidences, notebook->uid());
foreach (KCalendarCore::Incidence::Ptr incidence, currNbIncidences) {
notebookIncidenceUids.insert(incidence->uid());
}
}
int foundOrphans = 0;
foreach (const KCalendarCore::Incidence::Ptr incidence, allIncidences) {
if (!notebookIncidenceUids.contains(incidence->uid())) {
// orphan/ghost incidence. must be deleted.
SOCIALD_LOG_DEBUG("deleting orphan event with uid:" << incidence->uid());
m_calendar->deleteIncidence(m_calendar->incidence(incidence->uid(), incidence->recurrenceId()));
foundOrphans++;
}
}
if (foundOrphans == 0) {
setGhostEventCleanupPerformed();
SOCIALD_LOG_INFO("orphan cleanup completed without finding orphans!");
} else if (m_storage->save()) {
setGhostEventCleanupPerformed();
SOCIALD_LOG_INFO("orphan cleanup deleted" << foundOrphans << "; storage save completed!");
} else {
SOCIALD_LOG_ERROR("orphan cleanup found" << foundOrphans << "; but storage save failed!");
}
}
m_storage->close();
}