/
googlecalendarsyncadaptor.cpp
1779 lines (1636 loc) · 88.7 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-2014 Jolla Ltd.
** Contact: Chris Adams <chris.adams@jollamobile.com>
**
** 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 "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 <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <ksystemtimezone.h>
#include <kdatetime.h>
//----------------------------------------------
#define RFC3339_FORMAT "%Y-%m-%dT%H:%M:%S%:z"
#define RFC3339_FORMAT_NTZC "%Y-%m-%dT%H:%M:%S%z"
#define RFC3339_QDATE_FORMAT_MS "yyyy-MM-ddThh:mm:ss.zzzZ"
#define RFC3339_QDATE_FORMAT_MS_NTZC "yyyy-MM-ddThh:mm:ss.zzz"
#define KDATEONLY_FORMAT "%Y-%m-%d"
#define QDATEONLY_FORMAT "yyyy-MM-dd"
#define KLONGTZ_FORMAT "%:Z"
#define RFC5545_KDATETIME_FORMAT "%Y%m%dT%H%M%SZ"
#define RFC5545_KDATETIME_FORMAT_NTZC "%Y%m%dT%H%M%S"
#define RFC5545_QDATE_FORMAT "yyyyMMdd"
namespace {
static int GOOGLE_CAL_SYNC_PLUGIN_VERSION = 2;
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(QString::fromLatin1(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(QString::fromLatin1(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();
}
QString gCalEventId(KCalCore::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(KCalCore::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.
event->removeComment(comment);
break;
}
}
event->addComment(QStringLiteral("jolla-sociald:gcal-id:%1").arg(id));
}
QString gCalETag(KCalCore::Incidence::Ptr event)
{
return event->customProperty("jolla-sociald", "gcal-etag");
}
void setGCalETag(KCalCore::Incidence::Ptr event, const QString &etag)
{
// note: custom properties are purged on incidence deletion.
event->setCustomProperty("jolla-sociald", "gcal-etag", etag);
}
KDateTime datetimeFromUpdateStr(const QString &update)
{
// generally, this is an RFC3339 date with timezone information, like:
// 2015-04-25T12:02:40.988Z
// However, our version of KDateTime is old enough that we don't support this
// date format directly.
bool tzIncluded = update.endsWith('Z');
QDateTime qdt = tzIncluded
? QDateTime::fromString(update, RFC3339_QDATE_FORMAT_MS)
: QDateTime::fromString(update, RFC3339_QDATE_FORMAT_MS_NTZC);
if (tzIncluded) {
qdt.setTimeSpec(Qt::UTC);
}
return KDateTime(qdt, tzIncluded ? KDateTime::UTC : KDateTime::ClockTime);
}
QList<KDateTime> 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<KDateTime> 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("DATE-TIME:", Qt::CaseInsensitive)) {
str.remove(0, 10);
QStringList dts = str.split(',');
Q_FOREACH (const QString &dtstr, dts) {
if (dtstr.endsWith('Z')) {
// UTC
KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT);
kdt.setTimeSpec(KDateTime::Spec::UTC());
retn.append(kdt);
} else {
// Floating time
KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT_NTZC);
kdt.setTimeSpec(KDateTime::Spec::ClockTime());
retn.append(kdt);
}
}
} else if (str.startsWith("DATE:", Qt::CaseInsensitive)) {
str.remove(0, 5);
QStringList dts = str.split(',');
Q_FOREACH(const QString &dstr, dts) {
QDate date = QDate::fromString(dstr, RFC5545_QDATE_FORMAT);
KDateTime kdt(date, KDateTime::Spec::ClockTime());
retn.append(kdt);
}
} else if (str.startsWith("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"
KTimeZone tz = KSystemTimeZones::zone(tzidstr);
str.remove(0, tzidstr.size()+1);
QStringList dts = str.split(',');
Q_FOREACH (const QString &dtstr, dts) {
KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT_NTZC);
if (!kdt.isValid()) {
// try parsing from alternate formats
kdt = KDateTime::fromString(dtstr, RFC3339_FORMAT_NTZC);
}
if (!kdt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
if (tz.isValid()) {
kdt.setTimeSpec(tz);
} else {
kdt.setTimeSpec(KDateTime::Spec::ClockTime());
SOCIALD_LOG_INFO("WARNING: unknown tzid:" << tzidstr << "; assuming clock-time instead!");
}
retn.append(kdt);
}
}
} 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
KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT);
if (!kdt.isValid()) {
// try parsing from alternate formats
kdt = KDateTime::fromString(dtstr, RFC3339_FORMAT);
}
if (!kdt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
// parsed successfully
kdt.setTimeSpec(KDateTime::Spec::UTC());
retn.append(kdt);
}
} else {
// Floating time
KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT_NTZC);
if (!kdt.isValid()) {
// try parsing from alternate formats
kdt = KDateTime::fromString(dtstr, RFC3339_FORMAT_NTZC);
}
if (!kdt.isValid()) {
SOCIALD_LOG_ERROR("unable to parse datetime from ex/rdate string:" << exrdatestr);
} else {
// parsed successfully
kdt.setTimeSpec(KDateTime::Spec::ClockTime());
retn.append(kdt);
}
}
}
} else {
SOCIALD_LOG_ERROR("not a valid ex/rdate string:" << exrdatestr);
}
return retn;
}
QJsonArray recurrenceArray(KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat)
{
QJsonArray retn;
// RRULE
KCalCore::Recurrence *kcalRecurrence = event->recurrence();
Q_FOREACH (KCalCore::RecurrenceRule *rrule, kcalRecurrence->rRules()) {
QString rruleStr = icalFormat.toString(rrule);
rruleStr.replace("\r\n", "");
retn.append(QJsonValue(rruleStr));
}
// EXRULE
Q_FOREACH (KCalCore::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(rdate.toString(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 KDateTime &rdatetime, kcalRecurrence->rDateTimes()) {
if (rdatetime.timeSpec() == KDateTime::Spec::ClockTime()) {
rdatetimes.append(rdatetime.toString(RFC5545_KDATETIME_FORMAT_NTZC));
} else {
rdatetimes.append(rdatetime.toUtc().toString(RFC5545_KDATETIME_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()) {
exdates.append(exdate.toString(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 KDateTime &exdatetime, kcalRecurrence->exDateTimes()) {
if (exdatetime.timeSpec() == KDateTime::Spec::ClockTime()) {
exdatetimes.append(exdatetime.toString(RFC5545_KDATETIME_FORMAT_NTZC));
} else {
exdatetimes.append(exdatetime.toUtc().toString(RFC5545_KDATETIME_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;
}
KDateTime parseRecurrenceId(const QJsonObject &originalStartTime)
{
QString recurrenceIdStr = originalStartTime.value(QLatin1String("dateTime")).toVariant().toString();
QString recurrenceIdTzStr = originalStartTime.value(QLatin1String("timeZone")).toVariant().toString();
KDateTime recurrenceId = KDateTime::fromString(recurrenceIdStr, RFC3339_FORMAT);
if (!recurrenceIdTzStr.isEmpty()) {
recurrenceId = recurrenceId.toTimeSpec(KTimeZone(recurrenceIdTzStr));
}
return recurrenceId;
}
QJsonObject kCalToJson(KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat)
{
QString eventId = gCalEventId(event);
QJsonObject start, end;
// insert the date/time and timeZone information into the Json object.
// note that timeZone is required for recurring events, for some reason.
if (event->dtStart().isDateOnly() || (event->allDay() && event->dtStart().time() == QTime(0,0,0))) {
start.insert(QLatin1String("date"), event->dtStart().date().toString(QDATEONLY_FORMAT));
} else {
start.insert(QLatin1String("dateTime"), event->dtStart().toString(RFC3339_FORMAT));
start.insert(QLatin1String("timeZone"), QJsonValue(event->dtStart().toString(KLONGTZ_FORMAT)));
}
if (event->dtEnd().isDateOnly() || (event->allDay() && event->dtEnd().time() == QTime(0,0,0))) {
// note: for iCal spec, allDay events need to have an end date of real-end-date+1 as end date is exclusive.
end.insert(QLatin1String("date"), event->dateEnd().addDays(1).toString(QDATEONLY_FORMAT));
} else {
end.insert(QLatin1String("dateTime"), event->dtEnd().toString(RFC3339_FORMAT));
end.insert(QLatin1String("timeZone"), QJsonValue(event->dtEnd().toString(KLONGTZ_FORMAT)));
}
QJsonObject retn;
if (!eventId.isEmpty()) retn.insert(QLatin1String("id"), eventId);
if (event->recurrence()) retn.insert(QLatin1String("recurrence"), recurrenceArray(event, icalFormat));
retn.insert(QLatin1String("summary"), event->summary());
retn.insert(QLatin1String("description"), event->description());
retn.insert(QLatin1String("location"), event->location());
retn.insert(QLatin1String("start"), start);
retn.insert(QLatin1String("end"), end);
retn.insert(QLatin1String("sequence"), QString::number(event->revision()+1));
//retn.insert(QLatin1String("locked"), event->readOnly()); // only allow locking server-side.
// we may wish to support locking/readonly from local side also, in the future.
return retn;
}
void extractStartAndEnd(const QJsonObject &eventData,
bool *startExists,
bool *endExists,
bool *startIsDateOnly,
bool *endIsDateOnly,
bool *isAllDay,
KDateTime *start,
KDateTime *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) {
KDateTime parsedStartTime = KDateTime::fromString(startTimeString, RFC3339_FORMAT);
KDateTime ntzcStartTime = KDateTime::fromString(startTimeString, RFC3339_FORMAT_NTZC);
if (ntzcStartTime.time() > parsedStartTime.time()) parsedStartTime = ntzcStartTime;
// different format? let KDateTime detect the format automatically.
if (parsedStartTime.isNull()) {
parsedStartTime = KDateTime::fromString(startTimeString);
}
*start = parsedStartTime.toLocalZone();
} else {
*start = KDateTime(QDate::fromString(startTimeString, QDATEONLY_FORMAT), QTime(), KDateTime::ClockTime);
// note: don't call start->setDateOnly(true); or mkcal doesn't like it.
}
}
if (*endExists) {
if (!*endIsDateOnly) {
KDateTime parsedEndTime = KDateTime::fromString(endTimeString, RFC3339_FORMAT);
KDateTime ntzcEndTime = KDateTime::fromString(endTimeString, RFC3339_FORMAT_NTZC);
if (ntzcEndTime.time() > parsedEndTime.time()) parsedEndTime = ntzcEndTime;
// different format? let KDateTime detect the format automatically.
if (parsedEndTime.isNull()) {
parsedEndTime = KDateTime::fromString(endTimeString);
}
*end = parsedEndTime.toLocalZone();
} else {
// Special handling for all-day events is required.
if (*startExists && *startIsDateOnly) {
if (QDate::fromString(startTimeString, QDATEONLY_FORMAT)
== QDate::fromString(endTimeString, QDATEONLY_FORMAT)) {
// single-day all-day event
*endExists = false;
*isAllDay = true;
} else if (QDate::fromString(startTimeString, QDATEONLY_FORMAT)
== QDate::fromString(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).
*start = KDateTime(QDate::fromString(startTimeString, QDATEONLY_FORMAT), QTime(), KDateTime::ClockTime);
*end = KDateTime(QDate::fromString(endTimeString, QDATEONLY_FORMAT).addDays(-1), QTime(), KDateTime::ClockTime);
*isAllDay = true;
}
} else {
*end = KDateTime(QDate::fromString(endTimeString, QDATEONLY_FORMAT).addDays(-1), QTime(), KDateTime::ClockTime);
// note: don't call end->setDateOnly(true); or mkcal doesn't like it.
*isAllDay = false;
}
}
}
}
void extractRecurrence(const QJsonArray &recurrence, KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat)
{
KCalCore::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)) {
KCalCore::RecurrenceRule *rrule = new KCalCore::RecurrenceRule;
if (!icalFormat.fromString(rrule, ruleStr.mid(6))) {
SOCIALD_LOG_DEBUG("unable to parse RRULE information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
} else {
kcalRecurrence->addRRule(rrule);
}
} else if (ruleStr.startsWith(QString::fromLatin1("exrule"), Qt::CaseInsensitive)) {
KCalCore::RecurrenceRule *exrule = new KCalCore::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<KDateTime> 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 KDateTime &kdt, rdatetimes) {
if (isDateOnly) {
kcalRecurrence->addRDate(kdt.date());
} else {
kcalRecurrence->addRDateTime(kdt);
}
}
}
} else if (ruleStr.startsWith(QString::fromLatin1("exdate"), Qt::CaseInsensitive)) {
bool isDateOnly = false;
QList<KDateTime> 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 KDateTime &kdt, exdatetimes) {
if (isDateOnly) {
kcalRecurrence->addExDate(kdt.date());
} else {
kcalRecurrence->addExDateTime(kdt);
}
}
}
} else {
SOCIALD_LOG_DEBUG("unknown recurrence information:" << ruleStr);
traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
}
}
}
int nearestNemoReminderStartOffset(int googleStartOffset)
{
// Google supports arbitrary start offsets, whereas in Nemo's UI
// we only allow specific reminder offsets.
// See nemo-qml-plugin-calendar::NemoCalendarEvent::Reminder for
// those offset definitions.
// Also, Nemo reminder offsets are negative and in seconds,
// whereas Google start offsets are positive and in minutes.
if (googleStartOffset >= 0 && googleStartOffset <= 5) {
return -5 * 60; // 5 minutes before event start
} else if (googleStartOffset > 5 && googleStartOffset <= 15) {
return -15 * 60; // 15 minutes before event start
} else if (googleStartOffset > 15 && googleStartOffset <= 30) {
return -30 * 60; // 30 minutes before event start
} else if (googleStartOffset > 30 && googleStartOffset <= 60) {
return -60 * 60; // 1 hour before event start
} else if (googleStartOffset > 60 && googleStartOffset <= 120) {
return -120 * 60; // 2 hours before event start
} else if (googleStartOffset > 120 && googleStartOffset <= 1440) {
return -1440 * 60; // 1 day before event start (24 hours)
} else if (googleStartOffset > 1440) {
return -2880 * 60; // 2 days before event start (48 hours)
}
// default reminder: 15 minutes before event start.
return -15 * 60;
}
#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, KCalCore::Event::Ptr event, int defaultReminderStartOffset, bool *changed)
{
int startOffset = -1;
if (json.contains(QStringLiteral("reminders"))) {
QJsonObject reminders = json.value(QStringLiteral("reminders")).toObject();
if (reminders.value(QStringLiteral("useDefault")).toBool()) {
if (defaultReminderStartOffset > 0) {
startOffset = 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")) {
startOffset = override.value(QStringLiteral("minutes")).toInt();
}
}
}
if (startOffset > -1) {
startOffset = nearestNemoReminderStartOffset(startOffset);
SOCIALD_LOG_DEBUG("event needs reminder with start offset (seconds):" << startOffset);
KCalCore::Alarm::List alarms = event->alarms();
int alarmCount = 0;
// check that we have only one non-procedure alarm,
// and then check to see if its start offset is correct.
for (int i = 0; i < alarms.count(); ++i) {
// we don't count Procedure type alarms.
if (alarms.at(i)->type() != KCalCore::Alarm::Procedure) {
alarmCount += 1;
if (alarms.at(i)->startOffset().asSeconds() == startOffset) {
// no change required to this alarm.
} else {
alarmCount += 1; // this will cause alarm modification.
}
}
}
if (alarmCount == 1) {
// no need to modify alarms for this event
SOCIALD_LOG_DEBUG("event already has reminder with start offset (seconds):" << startOffset);
} else {
SOCIALD_LOG_DEBUG("setting event reminder with start offset (seconds):" << startOffset);
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
for (int i = 0; i < alarms.count(); ++i) {
if (alarms.at(i)->type() != KCalCore::Alarm::Procedure) {
event->removeAlarm(alarms.at(i));
}
}
KCalCore::Alarm::Ptr alarm = event->newAlarm();
alarm->setEnabled(true);
alarm->setStartOffset(KCalCore::Duration(startOffset));
}
}
}
if (startOffset == -1) {
// no reminders were defined in the json received from Google.
// remove any alarms as required from the local event.
KCalCore::Alarm::List alarms = event->alarms();
for (int i = 0; i < alarms.count(); ++i) {
if (alarms.at(i)->type() != KCalCore::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, KCalCore::Event::Ptr event, int defaultReminderStartOffset, KCalCore::ICalFormat &icalFormat, bool *changed)
{
bool alreadyStarted = *changed; // if this is true, we don't need to call startUpdates/endUpdates() in this function.
if (!alreadyStarted && gCalETag(event) == json.value(QLatin1String("etag")).toVariant().toString()) {
SOCIALD_LOG_DEBUG("Ignoring non-remote-changed:" << event->uid() << ","
<< gCalETag(event) << "==" << json.value(QLatin1String("etag")).toVariant().toString());
return; // this event has not changed server-side since we last saw it.
}
KDateTime start, end;
bool startExists = false, endExists = false;
bool startIsDateOnly = false, endIsDateOnly = false;
bool isAllDay = false;
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 (gCalETag(event) != json.value(QLatin1String("etag")).toVariant().toString()) {
START_EVENT_UPDATES_IF_REQUIRED(event, changed);
setGCalETag(event, json.value(QLatin1String("etag")).toVariant().toString());
}
extractRecurrence(json.value(QLatin1String("recurrence")).toArray(), event, icalFormat);
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("revision")).toVariant().toInt(), 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->setHasEndDate(true);
event->setDtEnd(end);
}
} else {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, hasEndDate, setHasEndDate, false, changed)
}
if (isAllDay) {
UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, allDay, setAllDay, false, changed)
}
extractAlarms(json, event, defaultReminderStartOffset, changed);
END_EVENT_UPDATES_IF_REQUIRED(event, changed, !alreadyStarted);
}
// 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)
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(QString::fromLatin1(PRIVILEGED_DATA_DIR))
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
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(QList<int> accountIds)
{
QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
.arg(QString::fromLatin1(PRIVILEGED_DATA_DIR))
.arg(QString::fromLatin1(SYNC_DATABASE_DIR));
QSettings settingsFile(settingsFileName, QSettings::IniFormat);
Q_FOREACH(int accountId, accountIds) {
settingsFile.setValue(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(true));
}
settingsFile.sync();
}
}
GoogleCalendarSyncAdaptor::GoogleCalendarSyncAdaptor(QObject *parent)
: GoogleDataTypeSyncAdaptor(SocialNetworkSyncAdaptor::Calendars, parent)
, m_calendar(mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(QLatin1String("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()
GoogleDataTypeSyncAdaptor::sync(dataTypeString, accountId);
}
void GoogleCalendarSyncAdaptor::finalCleanup()
{
// Commit changes to db. Note that we do this even if one or more of the operations encountered error!
// the reason is that we cannot recover fully from an error occurring because of the semantics of
// mkcal (ie, deleteNotebook() etc forcing a storage save).
// As such, the "best effort" when an error occurs is:
// - write as much of the data as possible to the local database
// - skip any upsync which may otherwise have occurred
// - mark the sync as failed so the next sync is a clean sync
if (m_storageNeedsSave) {
m_storage->save();
}
m_storageNeedsSave = false;
// set the success status for each of our account settings.
QList<int> succeededAccounts;
Q_FOREACH (int accountId, m_syncSucceeded.keys()) {
if (m_syncSucceeded.value(accountId)) {
succeededAccounts.append(accountId);
}
}
if (succeededAccounts.size()) {
setLastSyncSuccessful(succeededAccounts);
}
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();
KCalCore::Incidence::List allIncidences;
m_storage->allIncidences(&allIncidences);
mKCal::Notebook::List allNotebooks = m_storage->notebooks();
QSet<QString> notebookIncidenceUids;
foreach (mKCal::Notebook::Ptr notebook, allNotebooks) {
KCalCore::Incidence::List currNbIncidences;
m_storage->allIncidences(&currNbIncidences, notebook->uid());
foreach (KCalCore::Incidence::Ptr incidence, currNbIncidences) {
notebookIncidenceUids.insert(incidence->uid());
}
}
foreach (const KCalCore::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()));
m_storageNeedsSave = true;
}
}
if (!m_storageNeedsSave) {
setGhostEventCleanupPerformed();
SOCIALD_LOG_INFO("orphan cleanup completed without finding orphans!");
} else if (m_storage->save()) {
setGhostEventCleanupPerformed();
SOCIALD_LOG_INFO("orphan cleanup storage save completed!");
} else {
SOCIALD_LOG_ERROR("orphan cleanup storage save failed!");
}
}
m_storage->close();
}
void GoogleCalendarSyncAdaptor::purgeDataForOldAccount(int oldId, SocialNetworkSyncAdaptor::PurgeMode mode)
{
if (mode == SocialNetworkSyncAdaptor::CleanUpPurge) {
// need to initialise the database
m_storage->open(); // we close it in finalCleanup()
}
// We clean all the entries in the calendar
// Delete the notebooks from the storage
foreach (mKCal::Notebook::Ptr notebook, m_storage->notebooks()) {
if (notebook->pluginName().startsWith(QString(QLatin1String("google-")))
&& notebook->account() == QString::number(oldId)) {
// remove the incidences and delete the notebook
notebook->setIsReadOnly(false);
m_storage->deleteNotebook(notebook);
m_storageNeedsSave = true;
}
}
if (mode == SocialNetworkSyncAdaptor::CleanUpPurge) {
// and commit any changes made.
finalCleanup();
}
}
void GoogleCalendarSyncAdaptor::beginSync(int accountId, const QString &accessToken)
{
SOCIALD_LOG_DEBUG("beginning Calendar sync for Google, account" << accountId);
bool needCleanSync = !wasLastSyncSuccessful(accountId);
if (needCleanSync) {
SOCIALD_LOG_INFO("last sync was not successful; performing clean sync");
}
m_serverCalendarIdToCalendarInfo[accountId].clear();
m_calendarIdToEventObjects[accountId].clear();
m_syncSucceeded[accountId] = true; // set to false on error
requestCalendars(accountId, accessToken, needCleanSync);
}
void GoogleCalendarSyncAdaptor::requestCalendars(int accountId, const QString &accessToken, bool needCleanSync, const QString &pageToken)
{
QList<QPair<QString, QString> > queryItems;
queryItems.append(QPair<QString, QString>(QString::fromLatin1("key"), accessToken));
if (!pageToken.isEmpty()) { // continuation request
queryItems.append(QPair<QString, QString>(QString::fromLatin1("pageToken"),
pageToken));
}
QUrl url(QLatin1String("https://www.googleapis.com/calendar/v3/users/me/calendarList"));
QUrlQuery query(url);
query.setQueryItems(queryItems);
url.setQuery(query);
QNetworkRequest request(url);
request.setRawHeader("GData-Version", "3.0");
request.setRawHeader(QString(QLatin1String("Authorization")).toUtf8(),
QString(QLatin1String("Bearer ") + accessToken).toUtf8());
QNetworkReply *reply = m_networkAccessManager->get(request);
// we're requesting data. Increment the semaphore so that we know we're still busy.
incrementSemaphore(accountId);
if (reply) {
reply->setProperty("accountId", accountId);
reply->setProperty("accessToken", accessToken);
reply->setProperty("needCleanSync", QVariant::fromValue<bool>(needCleanSync));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(errorHandler(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(sslErrorsHandler(QList<QSslError>)));
connect(reply, SIGNAL(finished()), this, SLOT(calendarsFinishedHandler()));
setupReplyTimeout(accountId, reply);
} else {
SOCIALD_LOG_ERROR("unable to request calendars from Google account with id" << accountId);
m_syncSucceeded[accountId] = false;
decrementSemaphore(accountId);
}
}
void GoogleCalendarSyncAdaptor::calendarsFinishedHandler()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
int accountId = reply->property("accountId").toInt();
QString accessToken = reply->property("accessToken").toString();
bool needCleanSync = reply->property("needCleanSync").toBool();
QByteArray replyData = reply->readAll();
bool isError = reply->property("isError").toBool();
disconnect(reply);
reply->deleteLater();
removeReplyTimeout(accountId, reply);
// parse the calendars' metadata from the response.
bool fetchingNextPage = false;
bool ok = false;
QJsonObject parsed = parseJsonObjectReplyData(replyData, &ok);
if (!isError && ok) {
// first, check to see if there are more pages of calendars to fetch
if (parsed.find(QLatin1String("nextPageToken")) != parsed.end()
&& !parsed.value(QLatin1String("nextPageToken")).toVariant().toString().isEmpty()) {
fetchingNextPage = true;
requestCalendars(accountId, accessToken, needCleanSync,
parsed.value(QLatin1String("nextPageToken")).toVariant().toString());
}
// second, parse the calendars' metadata
QJsonArray items = parsed.value(QStringLiteral("items")).toArray();
for (int i = 0; i < items.count(); ++i) {
QJsonObject currCalendar = items.at(i).toObject();
if (!currCalendar.isEmpty() && currCalendar.find(QStringLiteral("id")) != currCalendar.end()) {
// we only sync calendars which the user owns (ie, not autogenerated calendars)
QString accessRole = currCalendar.value(QStringLiteral("accessRole")).toString();
if (accessRole == QStringLiteral("owner")) {
GoogleCalendarSyncAdaptor::CalendarInfo currCalendarInfo;
currCalendarInfo.color = currCalendar.value(QStringLiteral("backgroundColor")).toString();
currCalendarInfo.summary = currCalendar.value(QStringLiteral("summary")).toString();
currCalendarInfo.description = currCalendar.value(QStringLiteral("description")).toString();
currCalendarInfo.change = NoChange; // we detect the appropriate change type (if required) later.
QString currCalendarId = currCalendar.value(QStringLiteral("id")).toString();
m_serverCalendarIdToCalendarInfo[accountId].insert(currCalendarId, currCalendarInfo);
}
}
}
} else {
// error occurred during request.
SOCIALD_LOG_ERROR("unable to parse calendar data from request with account" << accountId << ";" <<
"got:" << QString::fromLatin1(replyData.constData()));
m_syncSucceeded[accountId] = false;
}
if (!fetchingNextPage) {
// we've finished loading all pages of calendar information
// we now need to process the loaded information to determine
// which calendars need to be added/updated/removed locally.
updateLocalCalendarNotebooks(accountId, accessToken, needCleanSync);
}
// we're finished with this request.
decrementSemaphore(accountId);
}
void GoogleCalendarSyncAdaptor::updateLocalCalendarNotebooks(int accountId, const QString &accessToken, bool needCleanSync)
{
if (syncAborted()) {
SOCIALD_LOG_DEBUG("sync aborted, skipping updating local calendar notebooks");
return;
}
// any calendars which exist on the device but not the server need to be purged.
QStringList calendarsToDelete;
QStringList deviceCalendarIds;
foreach (mKCal::Notebook::Ptr notebook, m_storage->notebooks()) {
// notebook pluginName is of form: google-calendarId
// where the calendarId comes from the server.