File: cdbirthdaycalendar.cpp

package info (click to toggle)
contactsd 1.4.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,392 kB
  • sloc: cpp: 8,862; ansic: 3,793; sh: 361; xml: 75; python: 22; makefile: 13
file content (371 lines) | stat: -rw-r--r-- 12,904 bytes parent folder | download
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
/** This file is part of Contacts daemon
 **
 ** Copyright (c) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
 **
 ** Contact:  Nokia Corporation (info@qt.nokia.com)
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser General Public License
 ** version 2.1 as published by the Free Software Foundation and appearing in the
 ** file LICENSE.LGPL included in the packaging of this file.  Please review the
 ** following information to ensure the GNU Lesser General Public License version
 ** 2.1 requirements will be met:
 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain additional rights.
 ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included
 ** in the file LGPL_EXCEPTION.txt in this package.
 **
 ** Other Usage
 ** Alternatively, this file may be used in accordance with the terms and
 ** conditions contained in a signed written agreement between you and Nokia.
 **/

#include <QStringBuilder>

#include <QContactName>
#include <QContactBirthday>
#include <QContactDisplayLabel>
#include <QContactNickname>
#include <QContactOrganization>
#include <QContactEmailAddress>
#include <QContactId>

#include <seasidecache.h>

#include <MLocale>

#include <KCalendarCore/RecurrenceRule>

#include "cdbirthdaycalendar.h"
#include "debug.h"

using namespace ML10N;

// A random ID.
const QLatin1String calNotebookId("b1376da7-5555-1111-2222-227549c4e570");
const QLatin1String calNotebookColor("#e00080"); // Pink
const QString calIdExtension = QLatin1String("com.nokia.birthday/");


CDBirthdayCalendar::CDBirthdayCalendar(SyncMode syncMode, QObject *parent) :
    QObject(parent),
    mCalendar(0),
    mStorage(0)
{
    mCalendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(QTimeZone::systemTimeZone()));
    mStorage = mKCal::ExtendedCalendar::defaultStorage(mCalendar);

    MLocale * const locale = new MLocale(this);

    if (not locale->isInstalledTrCatalog(QLatin1String("calendar"))) {
        locale->installTrCatalog(QLatin1String("calendar"));
    }

    locale->connectSettings();
    connect(locale, SIGNAL(settingsChanged()), this, SLOT(onLocaleChanged()));

    MLocale::setDefault(*locale);

    mStorage->open();

    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        notebook = createNotebook();
        mStorage->addNotebook(notebook);
    } else {
        // Clear the calendar database if and only if restoring from a backup.
        switch(syncMode) {
        case KeepOldDB:
            // Force calendar name update, if a locale change happened while contactsd was not running.
            onLocaleChanged();
            break;

        case DropOldDB:
            mStorage->deleteNotebook(notebook);
            notebook = createNotebook();
            mStorage->addNotebook(notebook);
            break;
        }
    }
}

CDBirthdayCalendar::~CDBirthdayCalendar()
{
    if (mStorage) {
        mStorage->close();
    }

    qCDebug(lcContactsd) << "Destroyed birthday calendar";
}

mKCal::Notebook::Ptr CDBirthdayCalendar::createNotebook()
{
    return mKCal::Notebook::Ptr(new mKCal::Notebook(calNotebookId,
                                                    //% "Birthdays"
                                                    qtTrId("qtn_caln_birthdays"),
                                                    QLatin1String(""),
                                                    calNotebookColor,
                                                    false, // Not shared.
                                                    true, // Is master.
                                                    false, // Not synced to Ovi.
                                                    true, // Not writable.
                                                    true, // Visible.
                                                    QLatin1String("Birthday-Nokia"),
                                                    QLatin1String(""),
                                                    0));
}

QHash<QContactId, CalendarBirthday>
CDBirthdayCalendar::birthdays()
{
    if (not mStorage->loadNotebookIncidences(calNotebookId)) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Failed to load all incidences";
        return QHash<QContactId, CalendarBirthday>();
    }

    QHash<QContactId, CalendarBirthday> result;

    foreach(const KCalendarCore::Event::Ptr event, mCalendar->events()) {
        const QString eventUid = event->uid();
        const QContactId contactId = localContactId(eventUid);

        if (!contactId.isNull()) {
            result.insert(contactId, CalendarBirthday(event->dtStart().date(), event->summary()));
        } else {
            qCWarning(lcContactsd) << Q_FUNC_INFO << "Birthday event with a bad uid: " << eventUid;
        }
    }

    return result;
}

void CDBirthdayCalendar::updateBirthday(const QContact &contact)
{
    if (contact.id().isNull()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Updating birthday for null contact";
        return;
    }

    const QDate contactBirthday = contact.detail<QContactBirthday>().date();

    if (contactBirthday.isNull()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Contact without birthday, local ID: " << contact.id();
        return;
    }

    QString displayLabel = contact.detail<QContactDisplayLabel>().label();
    if (displayLabel.isEmpty()) {
        displayLabel = contact.detail<QContactNickname>().nickname();
    }
    if (displayLabel.isEmpty()) {
        displayLabel = contact.detail<QContactOrganization>().name();
    }
    if (displayLabel.isEmpty()) {
        displayLabel = contact.detail<QContactEmailAddress>().emailAddress();
    }

    if (displayLabel.isEmpty()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Contact without name to use " << contact.id();
        return;
    }

    QString eventId = calendarEventId(contact.id());
    if (eventId.isEmpty()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Failed to map contact id to calendar event id" << contact.id();
        return;
    }

    if (not mCalendar->hasValidNotebook(calNotebookId)) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Invalid notebook ID: " << calNotebookId;
        return;
    }

    // NOTE: if making changes beyond summary and date, increase event version number in controller.
    // NOTE: controller is assuming name as summary and uses that to detect changes

    // Retrieve birthday event.
    KCalendarCore::Event::Ptr event = calendarEvent(contact.id());

    if (event.isNull()) {
        // Add a new event.
        event = KCalendarCore::Event::Ptr(new KCalendarCore::Event());
        event->setUid(eventId);

        // Ensure events appear as birthdays in the calendar, NB#259710.
        event->setCategories(QStringList() << QLatin1String("BIRTHDAY"));

        if (not mCalendar->addEvent(event, calNotebookId)) {
            qCWarning(lcContactsd) << Q_FUNC_INFO << "Failed to add event to calendar";
            return;
        }
    } else {
        // Update the existing event.
        event->setReadOnly(false);
    }
    event->startUpdates();

    // Transfer birthday details from contact to calendar event.
    event->setSummary(displayLabel);

    // Event has only date information, no time.
    event->setDtStart(QDateTime(contactBirthday));
    event->setAllDay(true);

    // Must always set the recurrence as it depends on the event date.
    KCalendarCore::Recurrence *const recurrence = event->recurrence();

    if (contactBirthday.month() != 2 || contactBirthday.day() < 29) {
        // Simply setup yearly recurrence for trivial dates.
        recurrence->setStartDateTime(event->dtStart(), true);
        recurrence->setYearly(1); /* every year */
    } else {
        // For birthdays on February 29th the event shall occur on the
        // last day of February. This is February 29th in leap years,
        // and February 28th in all other years.
        //
        // NOTE: Actually this recurrence pattern will fail badly for
        // people born on February 29th of the years 2100, 2200, 2300,
        // 2500, ... - but I seriously doubt we care.
        //
        // NOTE2: Using setByYearDays() instead of just setting proper
        // start dates, since libmkcal fails to store the start dates
        // of recurrence rules.
        KCalendarCore::RecurrenceRule *rule;

        // 1. Include February 29th in leap years.
        rule = new KCalendarCore::RecurrenceRule;
        rule->setStartDt(event->dtStart());
        rule->setByYearDays(QList<int>() << 60); // Feb 29th
        rule->setRecurrenceType(KCalendarCore::RecurrenceRule::rYearly);
        rule->setFrequency(4); // every 4th year
        recurrence->addRRule(rule);

        // 2. Include February 28th starting from year after birth.
        rule = new KCalendarCore::RecurrenceRule;
        rule->setStartDt(event->dtStart());
        rule->setByYearDays(QList<int>() << 59); // Feb 28th
        rule->setRecurrenceType(KCalendarCore::RecurrenceRule::rYearly);
        rule->setFrequency(1); // every year
        recurrence->addRRule(rule);

        // 3. Exclude February 28th in leap years.
        rule = new KCalendarCore::RecurrenceRule;
        rule->setStartDt(event->dtStart());
        rule->setByYearDays(QList<int>() << 59); // Feb 28th
        rule->setRecurrenceType(KCalendarCore::RecurrenceRule::rYearly);
        rule->setFrequency(4); // every 4th year
        recurrence->addExRule(rule);

    }

    // Clear the alarms on the event
    event->clearAlarms();

    // We don't want any alarms for birthday events.
    // To set an alarm for birthday events, uncomment the code below.
    //KCalendarCore::Alarm::Ptr alarm = event->newAlarm();
    //alarm->setType(KCalendarCore::Alarm::Audio);
    //alarm->setEnabled(true);
    //alarm->setDisplayAlarm(event->summary());
    //alarm->setStartOffset(KCalendarCore::Duration(-36 * 3600 /* seconds */));

    event->setReadOnly(true);
    event->endUpdates();
    qCDebug(lcContactsd) << "Updated birthday event in calendar, local ID: " << contact.id();
}

void CDBirthdayCalendar::deleteBirthday(const QContactId &contactId)
{
    KCalendarCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        qCDebug(lcContactsd) << Q_FUNC_INFO << "Not found in calendar:" << contactId;
        return;
    }

    mCalendar->deleteEvent(event);

    qCDebug(lcContactsd) << "Deleted birthday event in calendar, local ID: " << event->uid();
}

void CDBirthdayCalendar::save()
{
    if (not mStorage->save()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Failed to update birthdays in calendar";
    }
}

CalendarBirthday CDBirthdayCalendar::birthday(const QContactId &contactId)
{
    KCalendarCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        return CalendarBirthday();
    }

    return CalendarBirthday(event->dtStart().date(), event->summary());
}

QContactId CDBirthdayCalendar::localContactId(const QString &calendarEventId)
{
    quint32 numericId = 0;

    if (calendarEventId.startsWith(calIdExtension)) {
        numericId = calendarEventId.mid(calIdExtension.length()).toUInt();
    }

    return SeasideCache::apiId(numericId);
}

QString CDBirthdayCalendar::calendarEventId(const QContactId &contactId)
{
    quint32 id = SeasideCache::internalId(contactId);
    if (id == 0) {
        return QString();
    }
    return calIdExtension + QString::number(id);
}

KCalendarCore::Event::Ptr CDBirthdayCalendar::calendarEvent(const QContactId &contactId)
{
    const QString eventId = calendarEventId(contactId);

    if (eventId.isEmpty()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Failed to map contact to event id" << contactId.toString();
        return KCalendarCore::Event::Ptr();
    }

    if (not mStorage->load(eventId)) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Unable to load event from calendar";
        return KCalendarCore::Event::Ptr();
    }

    KCalendarCore::Event::Ptr event = mCalendar->event(eventId);

    if (event.isNull()) {
        qCDebug(lcContactsd) << Q_FUNC_INFO << "Not found in calendar:" << contactId;
    }

    return event;
}

void CDBirthdayCalendar::onLocaleChanged()
{
    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Calendar not found while changing locale";
        return;
    }

    const QString name = qtTrId("qtn_caln_birthdays");

    qCDebug(lcContactsd) << Q_FUNC_INFO << "Updating calendar name to" << name;
    notebook->setName(name);

    if (not mStorage->updateNotebook(notebook)) {
        qCWarning(lcContactsd) << Q_FUNC_INFO << "Could not save calendar";
    }
}