-
Notifications
You must be signed in to change notification settings - Fork 10
/
ewsresource.cpp
1421 lines (1230 loc) · 51.3 KB
/
ewsresource.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of Akonadi EWS Resource
Copyright (C) 2015-2017 Krzysztof Nowicki <krissn@op.pl>
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 "ewsresource.h"
#include <QDebug>
#include <KI18n/KLocalizedString>
#include <AkonadiCore/ChangeRecorder>
#include <AkonadiCore/CollectionFetchScope>
#include <AkonadiCore/ItemFetchScope>
#include <AkonadiCore/CollectionFetchJob>
#include <AkonadiCore/CollectionModifyJob>
#include <AkonadiCore/EntityDisplayAttribute>
#include <Akonadi/KMime/SpecialMailCollections>
#include <KMime/Message>
#include <KWallet/KWallet>
#include <KWidgetsAddons/KPasswordDialog>
#include "ewsfetchitemsjob.h"
#include "ewsfetchfoldersjob.h"
#include "ewsfetchfoldersincrjob.h"
#include "ewsgetitemrequest.h"
#include "ewsupdateitemrequest.h"
#include "ewsmodifyitemflagsjob.h"
#include "ewsmoveitemrequest.h"
#include "ewsdeleteitemrequest.h"
#include "ewscreatefolderrequest.h"
#include "ewsmovefolderrequest.h"
#include "ewsupdatefolderrequest.h"
#include "ewsdeletefolderrequest.h"
#include "ewssubscriptionmanager.h"
#include "ewsgetfolderrequest.h"
#include "ewsitemhandler.h"
#include "ewsmodifyitemjob.h"
#include "ewscreateitemjob.h"
#include "configdialog.h"
#include "settings.h"
#ifdef HAVE_SEPARATE_MTA_RESOURCE
#include "ewscreateitemrequest.h"
#endif
#include "tags/ewstagstore.h"
#include "tags/ewsupdateitemstagsjob.h"
#include "tags/ewsglobaltagswritejob.h"
#include "tags/ewsglobaltagsreadjob.h"
#include "ewsclient_debug.h"
#include "ewsresource_debug.h"
#include "resourceadaptor.h"
#include "settingsadaptor.h"
#include "walletadaptor.h"
using namespace Akonadi;
struct SpecialFolders {
EwsDistinguishedId did;
SpecialMailCollections::Type type;
QString iconName;
};
static const QVector<SpecialFolders> specialFolderList = {
{EwsDIdInbox, SpecialMailCollections::Inbox, QStringLiteral("mail-folder-inbox")},
{EwsDIdOutbox, SpecialMailCollections::Outbox, QStringLiteral("mail-folder-outbox")},
{EwsDIdSentItems, SpecialMailCollections::SentMail, QStringLiteral("mail-folder-sent")},
{EwsDIdDeletedItems, SpecialMailCollections::Trash, QStringLiteral("user-trash")},
{EwsDIdDrafts, SpecialMailCollections::Drafts, QStringLiteral("document-properties")}
};
const QString EwsResource::akonadiEwsPropsetUuid = QStringLiteral("9bf757ae-69b5-4d8a-bf1d-2dd0c0871a28");
const EwsPropertyField EwsResource::globalTagsProperty(EwsResource::akonadiEwsPropsetUuid,
QStringLiteral("GlobalTags"),
EwsPropTypeStringArray);
const EwsPropertyField EwsResource::globalTagsVersionProperty(EwsResource::akonadiEwsPropsetUuid,
QStringLiteral("GlobalTagsVersion"),
EwsPropTypeInteger);
const EwsPropertyField EwsResource::tagsProperty(EwsResource::akonadiEwsPropsetUuid,
QStringLiteral("Tags"), EwsPropTypeStringArray);
const EwsPropertyField EwsResource::flagsProperty(EwsResource::akonadiEwsPropsetUuid,
QStringLiteral("Flags"), EwsPropTypeStringArray);
static Q_CONSTEXPR int InitialReconnectTimeout = 60;
static Q_CONSTEXPR int ReconnectTimeout = 300;
EwsResource::EwsResource(const QString &id)
: Akonadi::ResourceBase(id), mTagsRetrieved(false), mReconnectTimeout(InitialReconnectTimeout),
mSettings(new Settings(winIdForDialogs()))
{
//setName(i18n("Microsoft Exchange"));
mEwsClient.setUrl(mSettings->baseUrl());
mSettings->requestPassword(mPassword, true);
if (!mSettings->hasDomain()) {
mEwsClient.setCredentials(mSettings->username(), mPassword);
} else {
mEwsClient.setCredentials(mSettings->domain() + '\\' + mSettings->username(), mPassword);
}
mEwsClient.setUserAgent(mSettings->userAgent());
mEwsClient.setEnableNTLMv2(mSettings->enableNTLMv2());
changeRecorder()->fetchCollection(true);
changeRecorder()->collectionFetchScope().setAncestorRetrieval(CollectionFetchScope::Parent);
changeRecorder()->itemFetchScope().fetchFullPayload(true);
changeRecorder()->itemFetchScope().setAncestorRetrieval(ItemFetchScope::Parent);
changeRecorder()->itemFetchScope().setFetchModificationTime(false);
changeRecorder()->itemFetchScope().setFetchTags(true);
mRootCollection.setParentCollection(Collection::root());
mRootCollection.setName(name());
mRootCollection.setContentMimeTypes(QStringList() << Collection::mimeType() << KMime::Message::mimeType());
mRootCollection.setRights(Collection::ReadOnly);
setScheduleAttributeSyncBeforeItemSync(true);
if (mSettings->baseUrl().isEmpty()) {
setOnline(false);
Q_EMIT status(NotConfigured, i18nc("@info:status", "No server configured yet."));
} else {
resetUrl();
}
// Load the sync state
QByteArray data = QByteArray::fromBase64(mSettings->syncState().toAscii());
if (!data.isEmpty()) {
data = qUncompress(data);
if (!data.isEmpty()) {
QDataStream stream(data);
stream >> mSyncState;
}
}
data = QByteArray::fromBase64(mSettings->folderSyncState().toAscii());
if (!data.isEmpty()) {
data = qUncompress(data);
if (!data.isEmpty()) {
mFolderSyncState = QString::fromAscii(data);
}
}
setHierarchicalRemoteIdentifiersEnabled(true);
mTagStore = new EwsTagStore(this);
QMetaObject::invokeMethod(this, "delayedInit", Qt::QueuedConnection);
connect(this, &AgentBase::reloadConfiguration, this, &EwsResource::reloadConfig);
}
EwsResource::~EwsResource()
{
}
void EwsResource::delayedInit()
{
new ResourceAdaptor(this);
new SettingsAdaptor(mSettings.data());
new WalletAdaptor(mSettings.data());
QDBusConnection::sessionBus().registerObject(QStringLiteral("/Settings"),
mSettings.data(), QDBusConnection::ExportAdaptors);
}
void EwsResource::resetUrl()
{
Q_EMIT status(Running, i18nc("@info:status", "Connecting to Exchange server"));
EwsGetFolderRequest *req = new EwsGetFolderRequest(mEwsClient, this);
EwsId::List folders;
folders << EwsId(EwsDIdMsgFolderRoot);
folders << EwsId(EwsDIdInbox);
req->setFolderIds(folders);
EwsFolderShape shape(EwsShapeIdOnly);
shape << EwsPropertyField(QStringLiteral("folder:DisplayName"));
// Use the opportunity of reading the root folder to read the tag data.
shape << globalTagsProperty << globalTagsVersionProperty;
req->setFolderShape(shape);
connect(req, &EwsRequest::result, this, &EwsResource::rootFolderFetchFinished);
req->start();
}
void EwsResource::rootFolderFetchFinished(KJob *job)
{
EwsGetFolderRequest *req = qobject_cast<EwsGetFolderRequest*>(job);
if (!req) {
Q_EMIT status(Idle, i18nc("@info:status", "Unable to connect to Exchange server"));
setTemporaryOffline(reconnectTimeout());
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid EwsGetFolderRequest job object");
return;
}
if (req->error()) {
Q_EMIT status(Idle, i18nc("@info:status", "Unable to connect to Exchange server"));
setTemporaryOffline(reconnectTimeout());
qWarning() << "ERROR" << req->errorString();
return;
}
if (req->responses().size() != 2) {
Q_EMIT status(Idle, i18nc("@info:status", "Unable to connect to Exchange server"));
setTemporaryOffline(reconnectTimeout());
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid number of responses received");
return;
}
EwsFolder folder = req->responses()[1].folder();
EwsId id = folder[EwsFolderFieldFolderId].value<EwsId>();
if (id.type() == EwsId::Real) {
#ifdef HAVE_INBOX_FILTERING_WORKAROUND
EwsId::setInboxId(id);
Collection c;
c.setRemoteId(id.id());
CollectionFetchJob *job = new CollectionFetchJob(c, CollectionFetchJob::Base, this);
job->setFetchScope(changeRecorder()->collectionFetchScope());
job->fetchScope().setResource(identifier());
job->fetchScope().setListFilter(CollectionFetchScope::Sync);
connect(job, &CollectionFetchJob::result, this, &EwsResource::adjustInboxRemoteIdFetchFinished);
#else
Collection c;
c.setRemoteId(QStringLiteral("INBOX"));
CollectionFetchJob *job = new CollectionFetchJob(c, CollectionFetchJob::Base, this);
job->setFetchScope(changeRecorder()->collectionFetchScope());
job->fetchScope().setResource(identifier());
job->fetchScope().setListFilter(CollectionFetchScope::Sync);
job->setProperty("inboxId", id.id());
connect(job, &CollectionFetchJob::result, this, &EwsResource::adjustInboxRemoteIdFetchFinished);
int inboxIdx = mSettings->serverSubscriptionList().indexOf(QStringLiteral("INBOX"));
if (inboxIdx >= 0) {
QStringList subList = mSettings->serverSubscriptionList();
subList[inboxIdx] = id.id();
mSettings->setServerSubscriptionList(subList);
}
#endif
}
folder = req->responses().first().folder();
id = folder[EwsFolderFieldFolderId].value<EwsId>();
if (id.type() == EwsId::Real) {
mRootCollection.setRemoteId(id.id());
mRootCollection.setRemoteRevision(id.changeKey());
qCDebug(EWSRES_LOG) << "Root folder is " << id;
Q_EMIT status(Idle, i18nc("@info:status Resource is ready", "Ready"));
if (mSettings->serverSubscription()) {
mSubManager.reset(new EwsSubscriptionManager(mEwsClient, id, mSettings.data(), this));
connect(mSubManager.data(), &EwsSubscriptionManager::foldersModified, this, &EwsResource::foldersModifiedEvent);
connect(mSubManager.data(), &EwsSubscriptionManager::folderTreeModified, this, &EwsResource::folderTreeModifiedEvent);
connect(mSubManager.data(), &EwsSubscriptionManager::fullSyncRequested, this, &EwsResource::fullSyncRequestedEvent);
/* Use a queued connection here as the connectionError() method will actually destroy the subscription manager. If this
* was done with a direct connection this would have ended up with destroying the caller object followed by a crash. */
connect(mSubManager.data(), &EwsSubscriptionManager::connectionError, this, &EwsResource::connectionError,
Qt::QueuedConnection);
mSubManager->start();
}
synchronizeCollectionTree();
mTagStore->readTags(folder[globalTagsProperty].toStringList(), folder[globalTagsVersionProperty].toInt());
}
}
void EwsResource::adjustInboxRemoteIdFetchFinished(KJob *job)
{
if (!job->error()) {
CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);
Q_ASSERT(fetchJob);
if (!fetchJob->collections().isEmpty()) {
Collection c = fetchJob->collections()[0];
#ifdef HAVE_INBOX_FILTERING_WORKAROUND
c.setRemoteId(QStringLiteral("INBOX"));
#else
c.setRemoteId(fetchJob->property("inboxId").toString());
#endif
CollectionModifyJob *modifyJob = new CollectionModifyJob(c, this);
modifyJob->start();
}
}
}
void EwsResource::retrieveCollections()
{
if (mRootCollection.remoteId().isNull()) {
cancelTask(QStringLiteral("Root folder id not known."));
return;
}
Q_EMIT status(Running, i18nc("@info:status", "Retrieving collection tree"));
if (!mFolderSyncState.isEmpty() && !mRootCollection.isValid()) {
/* When doing an incremental sync the real Akonadi identifier of the root collection must
* be known, because the retrieved list of changes needs to include all parent folders up
* to the root. None of the child collections are required to be valid, but the root must
* be, as it needs to be the anchor point.
*/
CollectionFetchJob *fetchJob = new CollectionFetchJob(mRootCollection,
CollectionFetchJob::Base);
connect(fetchJob, &CollectionFetchJob::result, this, &EwsResource::rootCollectionFetched);
fetchJob->start();
} else {
doRetrieveCollections();
}
synchronizeTags();
}
void EwsResource::rootCollectionFetched(KJob *job)
{
if (job->error()) {
qCWarning(EWSRES_LOG) << "ERROR" << job->errorString();
} else {
CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);
if (fetchJob && !fetchJob->collections().isEmpty()) {
mRootCollection = fetchJob->collections().first();
qCDebugNC(EWSRES_LOG) << QStringLiteral("Root collection fetched: ") << mRootCollection;
}
}
/* If the fetch failed for whatever reason force a full sync, which doesn't require the root
* collection to be valid. */
if (!mRootCollection.isValid()) {
mFolderSyncState.clear();
}
doRetrieveCollections();
}
void EwsResource::doRetrieveCollections()
{
if (mFolderSyncState.isEmpty()) {
EwsFetchFoldersJob *job = new EwsFetchFoldersJob(mEwsClient, mRootCollection, this);
connect(job, &EwsFetchFoldersJob::result, this, &EwsResource::fetchFoldersJobFinished);
job->start();
}
else {
EwsFetchFoldersIncrJob *job = new EwsFetchFoldersIncrJob(mEwsClient, mFolderSyncState,
mRootCollection, this);
connect(job, &EwsFetchFoldersIncrJob::result, this, &EwsResource::fetchFoldersIncrJobFinished);
job->start();
}
}
void EwsResource::connectionError()
{
Q_EMIT status(Broken, i18nc("@info:status", "Unable to connect to Exchange server"));
setTemporaryOffline(reconnectTimeout());
}
void EwsResource::retrieveItems(const Collection &collection)
{
Q_EMIT status(1, QStringLiteral("Retrieving item list"));
Q_EMIT status(Running, i18nc("@info:status", "Retrieving %1 items", collection.name()));
QString rid = collection.remoteId();
EwsFetchItemsJob *job = new EwsFetchItemsJob(collection, mEwsClient,
mSyncState.value(rid), mItemsToCheck.value(rid), mTagStore, this);
job->setQueuedUpdates(mQueuedUpdates.value(collection.remoteId()));
mQueuedUpdates.remove(collection.remoteId());
connect(job, &EwsFetchItemsJob::result, this, &EwsResource::itemFetchJobFinished);
connect(job, &EwsFetchItemsJob::status, this, [this](int s, const QString &message) {
status(s, message);
});
connect(job, &EwsFetchItemsJob::percent, this, [this](int p) {
percent(p);
});
job->start();
}
#if (AKONADI_VERSION > 0x50328)
bool EwsResource::retrieveItems(const Item::List &items, const QSet<QByteArray> &parts)
{
qCDebugNC(EWSRES_AGENTIF_LOG) << "retrieveItems: start " << items << parts;
EwsGetItemRequest *req = new EwsGetItemRequest(mEwsClient, this);
EwsId::List ids;
Q_FOREACH(const Item &item, items) {
ids << EwsId(item.remoteId(), item.remoteRevision());
}
req->setItemIds(ids);
EwsItemShape shape(EwsShapeIdOnly);
shape << EwsPropertyField("item:MimeContent");
req->setItemShape(shape);
req->setProperty("items", QVariant::fromValue<Item::List>(items));
connect(req, &EwsGetItemRequest::result, this, &EwsResource::getItemsRequestFinished);
req->start();
return true;
}
void EwsResource::getItemsRequestFinished(KJob *job)
{
if (job->error()) {
qWarning() << "ERROR" << job->errorString();
cancelTask(job->errorString());
return;
}
EwsGetItemRequest *req = qobject_cast<EwsGetItemRequest*>(job);
if (!req) {
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid EwsGetItemRequest job object");
cancelTask(QStringLiteral("Invalid EwsGetItemRequest job object"));
return;
}
Item::List items = req->property("items").value<Item::List>();
QHash<QString, Item> itemHash;
Q_FOREACH(const Item& item, items) {
itemHash.insert(item.remoteId(), item);
}
const EwsGetItemRequest::Response &resp = req->responses()[0];
if (!resp.isSuccess()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItems: Item fetch failed!");
cancelTask(QStringLiteral("Item fetch failed!"));
return;
}
if (items.size() != req->responses().size()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItems: incorrect number of responses!");
cancelTask(QStringLiteral("Item fetch failed - incorrect number of responses!"));
return;
}
Q_FOREACH(const EwsGetItemRequest::Response &resp, req->responses()) {
const EwsItem &ewsItem = resp.item();
EwsId id = ewsItem[EwsItemFieldItemId].value<EwsId>();
auto it = itemHash.find(id.id());
if (it == itemHash.end()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItems: Akonadi item not found for item %s!").arg(id.id());
cancelTask(QStringLiteral("Item fetch failed - Akonadi item not found for item %s!").arg(id.id()));
return;
}
EwsItemType type = ewsItem.internalType();
if (type == EwsItemTypeUnknown) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItems: Unknown item type for item %s!").arg(id.id());
cancelTask(QStringLiteral("Item fetch failed - Unknown item type for item %s!").arg(id.id()));
return;
}
if (!EwsItemHandler::itemHandler(type)->setItemPayload(*it, ewsItem)) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "retrieveItems: Failed to fetch item payload";
cancelTask(QStringLiteral("Failed to fetch item payload."));
return;
}
}
qCDebugNC(EWSRES_AGENTIF_LOG) << "retrieveItems: done";
itemsRetrieved(itemHash.values().toVector());
}
#else
bool EwsResource::retrieveItem(const Item &item, const QSet<QByteArray> &parts)
{
qCDebugNC(EWSRES_AGENTIF_LOG) << "retrieveItem: start " << item << parts;
EwsGetItemRequest *req = new EwsGetItemRequest(mEwsClient, this);
EwsId::List ids;
ids << EwsId(item.remoteId(), item.remoteRevision());
req->setItemIds(ids);
EwsItemShape shape(EwsShapeIdOnly);
shape << EwsPropertyField("item:MimeContent");
req->setItemShape(shape);
req->setProperty("item", QVariant::fromValue<Item>(item));
connect(req, &EwsGetItemRequest::result, this, &EwsResource::getItemRequestFinished);
req->start();
return true;
}
void EwsResource::getItemRequestFinished(KJob *job)
{
if (job->error()) {
qWarning() << "ERROR" << job->errorString();
cancelTask(job->errorString());
return;
}
EwsGetItemRequest *req = qobject_cast<EwsGetItemRequest*>(job);
if (!req) {
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid EwsGetItemRequest job object");
cancelTask(QStringLiteral("Invalid EwsGetItemRequest job object"));
return;
}
Item item = req->property("item").value<Item>();
const EwsGetItemRequest::Response &resp = req->responses()[0];
if (!resp.isSuccess()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItem: Item fetch failed!");
cancelTask(QStringLiteral("Item fetch failed!"));
return;
}
const EwsItem &ewsItem = resp.item();
EwsItemType type = ewsItem.internalType();
if (type == EwsItemTypeUnknown) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItem: Unknown item type!");
cancelTask(QStringLiteral("Item fetch failed - Unknown item type!"));
return;
}
if (!EwsItemHandler::itemHandler(type)->setItemPayload(item, ewsItem)) {
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("retrieveItem: Failed to fetch item payload.");
cancelTask(QStringLiteral("Failed to fetch item payload."));
return;
}
qCDebugNC(EWSRES_AGENTIF_LOG) << "retrieveItem: done";
itemRetrieved(item);
}
#endif
void EwsResource::reloadConfig()
{
mSubManager.reset(Q_NULLPTR);
qDebug() << QUrl(mSettings->baseUrl());
mEwsClient.setUrl(mSettings->baseUrl());
mSettings->requestPassword(mPassword, false);
if (mSettings->domain().isEmpty()) {
mEwsClient.setCredentials(mSettings->username(), mPassword);
} else {
mEwsClient.setCredentials(mSettings->domain() + '\\' + mSettings->username(), mPassword);
}
mSettings->save();
resetUrl();
}
void EwsResource::configure(WId windowId)
{
QPointer<ConfigDialog> dlg = new ConfigDialog(this, mEwsClient, windowId);
if (dlg->exec()) {
reloadConfig();
}
delete dlg;
}
void EwsResource::fetchFoldersJobFinished(KJob *job)
{
Q_EMIT status(Idle, i18nc("@info:status The resource is ready", "Ready"));
EwsFetchFoldersJob *req = qobject_cast<EwsFetchFoldersJob*>(job);
if (!req) {
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid EwsFetchFoldersJob job object");
cancelTask(QStringLiteral("Invalid EwsFetchFoldersJob job object"));
return;
}
if (req->error()) {
qWarning() << "ERROR" << req->errorString();
cancelTask(req->errorString());
return;
}
mFolderSyncState = req->syncState();
saveState();
collectionsRetrieved(req->folders());
fetchSpecialFolders();
}
void EwsResource::fetchFoldersIncrJobFinished(KJob *job)
{
Q_EMIT status(Idle, i18nc("@info:status The resource is ready", "Ready"));
EwsFetchFoldersIncrJob *req = qobject_cast<EwsFetchFoldersIncrJob*>(job);
if (!req) {
qCWarning(EWSRES_LOG) << QStringLiteral("Invalid EwsFetchFoldersIncrJob job object");
cancelTask(QStringLiteral("Invalid EwsFetchFoldersIncrJob job object"));
return;
}
if (req->error()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("ERROR") << req->errorString();
/* Retry with a full sync. */
qCWarningNC(EWSRES_LOG) << QStringLiteral("Retrying with a full sync.");
mFolderSyncState.clear();
doRetrieveCollections();
return;
}
mFolderSyncState = req->syncState();
saveState();
collectionsRetrievedIncremental(req->changedFolders(), req->deletedFolders());
fetchSpecialFolders();
}
void EwsResource::itemFetchJobFinished(KJob *job)
{
EwsFetchItemsJob *fetchJob = qobject_cast<EwsFetchItemsJob*>(job);
if (!fetchJob) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Invalid EwsFetchItemsJobjob object");
cancelTask(QStringLiteral("Invalid EwsFetchItemsJob job object"));
return;
}
if (job->error()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Item fetch error:") << job->errorString();
if (mSyncState.contains(fetchJob->collection().remoteId())) {
qCDebugNC(EWSRES_LOG) << QStringLiteral("Retrying with empty state.");
// Retry with a clear sync state.
mSyncState.remove(fetchJob->collection().remoteId());
retrieveItems(fetchJob->collection());
}
else {
qCDebugNC(EWSRES_LOG) << QStringLiteral("Clean sync failed.");
// No more hope
cancelTask(job->errorString());
return;
}
}
else {
mSyncState[fetchJob->collection().remoteId()] = fetchJob->syncState();
itemsRetrievedIncremental(fetchJob->changedItems(), fetchJob->deletedItems());
}
saveState();
mItemsToCheck.remove(fetchJob->collection().remoteId());
Q_EMIT status(Idle, i18nc("@info:status The resource is ready", "Ready"));
}
void EwsResource::itemChanged(const Akonadi::Item &item, const QSet<QByteArray> &partIdentifiers)
{
qCDebugNC(EWSRES_AGENTIF_LOG) << "itemChanged: start " << item << partIdentifiers;
EwsItemType type = EwsItemHandler::mimeToItemType(item.mimeType());
if (isEwsMessageItemType(type)) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemChanged: Item type not supported for changing";
cancelTask("Item type not supported for changing");
}
else {
EwsModifyItemJob *job = EwsItemHandler::itemHandler(type)->modifyItemJob(mEwsClient,
Item::List() << item, partIdentifiers, this);
connect(job, SIGNAL(result(KJob*)), SLOT(itemChangeRequestFinished(KJob*)));
job->start();
}
}
void EwsResource::itemsFlagsChanged(const Akonadi::Item::List &items, const QSet<QByteArray> &addedFlags,
const QSet<QByteArray> &removedFlags)
{
qCDebug(EWSRES_AGENTIF_LOG) << "itemsFlagsChanged: start" << items << addedFlags << removedFlags;
EwsModifyItemFlagsJob *job = new EwsModifyItemFlagsJob(mEwsClient, this, items, addedFlags, removedFlags);
connect(job, &EwsModifyItemFlagsJob::result, this, &EwsResource::itemModifyFlagsRequestFinished);
job->start();
}
void EwsResource::itemModifyFlagsRequestFinished(KJob *job)
{
if (job->error()) {
qCWarning(EWSRES_AGENTIF_LOG) << "itemsFlagsChanged:" << job->errorString();
cancelTask(job->errorString());
return;
}
EwsModifyItemFlagsJob *req = qobject_cast<EwsModifyItemFlagsJob*>(job);
if (!req) {
qCWarning(EWSRES_AGENTIF_LOG) << "itemsFlagsChanged: Invalid EwsModifyItemFlagsJob job object";
cancelTask(QStringLiteral("Invalid EwsModifyItemFlagsJob job object"));
return;
}
qCDebug(EWSRES_AGENTIF_LOG) << "itemsFlagsChanged: done";
changesCommitted(req->items());
}
void EwsResource::itemChangeRequestFinished(KJob *job)
{
if (job->error()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemChanged: " << job->errorString();
cancelTask(job->errorString());
return;
}
EwsModifyItemJob *req = qobject_cast<EwsModifyItemJob*>(job);
if (!req) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemChanged: Invalid EwsModifyItemJob job object";
cancelTask(QStringLiteral("Invalid EwsModifyItemJob job object"));
return;
}
qCDebugNC(EWSRES_AGENTIF_LOG) << "itemChanged: done";
changesCommitted(req->items());
}
void EwsResource::itemsMoved(const Item::List &items, const Collection &sourceCollection,
const Collection &destinationCollection)
{
qCDebug(EWSRES_AGENTIF_LOG) << "itemsMoved: start" << items << sourceCollection << destinationCollection;
EwsId::List ids;
Q_FOREACH(const Item &item, items) {
EwsId id(item.remoteId(), item.remoteRevision());
ids.append(id);
}
EwsMoveItemRequest *req = new EwsMoveItemRequest(mEwsClient, this);
req->setItemIds(ids);
EwsId destId(destinationCollection.remoteId(), QString());
req->setDestinationFolderId(destId);
req->setProperty("items", QVariant::fromValue<Item::List>(items));
req->setProperty("sourceCollection", QVariant::fromValue<Collection>(sourceCollection));
req->setProperty("destinationCollection", QVariant::fromValue<Collection>(destinationCollection));
connect(req, SIGNAL(result(KJob*)), SLOT(itemMoveRequestFinished(KJob*)));
req->start();
}
void EwsResource::itemMoveRequestFinished(KJob *job)
{
if (job->error()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsMoved: " << job->errorString();
cancelTask(job->errorString());
return;
}
EwsMoveItemRequest *req = qobject_cast<EwsMoveItemRequest*>(job);
if (!req) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsMoved: Invalid EwsMoveItemRequest job object";
cancelTask(QStringLiteral("Invalid EwsMoveItemRequest job object"));
return;
}
Item::List items = job->property("items").value<Item::List>();
if (items.count() != req->responses().count()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsMoved: Invalid number of responses received from server";
cancelTask(QStringLiteral("Invalid number of responses received from server."));
return;
}
/* When moving a batch of items it is possible that the operation will fail for some of them.
* Unfortunately Akonadi doesn't provide a way to report such partial success/failure. In order
* to work around this in case of partial failure the source and destination folders will be
* resynchronised. In order to avoid doing a full sync a hint will be provided in order to
* indicate the item(s) to check.
*/
Item::List movedItems;
EwsId::List failedIds;
Collection srcCol = req->property("sourceCollection").value<Collection>();
Collection dstCol = req->property("destinationCollection").value<Collection>();
Item::List::iterator it = items.begin();
Q_FOREACH(const EwsMoveItemRequest::Response &resp, req->responses()) {
Item &item = *it;
if (resp.isSuccess()) {
qCDebugNC(EWSRES_AGENTIF_LOG) << QStringLiteral("itemsMoved: succeeded for item %1 (new id: %2)")
.arg(ewsHash(item.remoteId())).arg(ewsHash(resp.itemId().id()));
if (item.isValid()) {
/* Log item deletion in the source folder so that the next sync doesn't trip over
* non-existent items. Use old remote ids for that. */
if (mSubManager) {
mSubManager->queueUpdate(EwsDeletedEvent, item.remoteId(), QString());
}
mQueuedUpdates[srcCol.remoteId()].append({item.remoteId(), QString(), EwsDeletedEvent});
item.setRemoteId(resp.itemId().id());
item.setRemoteRevision(resp.itemId().changeKey());
movedItems.append(item);
}
}
else {
warning(QStringLiteral("Move failed for item %1").arg(item.remoteId()));
qCDebugNC(EWSRES_AGENTIF_LOG) << QStringLiteral("itemsMoved: failed for item %1").arg(ewsHash(item.remoteId()));
failedIds.append(EwsId(item.remoteId(), QString()));
}
it++;
}
if (!failedIds.isEmpty()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Failed to move %1 items. Forcing src & dst folder sync.")
.arg(failedIds.size());
mItemsToCheck[srcCol.remoteId()] += failedIds;
foldersModifiedEvent(EwsId::List({EwsId(srcCol.remoteId(), QString())}));
mItemsToCheck[dstCol.remoteId()] += failedIds;
foldersModifiedEvent(EwsId::List({EwsId(dstCol.remoteId(), QString())}));
}
qCDebugNC(EWSRES_AGENTIF_LOG) << "itemsMoved: done";
changesCommitted(movedItems);
}
void EwsResource::itemsRemoved(const Item::List &items)
{
qCDebugNC(EWSRES_AGENTIF_LOG) << "itemsRemoved: start" << items;
EwsId::List ids;
Q_FOREACH(const Item &item, items) {
EwsId id(item.remoteId(), item.remoteRevision());
ids.append(id);
}
EwsDeleteItemRequest *req = new EwsDeleteItemRequest(mEwsClient, this);
req->setItemIds(ids);
req->setProperty("items", QVariant::fromValue<Item::List>(items));
connect(req, &EwsDeleteItemRequest::result, this, &EwsResource::itemDeleteRequestFinished);
req->start();
}
void EwsResource::itemDeleteRequestFinished(KJob *job)
{
if (job->error()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsRemoved: " << job->errorString();
cancelTask(job->errorString());
return;
}
EwsDeleteItemRequest *req = qobject_cast<EwsDeleteItemRequest*>(job);
if (!req) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsRemoved: Invalid EwsDeleteItemRequest job object";
cancelTask(QStringLiteral("Invalid EwsDeleteItemRequest job object"));
return;
}
Item::List items = job->property("items").value<Item::List>();
if (items.count() != req->responses().count()) {
qCWarningNC(EWSRES_AGENTIF_LOG) << "itemsRemoved: Invalid number of responses received from server";
cancelTask(QStringLiteral("Invalid number of responses received from server."));
return;
}
/* When removing a batch of items it is possible that the operation will fail for some of them.
* Unfortunately Akonadi doesn't provide a way to report such partial success/failure. In order
* to work around this in case of partial failure the original folder(s) will be resynchronised.
* In order to avoid doing a full sync a hint will be provided in order to indicate the item(s)
* to check.
*/
EwsId::List foldersToSync;
Item::List::iterator it = items.begin();
Q_FOREACH(const EwsDeleteItemRequest::Response &resp, req->responses()) {
Item &item = *it;
if (resp.isSuccess()) {
qCDebugNC(EWSRES_AGENTIF_LOG) << QStringLiteral("itemsRemoved: succeeded for item %1").arg(ewsHash(item.remoteId()));
if (mSubManager) {
mSubManager->queueUpdate(EwsDeletedEvent, item.remoteId(), QString());
}
mQueuedUpdates[item.parentCollection().remoteId()].append({item.remoteId(), QString(), EwsDeletedEvent});
}
else {
warning(QStringLiteral("Delete failed for item %1").arg(item.remoteId()));
qCWarningNC(EWSRES_AGENTIF_LOG) << QStringLiteral("itemsRemoved: failed for item %1").arg(ewsHash(item.remoteId()));
EwsId colId = EwsId(item.parentCollection().remoteId(), QString());
mItemsToCheck[colId.id()].append(EwsId(item.remoteId(), QString()));
if (!foldersToSync.contains(colId)) {
foldersToSync.append(colId);
}
}
it++;
}
if (!foldersToSync.isEmpty()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Need to force sync for %1 folders.")
.arg(foldersToSync.size());
foldersModifiedEvent(foldersToSync);
}
qCDebug(EWSRES_AGENTIF_LOG) << "itemsRemoved: done";
changeProcessed();
}
void EwsResource::itemAdded(const Item &item, const Collection &collection)
{
EwsItemType type = EwsItemHandler::mimeToItemType(item.mimeType());
if (isEwsMessageItemType(type)) {
cancelTask("Item type not supported for creation");
}
else {
EwsCreateItemJob *job = EwsItemHandler::itemHandler(type)->createItemJob(mEwsClient, item,
collection, mTagStore, this);
connect(job, &EwsCreateItemJob::result, this, &EwsResource::itemCreateRequestFinished);
job->start();
}
}
void EwsResource::itemCreateRequestFinished(KJob *job)
{
if (job->error()) {
cancelTask(job->errorString());
return;
}
EwsCreateItemJob *req = qobject_cast<EwsCreateItemJob*>(job);
if (!req) {
cancelTask(QStringLiteral("Invalid EwsCreateItemJob job object"));
return;
}
changeCommitted(req->item());
}
void EwsResource::collectionAdded(const Collection &collection, const Collection &parent)
{
EwsFolderType type;
QStringList mimeTypes = collection.contentMimeTypes();
if (mimeTypes.contains(EwsItemHandler::itemHandler(EwsItemTypeCalendarItem)->mimeType())) {
type = EwsFolderTypeCalendar;
}
else if (mimeTypes.contains(EwsItemHandler::itemHandler(EwsItemTypeContact)->mimeType())) {
type = EwsFolderTypeContacts;
}
else if (mimeTypes.contains(EwsItemHandler::itemHandler(EwsItemTypeTask)->mimeType())) {
type = EwsFolderTypeTasks;
}
else if (mimeTypes.contains(EwsItemHandler::itemHandler(EwsItemTypeMessage)->mimeType())) {
type = EwsFolderTypeMail;
}
else {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Cannot determine EWS folder type.");
cancelTask(QStringLiteral("Cannot determine EWS folder type."));
return;
}
EwsFolder folder;
folder.setType(type);
folder.setField(EwsFolderFieldDisplayName, collection.name());
EwsCreateFolderRequest *req = new EwsCreateFolderRequest(mEwsClient, this);
req->setParentFolderId(EwsId(parent.remoteId()));
req->setFolders(EwsFolder::List() << folder);
req->setProperty("collection", QVariant::fromValue<Collection>(collection));
connect(req, &EwsCreateFolderRequest::result, this, &EwsResource::folderCreateRequestFinished);
req->start();
}
void EwsResource::folderCreateRequestFinished(KJob *job)
{
if (job->error()) {
cancelTask(job->errorString());
return;
}
EwsCreateFolderRequest *req = qobject_cast<EwsCreateFolderRequest*>(job);
if (!req) {
cancelTask(QStringLiteral("Invalid EwsCreateFolderRequest job object"));
return;
}
Collection col = job->property("collection").value<Collection>();
EwsCreateFolderRequest::Response resp = req->responses().first();
if (resp.isSuccess()) {
const EwsId &id = resp.folderId();
col.setRemoteId(id.id());
col.setRemoteRevision(id.changeKey());
changeCommitted(col);
}
else {
cancelTask(i18nc("@info:status", "Failed to create folder"));
}
}
void EwsResource::collectionMoved(const Collection &collection, const Collection &collectionSource,
const Collection &collectionDestination)
{
Q_UNUSED(collectionSource)
EwsId::List ids;
ids.append(EwsId(collection.remoteId(), collection.remoteRevision()));
EwsMoveFolderRequest *req = new EwsMoveFolderRequest(mEwsClient, this);
req->setFolderIds(ids);
EwsId destId(collectionDestination.remoteId());
req->setDestinationFolderId(destId);
req->setProperty("collection", QVariant::fromValue<Collection>(collection));
connect(req, &EwsMoveFolderRequest::result, this, &EwsResource::folderMoveRequestFinished);
req->start();
}
void EwsResource::folderMoveRequestFinished(KJob *job)
{
if (job->error()) {
cancelTask(job->errorString());
return;
}
EwsMoveFolderRequest *req = qobject_cast<EwsMoveFolderRequest*>(job);
if (!req) {
cancelTask(QStringLiteral("Invalid EwsMoveFolderRequest job object"));
return;
}
Collection col = job->property("collection").value<Collection>();
if (req->responses().count() != 1) {
cancelTask(QStringLiteral("Invalid number of responses received from server."));
return;
}
EwsMoveFolderRequest::Response resp = req->responses().first();
if (resp.isSuccess()) {
const EwsId &id = resp.folderId();
col.setRemoteId(id.id());