contactsresource.cpp 16 KB
Newer Older
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
/*
    Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>

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

    You should have received a copy of the GNU Library General Public License
    along with this library; 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 "contactsresource.h"

#include "settingsadaptor.h"
#include "settingsdialog.h"

#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QFile>

#include <akonadi/changerecorder.h>
#include <akonadi/collectionfetchscope.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>
33
#include <akonadi/dbusconnectionpool.h>
34
#include <akonadi/agentfactory.h>
35
36
37
38

using namespace Akonadi;

ContactsResource::ContactsResource( const QString &id )
39
40
  : ResourceBase( id ),
  mSettings( new Settings( componentData().config() ) )
41
42
{
  // setup the resource
43
  new SettingsAdaptor( mSettings );
44
  DBusConnectionPool::threadConnection().registerObject( QLatin1String( "/Settings" ),
45
                            mSettings, QDBusConnection::ExportAdaptors );
46
47
48
49
50
51

  changeRecorder()->fetchCollection( true );
  changeRecorder()->itemFetchScope().fetchFullPayload( true );
  changeRecorder()->itemFetchScope().setAncestorRetrieval( ItemFetchScope::All );
  changeRecorder()->collectionFetchScope().setAncestorRetrieval( CollectionFetchScope::All );

52
53
  setHierarchicalRemoteIdentifiersEnabled( true );

54
  mSupportedMimeTypes << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType() << Collection::mimeType();
55

56
57
  if ( name().startsWith( QLatin1String( "akonadi_contacts_resource" ) ) )
    setName( i18n( "Personal Contacts" ) );
58

59
  if ( mSettings->isConfigured() )
60
    synchronize();
61
62
63
64
}

ContactsResource::~ContactsResource()
{
65
  delete mSettings;
66
67
68
69
70
71
72
73
}

void ContactsResource::aboutToQuit()
{
}

void ContactsResource::configure( WId windowId )
{
74
  SettingsDialog dlg( mSettings, windowId );
75
  if ( dlg.exec() ) {
76
77
    mSettings->setIsConfigured( true );
    mSettings->writeConfig();
78
79
80
81
82

    clearCache();
    initializeDirectory( baseDirectoryPath() );

    synchronize();
83
84
85
86

    emit configurationDialogAccepted();
  } else {
    emit configurationDialogRejected();
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  }
}

Collection::List ContactsResource::createCollectionsForDirectory( const QDir &parentDirectory, const Collection &parentCollection ) const
{
  Collection::List collections;

  QDir dir( parentDirectory );
  dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable );
  const QFileInfoList entries = dir.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    QDir subdir( entry.absoluteFilePath() );

    Collection collection;
    collection.setParentCollection( parentCollection );
    collection.setRemoteId( entry.fileName() );
    collection.setName( entry.fileName() );
    collection.setContentMimeTypes( mSupportedMimeTypes );
106
    collection.setRights( supportedRights( false ) );
107
108
109
110
111
112
113
114
115
116
117
118
119
120

    collections << collection;
    collections << createCollectionsForDirectory( subdir, collection );
  }

  return collections;
}

void ContactsResource::retrieveCollections()
{
  // create the resource collection
  Collection resourceCollection;
  resourceCollection.setParentCollection( Collection::root() );
  resourceCollection.setRemoteId( baseDirectoryPath() );
121
  resourceCollection.setName( name() );
122
  resourceCollection.setContentMimeTypes( mSupportedMimeTypes );
123
  resourceCollection.setRights( supportedRights( true ) );
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

  const QDir baseDir( baseDirectoryPath() );

  Collection::List collections = createCollectionsForDirectory( baseDir, resourceCollection );
  collections.append( resourceCollection );

  collectionsRetrieved( collections );
}

void ContactsResource::retrieveItems( const Akonadi::Collection &collection )
{
  QDir directory( directoryForCollection( collection ) );
  if ( !directory.exists() ) {
    cancelTask( i18n( "Directory '%1' does not exists", collection.remoteId() ) );
    return;
  }

  directory.setFilter( QDir::Files | QDir::Readable );

  Item::List items;

  const QFileInfoList entries = directory.entryInfoList();

  foreach ( const QFileInfo &entry, entries ) {
    if ( entry.fileName() == "WARNING_README.txt" )
      continue;

    Item item;
    item.setRemoteId( entry.fileName() );

    if ( entry.fileName().endsWith( ".vcf" ) )
      item.setMimeType( KABC::Addressee::mimeType() );
    else if ( entry.fileName().endsWith( ".ctg" ) )
      item.setMimeType( KABC::ContactGroup::mimeType() );
    else {
      cancelTask( i18n( "Found file of unknown format: '%1'", entry.absoluteFilePath() ) );
      return;
    }

    items.append( item );
  }

  itemsRetrieved( items );
}

bool ContactsResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray>& )
{
  const QString filePath = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  Item newItem( item );

  QFile file( filePath );
  if ( !file.open( QIODevice::ReadOnly ) ) {
    cancelTask( i18n( "Unable to open file '%1'", filePath ) );
    return false;
  }

  if ( filePath.endsWith( ".vcf" ) ) {
    KABC::VCardConverter converter;

    const QByteArray content = file.readAll();
    const KABC::Addressee contact = converter.parseVCard( content );
    if ( contact.isEmpty() ) {
      cancelTask( i18n( "Found invalid contact in file '%1'", filePath ) );
      return false;
    }

    newItem.setPayload<KABC::Addressee>( contact );
  } else if ( filePath.endsWith( ".ctg" ) ) {
    KABC::ContactGroup group;
    QString errorMessage;

    if ( !KABC::ContactGroupTool::convertFromXml( &file, group, &errorMessage ) ) {
Thomas Reitelbach's avatar
Thomas Reitelbach committed
197
      cancelTask( i18n( "Found invalid contact group in file '%1': %2", filePath, errorMessage ) );
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
      return false;
    }

    newItem.setPayload<KABC::ContactGroup>( group );
  } else {
    cancelTask( i18n( "Found file of unknown format: '%1'", filePath ) );
    return false;
  }

  file.close();

  itemRetrieved( newItem );

  return true;
}

void ContactsResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
216
  if ( mSettings->readOnly() ) {
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
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  const QString directoryPath = directoryForCollection( collection );

  Item newItem( item );

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    const QString fileName = directoryPath + QDir::separator() + contact.uid() + ".vcf";

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    file.write( content );
    file.close();

    newItem.setRemoteId( contact.uid() + ".vcf" );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    const QString fileName = directoryPath + QDir::separator() + group.id() + ".ctg";

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( group.id() + ".ctg" );

  } else {
262
    kWarning() << "got item without (usable) payload, ignoring it";
263
264
265
266
267
268
269
  }

  changeCommitted( newItem );
}

void ContactsResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray>& )
{
270
  if ( mSettings->readOnly() ) {
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
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

  Item newItem( item );

  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( item.hasPayload<KABC::Addressee>() ) {
    const KABC::Addressee contact = item.payload<KABC::Addressee>();

    KABC::VCardConverter converter;
    const QByteArray content = converter.createVCard( contact );

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }
    file.write( content );
    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else if ( item.hasPayload<KABC::ContactGroup>() ) {
    const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();

    QFile file( fileName );
    if ( !file.open( QIODevice::WriteOnly ) ) {
      cancelTask( i18n( "Unable to write to file '%1': %2", fileName, file.errorString() ) );
      return;
    }

    KABC::ContactGroupTool::convertToXml( group, &file );

    file.close();

    newItem.setRemoteId( item.remoteId() );

  } else {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
311
    cancelTask( i18n( "Received item with unknown payload %1", item.mimeType() ) );
312
313
314
315
316
317
318
319
    return;
  }

  changeCommitted( newItem );
}

void ContactsResource::itemRemoved( const Akonadi::Item &item )
{
320
  if ( mSettings->readOnly() ) {
321
322
323
324
    cancelTask( i18n( "Trying to write to a read-only file: '%1'", item.remoteId() ) );
    return;
  }

325
326
327
328
329
330
331
332
  // If the parent collection has no valid remote id, the parent
  // collection will be removed in a second, so stop here and remove
  // all items in collectionRemoved().
  if ( item.parentCollection().remoteId().isEmpty() ) {
    changeProcessed();
    return;
  }

333
334
335
336
337
338
339
340
341
342
343
344
  const QString fileName = directoryForCollection( item.parentCollection() ) + QDir::separator() + item.remoteId();

  if ( !QFile::remove( fileName ) ) {
    cancelTask( i18n( "Unable to remove file '%1'", fileName ) );
    return;
  }

  changeProcessed();
}

void ContactsResource::collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent )
{
345
  if ( mSettings->readOnly() ) {
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", parent.remoteId() ) );
    return;
  }

  const QString dirName = directoryForCollection( parent ) + QDir::separator() + collection.name();

  if ( !QDir::root().mkpath( dirName ) ) {
    cancelTask( i18n("Unable to create folder '%1'.", dirName ) );
    return;
  }

  initializeDirectory( dirName );

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

void ContactsResource::collectionChanged( const Akonadi::Collection &collection )
{
366
  if ( mSettings->readOnly() ) {
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

  if ( collection.parentCollection() == Collection::root() ) {
    if ( collection.name() != name() )
      setName( collection.name() );
    changeProcessed();
    return;
  }

  if ( collection.remoteId() == collection.name() ) {
    changeProcessed();
    return;
  }

  const QString dirName = directoryForCollection( collection );

  QFileInfo oldDirectory( dirName );
  if ( !QDir::root().rename( dirName, oldDirectory.absolutePath() + QDir::separator() + collection.name() ) ) {
    cancelTask( i18n("Unable to rename folder '%1'.", collection.name() ) );
    return;
  }

  Collection newCollection( collection );
  newCollection.setRemoteId( collection.name() );
  changeCommitted( newCollection );
}

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/**
 * Removes a @p directory recursively.
 */
static bool removeDirectory( const QDir &directory )
{
  const QFileInfoList infos = directory.entryInfoList( QDir::Files|QDir::Dirs|QDir::NoDotAndDotDot );
  foreach ( const QFileInfo &info, infos ) {
    if ( info.isDir() ) {
      if ( !removeDirectory( QDir( info.absoluteFilePath() ) ) )
        return false;
    } else {
      if ( !QFile::remove( info.filePath() ) )
        return false;
    }
  }

  if ( !QDir::root().rmdir( directory.absolutePath() ) )
    return false;

  return true;
}

418
419
void ContactsResource::collectionRemoved( const Akonadi::Collection &collection )
{
420
  if ( mSettings->readOnly() ) {
421
422
423
424
    cancelTask( i18n( "Trying to write to a read-only directory: '%1'", collection.remoteId() ) );
    return;
  }

425
  if ( !removeDirectory( directoryForCollection( collection ) ) ) {
426
    cancelTask( i18n( "Unable to delete folder '%1'.", collection.name() ) );
427
428
429
430
431
432
    return;
  }

  changeProcessed();
}

433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
void ContactsResource::itemMoved( const Akonadi::Item &item, const Akonadi::Collection &collectionSource,
                                  const Akonadi::Collection &collectionDestination )
{
  const QString sourceFileName = directoryForCollection( collectionSource ) + QDir::separator() + item.remoteId();
  const QString targetFileName = directoryForCollection( collectionDestination ) + QDir::separator() + item.remoteId();

  if ( QFile::rename( sourceFileName, targetFileName ) )
    changeProcessed();
  else
    cancelTask( i18n( "Unable to move file '%1' to '%2', '%2' already exists.", sourceFileName, targetFileName ) );
}

void ContactsResource::collectionMoved( const Akonadi::Collection &collection, const Akonadi::Collection &collectionSource,
                                        const Akonadi::Collection &collectionDestination )
{
  const QString sourceDirectoryName = directoryForCollection( collectionSource ) + QDir::separator() + collection.remoteId();
  const QString targetDirectoryName = directoryForCollection( collectionDestination ) + QDir::separator() + collection.remoteId();

  if ( QFile::rename( sourceDirectoryName, targetDirectoryName ) )
    changeProcessed();
  else
    cancelTask( i18n( "Unable to move directory '%1' to '%2', '%2' already exists.", sourceDirectoryName, targetDirectoryName ) );
}

457
458
QString ContactsResource::baseDirectoryPath() const
{
459
  return mSettings->path();
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
}

void ContactsResource::initializeDirectory( const QString &path ) const
{
  QDir dir( path );

  // if folder does not exists, create it
  if ( !dir.exists() )
    QDir::root().mkpath( dir.absolutePath() );

  // check whether warning file is in place...
  QFile file( dir.absolutePath() + QDir::separator() + "WARNING_README.txt" );
  if ( !file.exists() ) {
    // ... if not, create it
    file.open( QIODevice::WriteOnly );
    file.write( "Important Warning!!!\n\n"
                "Don't create or copy vCards inside this folder manually, they are managed by the Akonadi framework!\n" );
    file.close();
  }
}

481
Collection::Rights ContactsResource::supportedRights( bool isResourceCollection ) const
482
483
484
{
  Collection::Rights rights = Collection::ReadOnly;

485
  if ( !mSettings->readOnly() ) {
486
487
488
489
490
    rights |= Collection::CanChangeItem;
    rights |= Collection::CanCreateItem;
    rights |= Collection::CanDeleteItem;
    rights |= Collection::CanCreateCollection;
    rights |= Collection::CanChangeCollection;
491
492
493

    if ( !isResourceCollection )
      rights |= Collection::CanDeleteCollection;
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
  }

  return rights;
}

QString ContactsResource::directoryForCollection( const Collection& collection ) const
{
  if ( collection.remoteId().isEmpty() ) {
    kWarning() << "Got incomplete ancestor chain:" << collection;
    return QString();
  }

  if ( collection.parentCollection() == Collection::root() ) {
    kWarning( collection.remoteId() != baseDirectoryPath() ) << "RID mismatch, is " << collection.remoteId()
                                                             << " expected " << baseDirectoryPath();
    return collection.remoteId();
  }

  const QString parentDirectory = directoryForCollection( collection.parentCollection() );
  if ( parentDirectory.isNull() ) // invalid, != isEmpty() here!
    return QString();

  QString directory = parentDirectory;
  if ( !directory.endsWith( '/' ) )
    directory += QDir::separator() + collection.remoteId();
  else
    directory += collection.remoteId();

  return directory;
}

525
AKONADI_AGENT_FACTORY( ContactsResource, akonadi_contacts_resource )
526
527

#include "contactsresource.moc"