summaryrefslogtreecommitdiff
path: root/src/backends/akonadi/akonadisyncsource.cpp
blob: 6a676a38b44e0cff93197281e354233c82c7e8c2 (plain)
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
/*
    Copyright (c) 2009 Sascha Peilicke <sasch.pe@gmx.de>

    This application is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This application 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this application; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "akonadisyncsource.h"

#ifdef ENABLE_AKONADI

#include <Akonadi/ItemCreateJob>
#include <Akonadi/ItemDeleteJob>
#include <Akonadi/ItemFetchJob>
#include <Akonadi/ItemFetchScope>
#include <Akonadi/ItemModifyJob>

#include <Akonadi/CollectionFetchJob>
#include <Akonadi/CollectionFetchScope>

#include <Akonadi/CollectionStatistics>
#include <Akonadi/CollectionStatisticsJob>

#include <Akonadi/ServerManager>
#include <Akonadi/Control>
#include <kurl.h>

#include <QtCore/QDebug>

SE_BEGIN_CXX
using namespace Akonadi;

/**
 * We take over ownership of jobs by storing them in smart pointers
 * (RAII).  This is how SyncEvolution does things and more predictable
 * than assuming that a future exec() call will auto-delete them as
 * part of its event processing.
 *
 * To avoid double frees, we need to disable auto-deletion.
 * This method does that. Use like this:
 * std::auto_ptr<CollectionStatisticsJob> statisticsJob(DisableAutoDelete(new CollectionStatisticsJob(m_collection)));
 */
template<class J> J *DisableAutoDelete(J *job) { job->setAutoDelete(false); return job; }

AkonadiSyncSource::AkonadiSyncSource(const char *submime,
                                     const SyncSourceParams &params)
    : TrackingSyncSource(params)
    , m_subMime(submime)
{
}

AkonadiSyncSource::~AkonadiSyncSource()
{
}

bool AkonadiSyncSource::isEmpty()
{
    //To Check if the respective collection is Empty, without actually loading the collections
    std::auto_ptr<CollectionStatisticsJob> statisticsJob(DisableAutoDelete(new CollectionStatisticsJob(m_collection)));
    if (!statisticsJob->exec()) {
        throwError("Error fetching the collection stats");
    }
    return statisticsJob->statistics().count() == 0;
}

void AkonadiSyncSource::start()
{
    // Start The Akonadi Server if not already Running.
    if (!Akonadi::ServerManager::isRunning()) {
        // Don't try to start it. A normal KDE user should have it already
        // running. Users of other desktop systems probably don't want it
        // to run, if they have it installed at all.
        //
        // Starting it here also produces output that we don't want mixed
        // into normal SyncEvolution command line output.
#if 0
        SE_LOG_DEBUG(NULL, "Akonadi Server isn't running, and hence starting it.");
        if (!Akonadi::Control::start()) {
            SE_THROW("Couldn't Start Akonadi Server: hence the akonadi backend of syncevolution wont work ..");
        }
#else
        SE_THROW("Akonadi is not running. It can be started with 'akonadictl start'.");
#endif
    }
}

SyncSource::Databases AkonadiSyncSource::getDatabases()
{
    start();

    Databases res;
    QStringList mimeTypes;
    mimeTypes << m_subMime.c_str();
    // Insert databases which match the "type" of the source, including a user-visible
    // description and a database IDs. Exactly one of the databases  should be marked
    // as the default one used by the source.
    // res.push_back("Contacts", "some-KDE-specific-ID", isDefault);

    std::auto_ptr<CollectionFetchJob> fetchJob(DisableAutoDelete(new CollectionFetchJob(Collection::root(),
                                                                                        CollectionFetchJob::Recursive)));

    fetchJob->fetchScope().setContentMimeTypes(mimeTypes);

    if (!fetchJob->exec()) {
        throwError("cannot list collections");
    }

    // Currently, the first collection of the right type is the default
    // This decision should go to the GUI: which deals with sync profiles.

    bool isFirst = true;
    Collection::List collections = fetchJob->collections();
    foreach (const Collection &collection, collections) {
        res.push_back(Database(collection.name().toUtf8().constData(),
                               collection.url().url().toUtf8().constData(),
                               isFirst));
        isFirst = false;
    }
    return res;
}

void AkonadiSyncSource::open()
{
    start();

    // the "evolutionsource" property, empty for default,
    // otherwise the collection URL or a name
    string id = getDatabaseID();

    // hack for testing: use first resp. second database
    if (boost::starts_with(id, "Test_")) {
        Databases databases = getDatabases();
        ssize_t index = -1;
        if (boost::ends_with(id, "_1")) {
            index = 0;
        } else if (boost::ends_with(id, "_2")) {
            index = 1;
        }
        if (index >= 0) {
            if (databases.size() <= (size_t)index) {
                SE_THROW("need two Akonadi resources for testing");
            }
            id = databases[index].m_uri;
            SE_LOG_DEBUG(NULL, "testing Akonadi with %s", id.c_str());
        }
    }

    if (!boost::starts_with(id, "akonadi:")) {
        // TODO: support selection by name and empty ID for default
        SE_THROW("database must be selected via database = akonadi:?collection=<number>");
    }

    m_collection = Collection::fromUrl(KUrl(id.c_str()));
}

void AkonadiSyncSource::listAllItems(SyncSourceRevisions::RevisionMap_t &revisions)
{
    // copy all local IDs and the corresponding revision
    std::auto_ptr<ItemFetchJob> fetchJob(DisableAutoDelete(new ItemFetchJob(m_collection)));

    if (!fetchJob->exec()) {
        throwError("listing items");
    }
    BOOST_FOREACH (const Item &item, fetchJob->items()) {
        // Filter out items which don't have the right type (for example, VTODO when
        // syncing events)
        if (item.mimeType() == m_subMime.c_str()) {
            revisions[QByteArray::number(item.id()).constData()] =
                      QByteArray::number(item.revision()).constData();
        }
    }
}

void AkonadiSyncSource::close()
{
    // TODO: close collection!?
}

TrackingSyncSource::InsertItemResult AkonadiSyncSource::insertItem(const std::string &luid, const std::string &data, bool raw)
{
    Item item;

    if (luid.empty()) {
        item.setMimeType(m_subMime.c_str());
        item.setPayloadFromData(QByteArray(data.c_str()));
        std::auto_ptr<ItemCreateJob> createJob(DisableAutoDelete(new ItemCreateJob(item, m_collection)));
        if (!createJob->exec()) {
            throwError(string("storing new item ") + luid);
            return InsertItemResult("", "", ITEM_OKAY);
        }
        item = createJob->item();
    } else {
        Entity::Id syncItemId = QByteArray(luid.c_str()).toLongLong();
        std::auto_ptr<ItemFetchJob> fetchJob(DisableAutoDelete(new ItemFetchJob(Item(syncItemId))));
        if (!fetchJob->exec()) {
            throwError(string("checking item ") + luid);
        }
        item = fetchJob->items().first();
        item.setPayloadFromData(QByteArray(data.c_str()));
        std::auto_ptr<ItemModifyJob> modifyJob(DisableAutoDelete(new ItemModifyJob(item)));
        // TODO: SyncEvolution must pass the known revision that
        // we are updating.
        // TODO: check that the item has not been updated in the meantime
        if (!modifyJob->exec()) {
            throwError(string("updating item ") + luid);
            return InsertItemResult("", "", ITEM_OKAY);
        }
        item = modifyJob->item();
    }

    // Read-only datastores may not have actually added something here!
    // The Jobs themselves throw errors, and hence the return statements
    // above will take care of this
    return InsertItemResult(QByteArray::number(item.id()).constData(),
                            QByteArray::number(item.revision()).constData(),
                            ITEM_OKAY);
}

void AkonadiSyncSource::removeItem(const string &luid)
{
    Entity::Id syncItemId = QByteArray(luid.c_str()).toLongLong();

    // Delete the item from our collection
    // TODO: check that the revision is right (need revision from SyncEvolution)
    std::auto_ptr<ItemDeleteJob> deleteJob(DisableAutoDelete(new ItemDeleteJob(Item(syncItemId))));
    if (!deleteJob->exec()) {
        throwError(string("deleting item " ) + luid);
    }
}

void AkonadiSyncSource::readItem(const std::string &luid, std::string &data, bool raw)
{
    Entity::Id syncItemId = QByteArray(luid.c_str()).toLongLong();

    std::auto_ptr<ItemFetchJob> fetchJob(DisableAutoDelete(new ItemFetchJob(Item(syncItemId))));
    fetchJob->fetchScope().fetchFullPayload();
    if (fetchJob->exec()) {
        if (fetchJob->items().empty()) {
            throwError(STATUS_NOT_FOUND, string("extracting item ") + luid);
        }
        QByteArray payload = fetchJob->items().first().payloadData();
        data.assign(payload.constData(),
                    payload.size());
    } else {
        throwError(string("extracting item " ) + luid);
    }
}

QString AkonadiMemoSource::toKJots(QString data){
  // KJots stores it's resource in the format
  //Subject: Hello World
  //Content-Type: text/plain <------- always plain text for the akonadi resource
  //Date: Wed, 30 Mar 2011 01:02:48 +0530 <----date created
  //MIME-Version: 1.0 <----- always the same
  // <---- This line break seperates the content from the information
  //<Content>

  QString subject = "Subject: ";
  QString contentType = "Content-Type: text/plain";
  QString dateTime = QDateTime::currentDateTime().toString(Qt::ISODate);
  QString mimeVersion = "MIME-Version: 1.0";
  QString content;
  
  QStringList lines = data.split('\n');
  subject += lines.first();
  content = data.remove(0,data.indexOf('\n')+1);
  
  QString result = subject + '\n' +
                   contentType + '\n' +
                   dateTime + '\n'+
                   mimeVersion + "\n\n"+
                   content;
  return result;
}

QString AkonadiMemoSource::toSynthesis(QString data){
    //Synthesis expects Plain Text in the form Subject + "\n" + Content
    QString subject;
    QString content;
  
    subject = data.split('\n').first();
    subject.remove("Subject: ");
    
    content = data.remove(0,data.indexOf("\n\n")+2);
    return subject+'\n'+content;
}

void AkonadiMemoSource::readItem(const std::string &luid, std::string &data, bool raw)
{
    AkonadiSyncSource::readItem(luid, data, raw);
    data = toSynthesis(QString::fromStdString(data)).toStdString();
}

TrackingSyncSource::InsertItemResult AkonadiMemoSource::insertItem(const std::string &luid, const std::string &data, bool raw)
{
    std::string formattedData = toKJots(QString::fromStdString(data)).toStdString();
    return AkonadiSyncSource::insertItem(luid, formattedData , raw);
}

SE_END_CXX
#endif // ENABLE_AKONADI

#ifdef ENABLE_MODULES
# include "AkonadiSyncSourceRegister.cpp"
#endif