googlecalendarsyncadaptor.cpp 135 KB
Newer Older
1 2
/****************************************************************************
 **
3
 ** Copyright (C) 2013-2014 Jolla Ltd.
4 5
 ** Contact: Chris Adams <chris.adams@jollamobile.com>
 **
6 7 8 9 10 11 12 13 14 15 16 17 18 19
 ** 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
 **
20 21 22
 ****************************************************************************/

#include "googlecalendarsyncadaptor.h"
23
#include "googlecalendarincidencecomparator.h"
24 25 26 27 28
#include "trace.h"

#include <QtCore/QUrlQuery>
#include <QtCore/QFile>
#include <QtCore/QDir>
29
#include <QtCore/QByteArray>
30 31
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
32 33
#include <QtCore/QJsonDocument>
#include <QtCore/QSettings>
34
#include <QtCore/QSet>
35 36 37 38

#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>

39
#include <ksystemtimezone.h>
40
#include <kdatetime.h>
41

42 43 44 45
#include <Accounts/Account>
#include <Accounts/Manager>
#include <Accounts/Service>

46
//----------------------------------------------
47

48 49
#define RFC3339_FORMAT      "%Y-%m-%dT%H:%M:%S%:z"
#define RFC3339_FORMAT_NTZC "%Y-%m-%dT%H:%M:%S%z"
50 51
#define RFC3339_QDATE_FORMAT_MS "yyyy-MM-ddThh:mm:ss.zzzZ"
#define RFC3339_QDATE_FORMAT_MS_NTZC "yyyy-MM-ddThh:mm:ss.zzz"
52 53 54
#define KDATEONLY_FORMAT    "%Y-%m-%d"
#define QDATEONLY_FORMAT    "yyyy-MM-dd"
#define KLONGTZ_FORMAT      "%:Z"
55 56 57
#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"
58 59 60

namespace {

61 62
const int GOOGLE_CAL_SYNC_PLUGIN_VERSION = 3;
const QByteArray NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY = QByteArrayLiteral("syncToken");
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
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);
    }
}

90 91 92 93
// returns true if the ghost-event cleanup sync has been performed.
bool ghostEventCleanupPerformed()
{
    QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
94
            .arg(PRIVILEGED_DATA_DIR)
95 96 97 98 99 100 101
            .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")
102
            .arg(PRIVILEGED_DATA_DIR)
103 104 105 106 107 108
            .arg(QString::fromLatin1(SYNC_DATABASE_DIR));
    QSettings settingsFile(settingsFileName, QSettings::IniFormat);
    settingsFile.setValue(QString::fromLatin1("cleaned"), QVariant::fromValue<bool>(true));
    settingsFile.sync();
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
void uniteIncidenceLists(const KCalCore::Incidence::List &first, KCalCore::Incidence::List *second)
{
    int originalSecondSize = second->size();
    bool foundMatch = false;
    Q_FOREACH (KCalCore::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);
        }
    }
}

128 129
QString gCalEventId(KCalCore::Incidence::Ptr event)
{
130 131 132 133 134 135 136 137 138
    // 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();
139
}
140

141 142
void setGCalEventId(KCalCore::Incidence::Ptr event, const QString &id)
{
143 144 145 146 147 148 149 150 151 152 153 154 155
    // 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));
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
void setRemoteUidCustomField(KCalCore::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());
        }
    }
}

173 174 175 176
QString gCalETag(KCalCore::Incidence::Ptr event)
{
    return event->customProperty("jolla-sociald", "gcal-etag");
}
177

178 179 180 181 182 183
void setGCalETag(KCalCore::Incidence::Ptr event, const QString &etag)
{
    // note: custom properties are purged on incidence deletion.
    event->setCustomProperty("jolla-sociald", "gcal-etag", etag);
}

184 185 186 187 188 189 190 191
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
192 193
                  ? QLocale::c().toDateTime(update, RFC3339_QDATE_FORMAT_MS)
                  : QLocale::c().toDateTime(update, RFC3339_QDATE_FORMAT_MS_NTZC);
194 195 196 197
    if (tzIncluded) {
        qdt.setTimeSpec(Qt::UTC);
    }
    return KDateTime(qdt, tzIncluded ? KDateTime::UTC : KDateTime::ClockTime);
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
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);
225 226
        if (str.startsWith("VALUE=DATE-TIME:", Qt::CaseInsensitive)) {
            str.remove(0, 16);
227 228 229 230 231 232 233 234 235 236 237 238 239 240
            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);
                }
            }
241 242
        } else if (str.startsWith("VALUE=DATE:", Qt::CaseInsensitive)) {
            str.remove(0, 11);
243 244
            QStringList dts = str.split(',');
            Q_FOREACH(const QString &dstr, dts) {
245
                QDate date = QLocale::c().toDate(dstr, RFC5545_QDATE_FORMAT);
246 247 248
                KDateTime kdt(date, KDateTime::Spec::ClockTime());
                retn.append(kdt);
            }
249
        } else if (str.startsWith("VALUE=PERIOD:", Qt::CaseInsensitive)) {
250 251
            SOCIALD_LOG_ERROR("unsupported parameter in ex/rdate string:" << exrdatestr);
            // TODO: support PERIOD formats, or just switch to CalDAV for Google sync...
252
        } else if (str.startsWith("TZID=") && str.contains(':')) {
253 254
            str.remove(0, 5);
            QString tzidstr = str.mid(0, str.indexOf(':')); // something like: "Australia/Brisbane"
255 256 257 258 259
            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);
260 261 262 263 264 265
                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);
266
                } else {
267 268 269 270 271 272 273
                    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);
274 275 276 277 278 279 280 281 282 283 284 285
                }
            }
        } 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);
286 287 288 289 290 291 292 293 294 295 296
                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);
                }
297 298 299
            } else {
                // Floating time
                KDateTime kdt = KDateTime::fromString(dtstr, RFC5545_KDATETIME_FORMAT_NTZC);
300 301 302 303 304 305 306 307 308 309 310
                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);
                }
311 312 313 314 315 316 317 318 319
            }
        }
    } else {
        SOCIALD_LOG_ERROR("not a valid ex/rdate string:" << exrdatestr);
    }

    return retn;
}

320 321 322
QJsonArray recurrenceArray(KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat)
{
    QJsonArray retn;
323 324

    // RRULE
325 326 327 328 329 330
    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));
    }
331 332

    // EXRULE
333 334 335 336 337 338
    Q_FOREACH (KCalCore::RecurrenceRule *exrule, kcalRecurrence->exRules()) {
        QString exruleStr = icalFormat.toString(exrule);
        exruleStr.replace("RRULE", "EXRULE");
        exruleStr.replace("\r\n", "");
        retn.append(QJsonValue(exruleStr));
    }
339 340 341

    // RDATE (date)
    QString rdates;
342
    Q_FOREACH (const QDate &rdate, kcalRecurrence->rDates()) {
343
        rdates.append(QLocale::c().toString(rdate, RFC5545_QDATE_FORMAT));
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        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)));
364
    }
365 366 367

    // EXDATE (date)
    QString exdates;
368
    Q_FOREACH (const QDate &exdate, kcalRecurrence->exDates()) {
369
        exdates.append(QLocale::c().toString(exdate, RFC5545_QDATE_FORMAT));
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        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)));
390
    }
391

392 393 394
    return retn;
}

395 396 397 398 399 400 401 402 403 404 405
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;
}

406
QJsonObject kCalToJson(KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat, bool setUidProperty = false)
407 408
{
    QString eventId = gCalEventId(event);
409
    QJsonObject start, end;
410

411 412 413
    QJsonArray attendees;
    const KCalCore::Attendee::List attendeesList = event->attendees();
    if (!attendeesList.isEmpty()) {
414
        const QString &organizerEmail = event->organizer()->email();
415
        Q_FOREACH (auto att, attendeesList) {
416
            if (att->email().isEmpty() || att->email() == organizerEmail) {
417 418 419 420 421 422 423 424 425 426 427 428 429 430
                continue;
            }
            QJsonObject attendee;
            attendee.insert("email", att->email());
            if (att->role() == KCalCore::Attendee::OptParticipant) {
                attendee.insert("optional", true);
            }
            const QString &name = att->name();
            if (!name.isEmpty()) {
                attendee.insert("displayName", name);
            }
            attendees.append(attendee);
        }
    }
431 432 433
    // 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))) {
434
        start.insert(QLatin1String("date"), QLocale::c().toString(event->dtStart().date(), QDATEONLY_FORMAT));
435 436 437 438 439
    } 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))) {
440
        // note: for iCal spec, allDay events need to have an end date of real-end-date+1 as end date is exclusive.
441
        end.insert(QLatin1String("date"), QLocale::c().toString(event->dateEnd().addDays(1), QDATEONLY_FORMAT));
442 443 444 445 446 447 448
    } 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);
449 450 451 452 453 454
    if (event->recurrence()) {
        QJsonArray recArray = recurrenceArray(event, icalFormat);
        if (recArray.size()) {
            retn.insert(QLatin1String("recurrence"), recArray);
        }
    }
455 456 457 458 459 460
    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));
461 462 463
    if (!attendees.isEmpty()) {
        retn.insert(QLatin1String("attendees"), attendees);
    }
464 465 466
    //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.

467 468 469 470 471 472 473 474 475 476
    // if the event has no alarms associated with it, don't let Google add one automatically
    // otherwise, attempt to upsync the alarms as popup reminders.
    QJsonObject reminders;
    if (event->alarms().count()) {
        QJsonArray overrides;
        KCalCore::Alarm::List alarms = event->alarms();
        for (int i = 0; i < alarms.count(); ++i) {
            // only upsync non-procedure alarms as popup reminders.
            QSet<int> seenMinutes;
            if (alarms.at(i)->type() != KCalCore::Alarm::Procedure) {
477
                const int minutes = (alarms.at(i)->startOffset().asSeconds() / 60) * -1;
478 479 480 481 482 483 484 485 486 487
                if (!seenMinutes.contains(minutes)) {
                    QJsonObject override;
                    override.insert(QLatin1String("method"), QLatin1String("popup"));
                    override.insert(QLatin1String("minutes"), minutes);
                    overrides.append(override);
                    seenMinutes.insert(minutes);
                }
            }
        }
        reminders.insert(QLatin1String("overrides"), overrides);
488
    }
489 490
    reminders.insert(QLatin1String("useDefault"), false);
    retn.insert(QLatin1String("reminders"), reminders);
491

492 493 494 495 496 497 498 499 500 501 502 503
    if (setUidProperty) {
        // now we store private extended properties: local uid.
        // this allows us to detect partially-upsynced artifacts during subsequent syncs.
        // usually this codepath will be hit for localAdditions being upsynced,
        // but sometimes also if we need to update the mapping due to clean-sync.
        QJsonObject privateExtendedProperties;
        privateExtendedProperties.insert(QLatin1String("x-jolla-sociald-mkcal-uid"), event->uid());
        QJsonObject extendedProperties;
        extendedProperties.insert(QLatin1String("private"), privateExtendedProperties);
        retn.insert(QLatin1String("extendedProperties"), extendedProperties);
    }

504 505 506
    return retn;
}

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
KDateTime parseDateTimeString(const QString &dateTimeStr)
{
    KDateTime parsedTime = KDateTime::fromString(dateTimeStr, RFC3339_FORMAT);
    KDateTime ntzcTime = KDateTime::fromString(dateTimeStr, RFC3339_FORMAT_NTZC);

    if (ntzcTime.time() > parsedTime.time()) {
        parsedTime = ntzcTime;
    }

    // different format?  let KDateTime detect the format automatically.
    if (parsedTime.isNull()) {
        parsedTime = KDateTime::fromString(dateTimeStr);
    }

    return parsedTime.toLocalZone();
}

void extractCreatedAndUpdated(const QJsonObject &eventData,
                              KDateTime *created,
                              KDateTime *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);
    }
}

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
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) {
576
            *start = parseDateTimeString(startTimeString);
577
        } else {
578
            *start = KDateTime(QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT), QTime(), KDateTime::ClockTime);
579
            start->setDateOnly(true);
580 581 582 583 584
        }
    }

    if (*endExists) {
        if (!*endIsDateOnly) {
585
            *end = parseDateTimeString(endTimeString);
586
        } else {
587
            // Special handling for all-day events is required.
588
            if (*startExists && *startIsDateOnly) {
589 590
                if (QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT)
                        == QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT)) {
591 592 593
                    // single-day all-day event
                    *endExists = false;
                    *isAllDay = true;
594 595
                } else if (QLocale::c().toDate(startTimeString, QDATEONLY_FORMAT)
                        == QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT).addDays(-1)) {
596 597 598 599 600
                    // 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;
601
                } else {
602 603 604
                    // 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).
605
                    *end = KDateTime(QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT), QTime(), KDateTime::ClockTime);
606
                    end->setDateOnly(true);
607 608 609
                    *isAllDay = true;
                }
            } else {
610
                *end = KDateTime(QLocale::c().toDate(endTimeString, QDATEONLY_FORMAT), QTime(), KDateTime::ClockTime);
611
                end->setDateOnly(true);
612 613 614 615 616 617 618 619 620
                *isAllDay = false;
            }
        }
    }
}

void extractRecurrence(const QJsonArray &recurrence, KCalCore::Event::Ptr event, KCalCore::ICalFormat &icalFormat)
{
    KCalCore::Recurrence *kcalRecurrence = event->recurrence();
621
    kcalRecurrence->clear(); // avoid adding duplicate recurrence information
622 623
    for (int i = 0; i < recurrence.size(); ++i) {
        QString ruleStr = recurrence.at(i).toString();
624
        if (ruleStr.startsWith(QString::fromLatin1("rrule"), Qt::CaseInsensitive)) {
625 626
            KCalCore::RecurrenceRule *rrule = new KCalCore::RecurrenceRule;
            if (!icalFormat.fromString(rrule, ruleStr.mid(6))) {
627 628
                SOCIALD_LOG_DEBUG("unable to parse RRULE information:" << ruleStr);
                traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
629 630 631
            } else {
                kcalRecurrence->addRRule(rrule);
            }
632
        } else if (ruleStr.startsWith(QString::fromLatin1("exrule"), Qt::CaseInsensitive)) {
633 634
            KCalCore::RecurrenceRule *exrule = new KCalCore::RecurrenceRule;
            if (!icalFormat.fromString(exrule, ruleStr.mid(7))) {
635 636
                SOCIALD_LOG_DEBUG("unable to parse EXRULE information:" << ruleStr);
                traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
637 638 639
            } else {
                kcalRecurrence->addExRule(exrule);
            }
640 641 642 643 644 645
        } 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()));
646
            } else {
647 648 649 650 651 652 653
                Q_FOREACH (const KDateTime &kdt, rdatetimes) {
                    if (isDateOnly) {
                        kcalRecurrence->addRDate(kdt.date());
                    } else {
                        kcalRecurrence->addRDateTime(kdt);
                    }
                }
654
            }
655 656 657 658 659 660
        } 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()));
661
            } else {
662 663 664 665 666 667 668
                Q_FOREACH (const KDateTime &kdt, exdatetimes) {
                    if (isDateOnly) {
                        kcalRecurrence->addExDate(kdt.date());
                    } else {
                        kcalRecurrence->addExDateTime(kdt);
                    }
                }
669 670
            }
        } else {
671 672
          SOCIALD_LOG_DEBUG("unknown recurrence information:" << ruleStr);
          traceDumpStr(QString::fromUtf8(QJsonDocument(recurrence).toJson()));
673 674 675 676
        }
    }
}

677 678
void extractOrganizer(const QJsonObject &creatorObj, const QJsonObject &organizerObj, KCalCore::Event::Ptr event)
{
679 680 681 682 683 684 685
    if (!organizerObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
                    || !organizerObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
            KCalCore::Person::Ptr organizer(new KCalCore::Person(
                    organizerObj.value(QLatin1String("displayName")).toVariant().toString(),
                    organizerObj.value(QLatin1String("email")).toVariant().toString()));
            event->setOrganizer(organizer);
    } else if (!creatorObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
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
                || !creatorObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
        KCalCore::Person::Ptr organizer(new KCalCore::Person(
                creatorObj.value(QLatin1String("displayName")).toVariant().toString(),
                creatorObj.value(QLatin1String("email")).toVariant().toString()));
        event->setOrganizer(organizer);
    } else {
        KCalCore::Person::Ptr organizer(new KCalCore::Person);
        event->setOrganizer(organizer);
    }
}

void extractAttendees(const QJsonArray &attendees, KCalCore::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()) {
            KCalCore::Attendee::Ptr attendee(new KCalCore::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(KCalCore::Attendee::OptParticipant);
                } else {
                    attendee->setRole(KCalCore::Attendee::ReqParticipant);
                }
            }
713 714 715 716 717 718 719 720 721 722 723 724 725
            if (attendeeObj.find(QLatin1String("responseStatus")) != attendeeObj.end()) {
                const QString &responseValue = attendeeObj.value(QLatin1String("responseStatus")).toVariant().toString();
                if (responseValue == "needsAction") {
                    attendee->setStatus(KCalCore::Attendee::NeedsAction);
                } else if (responseValue == "accepted") {
                    attendee->setStatus(KCalCore::Attendee::Accepted);
                } else if (responseValue == "declined") {
                    attendee->setStatus(KCalCore::Attendee::Declined);
                } else {
                    attendee->setStatus(KCalCore::Attendee::Tentative);
                }
            }
            attendee->setRSVP(true);
726
            event->addAttendee(attendee);
727 728 729 730 731 732 733 734 735 736 737 738
        } else {
            KCalCore::Person::Ptr calOrganizer = event->organizer();
            if (!calOrganizer.isNull() && !calOrganizer->isEmpty()) {
                continue;
            }
            if (!attendeeObj.value(QLatin1String("displayName")).toVariant().toString().isEmpty()
                        || !attendeeObj.value(QLatin1String("email")).toVariant().toString().isEmpty()) {
                KCalCore::Person::Ptr organizer(new KCalCore::Person(
                        attendeeObj.value(QLatin1String("displayName")).toVariant().toString(),
                        attendeeObj.value(QLatin1String("email")).toVariant().toString()));
                event->setOrganizer(organizer);
            }
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
#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)
764
{
765
    QSet<int> startOffsets;
766 767 768 769
    if (json.contains(QStringLiteral("reminders"))) {
        QJsonObject reminders = json.value(QStringLiteral("reminders")).toObject();
        if (reminders.value(QStringLiteral("useDefault")).toBool()) {
            if (defaultReminderStartOffset > 0) {
770
                startOffsets.insert(defaultReminderStartOffset);
771 772 773 774 775 776 777 778
            } 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")) {
779
                    startOffsets.insert(override.value(QStringLiteral("minutes")).toInt());
780 781 782
                }
            }
        }
783 784 785
        // 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++) {
786
            const int startOffset = (*it) * -60; // convert minutes to seconds (before event)
787 788
            SOCIALD_LOG_DEBUG("event needs reminder with start offset (seconds):" << startOffset);
            KCalCore::Alarm::List alarms = event->alarms();
789
            int alarmsCount = 0;
790 791 792
            for (int i = 0; i < alarms.count(); ++i) {
                // we don't count Procedure type alarms.
                if (alarms.at(i)->type() != KCalCore::Alarm::Procedure) {
793
                    alarmsCount += 1;
794
                    if (alarms.at(i)->startOffset().asSeconds() == startOffset) {
795
                        SOCIALD_LOG_DEBUG("event already has reminder with start offset (seconds):" << startOffset);
796
                    } else {
797 798
                        SOCIALD_LOG_DEBUG("event is missing reminder with start offset (seconds):" << startOffset);
                        needRemoveAndRecreate = true;
799 800 801
                    }
                }
            }
802 803 804 805 806 807 808 809 810 811 812
            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);
            KCalCore::Alarm::List alarms = event->alarms();
            for (int i = 0; i < alarms.count(); ++i) {
                if (alarms.at(i)->type() != KCalCore::Alarm::Procedure) {
                    event->removeAlarm(alarms.at(i));
813
                }
814 815
            }
            for (QSet<int>::const_iterator it = startOffsets.constBegin(); it != startOffsets.constEnd(); it++) {
816
                const int startOffset = (*it) * -60; // convert minutes to seconds (before event)
817
                SOCIALD_LOG_DEBUG("setting event reminder with start offset (seconds):" << startOffset);
818 819 820 821 822 823
                KCalCore::Alarm::Ptr alarm = event->newAlarm();
                alarm->setEnabled(true);
                alarm->setStartOffset(KCalCore::Duration(startOffset));
            }
        }
    }
824
    if (startOffsets.isEmpty()) {
825 826 827 828 829 830
        // 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());
831
                START_EVENT_UPDATES_IF_REQUIRED(event, changed);
832 833 834 835 836 837
                event->removeAlarm(alarms.at(i));
            }
        }
    }
}

838
void jsonToKCal(const QJsonObject &json, KCalCore::Event::Ptr event, int defaultReminderStartOffset, KCalCore::ICalFormat &icalFormat, bool *changed)
839
{
840
    Q_ASSERT(!event.isNull());
841
    bool alreadyStarted = *changed; // if this is true, we don't need to call startUpdates/endUpdates() in this function.
842 843 844
    const QString eventGCalETag(gCalETag(event));
    const QString jsonGCalETag(json.value(QLatin1String("etag")).toVariant().toString());
    if (!alreadyStarted && eventGCalETag == jsonGCalETag) {
845
        SOCIALD_LOG_DEBUG("Ignoring non-remote-changed:" << event->uid() << ","
846
                          << eventGCalETag << "==" << jsonGCalETag);
847 848 849
        return; // this event has not changed server-side since we last saw it.
    }

850
    KDateTime createdTimestamp, updatedTimestamp, start, end;
851 852 853
    bool startExists = false, endExists = false;
    bool startIsDateOnly = false, endIsDateOnly = false;
    bool isAllDay = false;
854
    extractCreatedAndUpdated(json, &createdTimestamp, &updatedTimestamp);
855
    extractStartAndEnd(json, &startExists, &endExists, &startIsDateOnly, &endIsDateOnly, &isAllDay, &start, &end);
856 857 858 859
    if (gCalEventId(event) != json.value(QLatin1String("id")).toVariant().toString()) {
        START_EVENT_UPDATES_IF_REQUIRED(event, changed);
        setGCalEventId(event, json.value(QLatin1String("id")).toVariant().toString());
    }
860
    if (eventGCalETag != jsonGCalETag) {
861
        START_EVENT_UPDATES_IF_REQUIRED(event, changed);
862
        setGCalETag(event, jsonGCalETag);
863
    }
864
    setRemoteUidCustomField(event, json.value(QLatin1String("iCalUID")).toVariant().toString(), json.value(QLatin1String("id")).toVariant().toString());
865
    extractRecurrence(json.value(QLatin1String("recurrence")).toArray(), event, icalFormat);
866 867
    extractOrganizer(json.value(QLatin1String("creator")).toObject(), json.value(QLatin1String("organizer")).toObject(), event);
    extractAttendees(json.value(QLatin1String("attendees")).toArray(), event);
868 869 870 871
    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)
872
    UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, revision, setRevision, json.value(QLatin1String("sequence")).toVariant().toInt(), changed)
873 874 875 876 877 878
    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)
    }
879
    if (startExists) {
880
        UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, dtStart, setDtStart, start, changed)
881 882
    }
    if (endExists) {
883 884 885 886 887
        if (!event->hasEndDate() || event->dtEnd() != end) {
            START_EVENT_UPDATES_IF_REQUIRED(event, changed);
            event->setHasEndDate(true);
            event->setDtEnd(end);
        }
888
    } else {
889
        UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, hasEndDate, setHasEndDate, false, changed)
890 891
    }
    if (isAllDay) {
892
        UPDATE_EVENT_PROPERTY_IF_REQUIRED(event, allDay, setAllDay, false, changed)
893
    }
894 895
    extractAlarms(json, event, defaultReminderStartOffset, changed);
    END_EVENT_UPDATES_IF_REQUIRED(event, changed, !alreadyStarted);
896 897
}

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
bool remoteModificationIsReal(const QJsonObject &json, KCalCore::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, KCalCore::ICalFormat &icalFormat)
{
    bool changed = true;
    KCalCore::Event::Ptr localEvent = KCalCore::Event::Ptr(new KCalCore::Event);
    KCalCore::Event::Ptr remoteEvent = KCalCore::Event::Ptr(new KCalCore::Event);
    jsonToKCal(local, localEvent, defaultReminderStartOffset, icalFormat, &changed);
    jsonToKCal(remote, remoteEvent, defaultReminderStartOffset, icalFormat, &changed);
916
    if (GoogleCalendarIncidenceComparator::incidencesEqual(localEvent, remoteEvent, true)) {
917 918 919 920 921
        return false; // they're equal, so the local modification is not real.
    }
    return true;
}

922 923 924
// 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.
925
bool wasLastSyncSuccessful(int accountId, bool *needCleanSync)
926 927
{
    QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
928
            .arg(PRIVILEGED_DATA_DIR)
929
            .arg(QString::fromLatin1(SYNC_DATABASE_DIR));
930 931 932 933 934 935
    if (!QFile::exists(settingsFileName)) {
        SOCIALD_LOG_DEBUG("gcal.ini settings file does not exist, triggering clean sync");
        *needCleanSync = true;
        return false;
    }

936
    QSettings settingsFile(settingsFileName, QSettings::IniFormat);
937 938
    // 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();
939 940
    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));
941 942 943 944 945 946
    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;
    }
947 948 949 950 951 952 953
    settingsFile.sync();
    return retn;
}

void setLastSyncSuccessful(QList<int> accountIds)
{
    QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
954
            .arg(PRIVILEGED_DATA_DIR)
955 956 957
            .arg(QString::fromLatin1(SYNC_DATABASE_DIR));
    QSettings settingsFile(settingsFileName, QSettings::IniFormat);
    Q_FOREACH(int accountId, accountIds) {
958
        settingsFile.setValue(QString::fromLatin1("%1-needCleanSync").arg(accountId), QVariant::fromValue<bool>(false));
959 960 961 962 963
        settingsFile.setValue(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(true));
    }
    settingsFile.sync();
}

964 965 966
void setLastSyncRequiresCleanSync(QList<int> accountIds)
{
    QString settingsFileName = QString::fromLatin1("%1/%2/gcal.ini")
967
            .arg(PRIVILEGED_DATA_DIR)
968 969 970 971 972 973 974 975 976
            .arg(QString::fromLatin1(SYNC_DATABASE_DIR));
    QSettings settingsFile(settingsFileName, QSettings::IniFormat);
    Q_FOREACH(int accountId, accountIds) {
        settingsFile.setValue(QString::fromLatin1("%1-needCleanSync").arg(accountId), QVariant::fromValue<bool>(true));
        settingsFile.setValue(QString::fromLatin1("%1-success").arg(accountId), QVariant::fromValue<bool>(false));
    }
    settingsFile.sync();
}

977 978
}

979 980
GoogleCalendarSyncAdaptor::GoogleCalendarSyncAdaptor(QObject *parent)
    : GoogleDataTypeSyncAdaptor(SocialNetworkSyncAdaptor::Calendars, parent)
981 982
    , m_calendar(mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(QLatin1String("UTC"))))
    , m_storage(mKCal::ExtendedCalendar::defaultStorage(m_calendar))
983
    , m_storageNeedsSave(false)
984
{
985
    setInitialActive(true);
986 987 988 989 990 991
}

GoogleCalendarSyncAdaptor::~GoogleCalendarSyncAdaptor()
{
}

992 993 994 995 996 997
QString GoogleCalendarSyncAdaptor::syncServiceName() const
{
    return QStringLiteral("google-calendars");
}

void GoogleCalendarSyncAdaptor::sync(const QString &dataTypeString, int accountId)
998 999
{
    m_storage->open(); // we close it in finalCleanup()
1000
    GoogleDataTypeSyncAdaptor::sync(dataTypeString, accountId);
1001 1002
}

1003 1004
void GoogleCalendarSyncAdaptor::finalCleanup()
{
1005 1006 1007 1008
    if (m_syncSucceeded.size()) {
        // there is only one account per sync run, even though we haven't fully
        // cleaned up the multi-account-isms from the member variables / API.
        int accountId = m_syncSucceeded.keys().first();
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        if (!m_syncSucceeded[accountId]) {
            // 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 KDateTime yesterdayDate = KDateTime::currentDateTime(KDateTime::Spec::UTC()).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(accountId, 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(KDateTime());
                    } 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);
                    m_storageNeedsSave = true;
                }
            }
        } else {
            // sync succeeded.  apply the changes to the database.
1038 1039
            applyRemoteChangesLocally(accountId);
            if (!m_syncSucceeded[accountId]) {
1040
                SOCIALD_LOG_INFO("Error occurred while applying remote changes locally");
1041 1042
            } else {
                Q_FOREACH (const QString &updatedCalendarId, m_calendarsFinishedRequested.keys()) {
1043 1044 1045 1046 1047
                    // 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.
1048 1049 1050 1051 1052 1053
                    QString updateTimestamp = m_calendarsFinishedRequested.value(updatedCalendarId);
                    mKCal::Notebook::Ptr notebook = notebookForCalendarId(accountId, updatedCalendarId);
                    if (!notebook) {
                        // may have been deleted due to a purge operation.
                        continue;
                    }
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

                    const KDateTime yesterdayDate = KDateTime::currentDateTime(KDateTime::Spec::UTC()).addDays(-1);
                    if (!updateTimestamp.isEmpty()) {
                        // set the sync date to the update timestamp provided by Google.
                        // if it is too far in the past, it might be rejected when used
                        // as a timeMin, which could trigger a 410 error, so instead
                        // in that case we set the timestamp to yesterday (we know there
                        // have been no changes in between those two dates, so no lost
                        // updates could occur).
                        const KDateTime oldSyncDate = notebook->syncDate();
                        KDateTime syncDate = datetimeFromUpdateStr(updateTimestamp);
                        if (qAbs(syncDate.daysTo(yesterdayDate)) >= 7) {
                            syncDate = yesterdayDate;
                        }
                        if (oldSyncDate < syncDate) {
                            notebook->setSyncDate(syncDate);
                        }
                    } else {
1072 1073
                        SOCIALD_LOG_ERROR("Error: no update timestamp, but no error detected!");
                        notebook->setSyncDate(yesterdayDate);
1074
                    }
1075

1076
                    // also update the remote sync token in each notebook.
1077 1078
                    notebook->setCustomProperty(NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY,
                                                m_calendarsNextSyncTokens.value(updatedCalendarId));
1079 1080 1081 1082 1083 1084
                    m_storage->updateNotebook(notebook);
                    m_storageNeedsSave = true;
                }
            }
        }
    }
1085

1086 1087 1088
    if (m_storageNeedsSave) {
        m_storage->save();
    }
1089
    m_storageNeedsSave = false;
1090 1091 1092 1093 1094 1095 1096 1097

    // 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);
        }
    }
1098 1099 1100
    if (succeededAccounts.size()) {
        setLastSyncSuccessful(succeededAccounts);
    }
1101 1102 1103 1104 1105 1106 1107 1108 1109
    QList<int> cleanSyncAccounts;
    Q_FOREACH (int accountId, m_cleanSyncRequired.keys()) {
        if (m_cleanSyncRequired.value(accountId)) {
            cleanSyncAccounts.append(accountId);
        }
    }
    if (cleanSyncAccounts.size()) {
        setLastSyncRequiresCleanSync(cleanSyncAccounts);
    }
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132

    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());
            }
        }
1133
        int foundOrphans = 0;
1134 1135 1136 1137 1138
        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()));
1139
                foundOrphans++;
1140 1141
            }
        }
1142
        if (foundOrphans == 0) {
1143 1144 1145 1146
            setGhostEventCleanupPerformed();
            SOCIALD_LOG_INFO("orphan cleanup completed without finding orphans!");
        } else if (m_storage->save()) {
            setGhostEventCleanupPerformed();
1147
            SOCIALD_LOG_INFO("orphan cleanup deleted" << foundOrphans << "; storage save completed!");
1148
        } else {
1149
            SOCIALD_LOG_ERROR("orphan cleanup found" << foundOrphans << "; but storage save failed!");
1150 1151 1152 1153
        }
    }

    m_storage->close();
1154 1155
}

1156
void GoogleCalendarSyncAdaptor::purgeDataForOldAccount(int oldId, SocialNetworkSyncAdaptor::PurgeMode mode)
1157
{
1158 1159 1160 1161 1162
    if (mode == SocialNetworkSyncAdaptor::CleanUpPurge) {
        // need to initialise the database
        m_storage->open(); // we close it in finalCleanup()
    }

1163
    // We clean all the entries in the calendar
1164 1165 1166 1167 1168 1169 1170 1171
    // 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;
1172 1173
        }
    }
1174 1175 1176 1177 1178

    if (mode == SocialNetworkSyncAdaptor::CleanUpPurge) {
        // and commit any changes made.
        finalCleanup();
    }
1179 1180 1181 1182
}

void GoogleCalendarSyncAdaptor::beginSync(int accountId, const QString &accessToken)
{
1183
    SOCIALD_LOG_DEBUG("beginning Calendar sync for Google, account" << accountId);
1184 1185
    bool needCleanSync = false;
    bool lastSyncSuccessful = wasLastSyncSuccessful(accountId, &needCleanSync);
1186
    if (needCleanSync) {
1187 1188 1189
        SOCIALD_LOG_INFO("performing clean sync");
    } else if (!lastSyncSuccessful) {
        SOCIALD_LOG_INFO("last sync was not successful, attempting to recover without clean sync");
1190
    }
1191
    m_serverCalendarIdToCalendarInfo[accountId].clear();
1192
    m_calendarIdToEventObjects[accountId].clear();
1193 1194
    m_syncSucceeded[accountId] = true; // set to false on error
    requestCalendars(accountId, accessToken, needCleanSync);
1195 1196
}

1197
void GoogleCalendarSyncAdaptor::requestCalendars(int accountId, const QString &accessToken, bool needCleanSync, const QString &pageToken)
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
{
    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());

1216
    QNetworkReply *reply = m_networkAccessManager->get(request);
1217 1218 1219 1220 1221 1222 1223

    // 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);
1224
        reply->setProperty("needCleanSync", QVariant::fromValue<bool>(needCleanSync));
1225 1226 1227 1228 1229
        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()));
1230 1231

        setupReplyTimeout(accountId, reply);
1232
    } else {
1233
        SOCIALD_LOG_ERROR("unable to request calendars from Google account with id" << accountId);
1234
        m_syncSucceeded[accountId] = false;
1235 1236 1237 1238 1239 1240 1241 1242 1243
        decrementSemaphore(accountId);
    }
}

void GoogleCalendarSyncAdaptor::calendarsFinishedHandler()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    int accountId = reply->property("accountId").toInt();
    QString accessToken = reply->property("accessToken").toString();
1244
    bool needCleanSync = reply->property("needCleanSync").toBool();
1245 1246 1247 1248 1249
    QByteArray replyData = reply->readAll();
    bool isError = reply->property("isError").toBool();

    disconnect(reply);
    reply->deleteLater();
1250
    removeReplyTimeout(accountId, reply);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

    // 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;
1261
            requestCalendars(accountId, accessToken, needCleanSync,
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
                             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();
1272
                if (accessRole == QStringLiteral("owner") || accessRole == QStringLiteral("writer")) {
1273 1274 1275 1276
                    GoogleCalendarSyncAdaptor::CalendarInfo currCalendarInfo;
                    currCalendarInfo.color = currCalendar.value(QStringLiteral("backgroundColor")).toString();
                    currCalendarInfo.summary = currCalendar.value(QStringLiteral("summary")).toString();
                    currCalendarInfo.description = currCalendar.value(QStringLiteral("description")).toString();
1277
                    currCalendarInfo.change = NoChange; // we detect the appropriate change type (if required) later.
1278 1279 1280 1281 1282
                    if (accessRole == QStringLiteral("owner")) {
                        currCalendarInfo.access = Owner;
                    } else {
                        currCalendarInfo.access = Writer;
                    }
1283
                    QString currCalendarId = currCalendar.value(QStringLiteral("id")).toString();
1284
                    m_serverCalendarIdToCalendarInfo[accountId].insert(currCalendarId, currCalendarInfo);
1285 1286 1287
                }
            }
        }
1288 1289
    } else {
        // error occurred during request.
1290 1291
        SOCIALD_LOG_ERROR("unable to parse calendar data from request with account" << accountId << "; got:");
        errorDumpStr(QString::fromLatin1(replyData.constData()));
1292
        m_syncSucceeded[accountId] = false;
1293 1294 1295 1296 1297 1298
    }

    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.
1299
        updateLocalCalendarNotebooks(accountId, accessToken, needCleanSync);
1300 1301 1302 1303 1304 1305 1306
    }

    // we're finished with this request.
    decrementSemaphore(accountId);
}


1307
void GoogleCalendarSyncAdaptor::updateLocalCalendarNotebooks(int accountId, const QString &accessToken, bool needCleanSync)
1308
{
1309 1310 1311 1312 1313
    if (syncAborted()) {
        SOCIALD_LOG_DEBUG("sync aborted, skipping updating local calendar notebooks");
        return;
    }

1314
    QMap<QString, CalendarInfo> &calendars = m_serverCalendarIdToCalendarInfo[accountId];
1315
    QMap<QString, QString> serverCalendarIdToSyncToken;
1316

1317
    // any calendars which exist on the device but not the server need to be purged.
1318
    QStringList calendarsToDelete;
1319
    QStringList deviceCalendarIds;
1320
    foreach (mKCal::Notebook::Ptr notebook, m_storage->notebooks()) {
1321 1322 1323 1324 1325
        // notebook pluginName is of form: google-calendarId
        // where the calendarId comes from the server.
        if (notebook->pluginName().startsWith(QStringLiteral("google-"))
                && notebook->account() == QString::number(accountId)) {
            QString currDeviceCalendarId = notebook->pluginName().mid(7);
1326 1327

            if (calendars.contains(currDeviceCalendarId)) {
1328
                // the server-side calendar exists on the device.
1329 1330 1331 1332 1333 1334
                const QString notebookNextSyncToken = notebook->customProperty(NOTEBOOK_SERVER_SYNC_TOKEN_PROPERTY);
                if (!notebookNextSyncToken.isEmpty()) {
                    serverCalendarIdToSyncToken.insert(currDeviceCalendarId, notebookNextSyncToken);
                }

                // check to see if we need to perform a clean sync cycle with this notebook.
1335 1336 1337
                if (needCleanSync) {
                    // we are performing a clean sync cycle.
                    // we will eventually delete and then insert this notebook.
1338 1339
                    SOCIALD_LOG_DEBUG("queueing clean sync of local calendar" << notebook->name()
                                      << currDeviceCalendarId << "for Google account:" << accountId);
1340
                    deviceCalendarIds.append(currDeviceCalendarId);
1341
                    calendars[currDeviceCalendarId].change = GoogleCalendarSyncAdaptor::CleanSync;
1342 1343 1344
                } else {
                    // we don't need to purge it, but we may need to update its summary/color details.
                    deviceCalendarIds.append(currDeviceCalendarId);
1345 1346 1347 1348
                    if (notebook->name() != calendars.value(currDeviceCalendarId).summary
                            || notebook->color() != calendars.value(currDeviceCalendarId).color
                            || notebook->description() != calendars.value(currDeviceCalendarId).description
                            || notebook->sharedWith() != QStringList(currDeviceCalendarId)
1349 1350
                            || notebook->isReadOnly()) {
                        // calendar information changed server-side.
1351 1352 1353
                        SOCIALD_LOG_DEBUG("queueing modification of local calendar" << notebook->name()
                                          << currDeviceCalendarId << "for Google account:" << accountId);
                        calendars[currDeviceCalendarId].change = GoogleCalendarSyncAdaptor::Modify;
1354 1355 1356
                    } else {
                        // the calendar information is unchanged server-side.
                        // no need to change anything locally.
1357 1358 1359
                        SOCIALD_LOG_DEBUG("No modification required for local calendar" << notebook->name()
                                          << currDeviceCalendarId << "for Google account:" << accountId);
                        calendars[currDeviceCalendarId].change = GoogleCalendarSyncAdaptor::NoChange;
1360
                    }
1361 1362 1363 1364
                }
            } else {
                // the calendar has been removed from the server.
                // we need to purge it from the device.
1365 1366
                SOCIALD_LOG_DEBUG("queueing removal of local calendar" << notebook->name() << currDeviceCalendarId
                                  << "for Google account:" << accountId);
1367
                calendarsToDelete.append(currDeviceCalendarId);
1368 1369 1370 1371 1372
            }
        }
    }

    // any calendarIds which exist on the server but not the device need to be created.
1373
    foreach (const QString &serverCalendarId, calendars.keys()) {
1374
        if (!deviceCalendarIds.contains(serverCalendarId)) {
1375
            SOCIALD_LOG_DEBUG("queueing addition of local calendar" << serverCalendarId
1376
                              << calendars.value(serverCalendarId).summary
1377
                              << "for Google account:" << accountId);
1378
            calendars[serverCalendarId].change = GoogleCalendarSyncAdaptor::Insert;
1379 1380 1381
        }
    }

1382
    SOCIALD_LOG_DEBUG("Syncing calendar events for Google account: " << accountId << " CleanSync: " << needCleanSync);
1383

1384
    foreach (const QString &calendarId, calendars.keys()) {
1385
        const QString syncToken = needCleanSync ? QString() : serverCalendarIdToSyncToken.value(calendarId);
1386
        requestEvents(accountId, accessToken, calendarId, syncToken);
1387 1388 1389 1390 1391 1392
        m_calendarsBeingRequested.append(calendarId);
    }

    // now we can queue the calendars which need deletion.
    // note: we have to do it after the previous foreach loop, otherwise we'd attempt to retrieve events for them.
    foreach (const QString &currDeviceCalendarId, calendarsToDelete) {
1393
        calendars[currDeviceCalendarId].change = GoogleCalendarSyncAdaptor::Delete;
1394 1395 1396
    }
}

1397
void GoogleCalendarSyncAdaptor::requestEvents(int accountId, const QString &accessToken, const QString &calendarId,
1398
                                              const QString &syncToken, const QString &pageToken)
1399
{
1400
    // get the last sync date stored into the notebook (if it exists).
1401 1402
    // we need to perform a "clean" sync if we don't have a valid sync date
    // or if we don't have a valid syncToken.
1403
    mKCal::Notebook::Ptr notebook = notebookForCalendarId(accountId, calendarId);
1404 1405
    KDateTime syncDate = notebook ? notebook->