-
Notifications
You must be signed in to change notification settings - Fork 2
/
SyncManager.m
1779 lines (1618 loc) · 57.8 KB
/
SyncManager.m
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
//
// SyncManager.m
// Less2Do
//
// Created by Gerhard Schraml on 04.01.10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "SyncManager.h"
#import "Setting.h"
#import "SFHFKeychainUtils.h"
@implementation SyncManager
@synthesize tdApi;
@synthesize isConnected;
@synthesize syncError;
@synthesize currentDate;
/*
Führt eine Synchronisation mit automatischer Wahl des aktuelleren Datensatzes durch.
Die automatische Wahl funktioniert jedoch nur für Tasks, nicht für Folder und Contexts,
weil bei letzteren auf Seiten von Toodledo keine Modified-Dates gespeichert werden.
Die Preference (SyncPreferLocal/SyncPreferRemote) bezieht sich also nur auf Folder und Contexts.
*/
-(BOOL)syncWithPreference:(SyncPreference)preference error:(NSError**)error
{
// 1. init members
BOOL wasSuccessful = YES;
isConnected = NO;
currentDate = [NSDate date];
syncError = nil;
*error = nil;
Setting *settings = (Setting *)[Setting getSettings:&syncError];
if(settings == nil)
{
*error = syncError;
return NO;
}
ALog(@"settings: %@", settings);
NSString *tdPassword = [SFHFKeychainUtils getPasswordForUsername:settings.tdEmail error:&syncError];
if(syncError != nil)
{
*error = syncError;
return NO;
}
tdApi = [[TDApi alloc] initWithUsername:settings.tdEmail password:tdPassword error:&syncError];
if(syncError != nil) // error establishing connection
{
*error = syncError;
wasSuccessful = NO;
}
else // successfully connected
{
[BaseManagedObject commit];
[self stopAutocommit];
if(preference == SyncPreferLocal)
{
// 1. Folders
wasSuccessful = [self syncFoldersPreferLocal];
if(!wasSuccessful)
return [self exitFailure:error];
// 2. Contexts
wasSuccessful = [self syncContextsPreferLocal];
if(!wasSuccessful)
return [self exitFailure:error];
// 3. Tasks
wasSuccessful = [self syncTasksMatchDates];
if(!wasSuccessful)
return [self exitFailure:error];
}
else
{
// 1. Folders
wasSuccessful = [self syncFoldersPreferRemote];
if(!wasSuccessful)
return [self exitFailure:error];
// 2. Contexts
wasSuccessful = [self syncContextsPreferRemote];
if(!wasSuccessful)
return [self exitFailure:error];
// 3. Tasks
wasSuccessful = [self syncTasksMatchDates];
if(!wasSuccessful)
return [self exitFailure:error];
}
[BaseManagedObject commitWithoutLocalModification];
[self startAutocommit];
[tdApi release];
return YES;
}
return wasSuccessful;
}
/*
Der komplette lokale Stand wird gelöscht und mit dem aktuellen Remote-Stand überschrieben.
*/
-(BOOL)overwriteLocal:(NSError**)error
{
// 1. init members
BOOL wasSuccessful = YES;
isConnected = NO;
currentDate = [NSDate date];
syncError = nil;
*error = nil;
Setting *settings = [Setting getSettings:&syncError];
if(settings == nil)
{
*error = syncError;
return NO;
}
NSString *tdPassword = [SFHFKeychainUtils getPasswordForUsername:settings.tdEmail error:&syncError];
if(syncError != nil)
{
*error = syncError;
return NO;
}
tdApi = [[TDApi alloc] initWithUsername:settings.tdEmail password:tdPassword error:&syncError];
if(syncError != nil) // error establishing connection
{
*error = syncError;
wasSuccessful = NO;
}
else // successfully connected
{
[self stopAutocommit];
// ------ FIRST: DELETE ALL LOCAL DATA ------
// delete Folders
wasSuccessful = [self deleteAllLocalFolders];
if(!wasSuccessful)
return [self exitFailure:error];
// delete Contexts
wasSuccessful = [self deleteAllLocalContexts];
if(!wasSuccessful)
return [self exitFailure:error];
// delete Tags
wasSuccessful = [self deleteAllLocalTags];
if(!wasSuccessful)
return [self exitFailure:error];
// delete Tasks
wasSuccessful = [self deleteAllLocalTasks];
if(!wasSuccessful)
return [self exitFailure:error];
// später: deleteAllExtendedInfos
// ------ SECOND: GET DATA FROM REMOTE STORE
// 1. get Folders
wasSuccessful = [self syncFoldersPreferRemote];
if(!wasSuccessful)
return [self exitFailure:error];
// 2. get Contexts
wasSuccessful = [self syncContextsPreferRemote];
if(!wasSuccessful)
return [self exitFailure:error];
// 3. write Tasks
wasSuccessful = [self syncTasksPreferRemote];
if(!wasSuccessful)
return [self exitFailure:error];
[BaseManagedObject commitWithoutLocalModification];
[self startAutocommit];
[tdApi release];
return YES;
}
return wasSuccessful;
}
/*
Der komplette Remote-Stand wird gelöscht und mit dem aktuellen lokalen Stand überschrieben.
*/
-(BOOL)overwriteRemote:(NSError**)error
{
// 1. init members
BOOL wasSuccessful = YES;
isConnected = NO;
currentDate = [NSDate date];
syncError = nil;
*error = nil;
Setting *settings = [Setting getSettings:&syncError];
if(settings == nil)
{
*error = syncError;
return NO;
}
NSString *tdPassword = [SFHFKeychainUtils getPasswordForUsername:settings.tdEmail error:&syncError];
if(syncError != nil)
{
*error = syncError;
return NO;
}
tdApi = [[TDApi alloc] initWithUsername:settings.tdEmail password:tdPassword error:&syncError];
if(syncError != nil) // error establishing connection
{
*error = syncError;
wasSuccessful = NO;
}
else // successfully connected
{
[self stopAutocommit];
// ------ FIRST: DELETE ALL REMOTE DATA ------
// delete Folders
wasSuccessful = [self deleteAllRemoteFolders];
if(!wasSuccessful)
return [self exitFailure:error];
// delete Contexts
wasSuccessful = [self deleteAllRemoteContexts];
if(!wasSuccessful)
return [self exitFailure:error];
// delete Tasks
wasSuccessful = [self deleteAllRemoteTasks];
if(!wasSuccessful)
return [self exitFailure:error];
// ------ SECOND: WRITE LOCAL DATA TO REMOTE STORE
// 1. write Folders
wasSuccessful = [self syncFoldersPreferLocal];
if(!wasSuccessful)
return [self exitFailure:error];
// 2. write Contexts
wasSuccessful = [self syncContextsPreferLocal];
if(!wasSuccessful)
return [self exitFailure:error];
// 3. write Tasks
wasSuccessful = [self syncTasksPreferLocal];
if(!wasSuccessful)
return [self exitFailure:error];
[BaseManagedObject commitWithoutLocalModification];
[self startAutocommit];
[tdApi release];
return YES;
}
return wasSuccessful;
}
+(NSString *)gtdErrorMessage:(NSInteger)errorCode
{
/*GtdApiNoConnectionError = 10,
GtdApiNotReachableError = 20,
GtdApiDataError = 30,
GtdApiMissingParameters = 40,
GtdApiMissingCredentialsError = 110,
GtdApiWrongCredentialsError = 120,
GtdApiFolderNotAddedError = 210,
GtdApiFolderNotDeletedError = 310,
GtdApiFolderNotEditedError = 410,
GtdApiContextNotAddedError = 510,
GtdApiContextNotDeletedError = 520,
GtdApiContextNotEditedError = 530*/
switch (errorCode) {
case GtdApiNoConnectionError:
return @"Toodledo API no connection";
case GtdApiNotReachableError:
return @"Toodledo API not reachable";
case GtdApiDataError:
return @"Toodledo API data error";
case GtdApiMissingParameters:
return @"Toodledo API missing parameters";
case GtdApiMissingCredentialsError:
return @"Toodledo API missing credentials";
case GtdApiWrongCredentialsError:
return @"Toodledo API wrong credentials";
case GtdApiFolderNotAddedError:
return @"Toodledo API Folder not added";
case GtdApiFolderNotDeletedError:
return @"Toodledo API Folder not deleted";
case GtdApiFolderNotEditedError:
return @"Toodledo API Folder not edited";
case GtdApiContextNotAddedError:
return @"Toodledo API Context not added";
case GtdApiContextNotDeletedError:
return @"Toodledo API Context not deleted";
case GtdApiContextNotEditedError:
return @"Toodledo API Context not edited";
default:
return @"Toodledo API unknown error";
}
}
-(BOOL)syncFoldersPreferLocal
{
NSArray *remoteFolders = [tdApi getFolders:&syncError];
if(syncError != nil)
return NO;
NSArray *localFoldersWithRemoteIdArray = [Folder getRemoteStoredFolders:&syncError];
if(syncError != nil)
return NO;
// initialisiere zunächst mit allen bereits gesyncten Foldern
// sobald ein remote-pendant gefunden wurde, entferne folder aus dieser collection
// die übrig gebliebenen wurden remote entfernt, müssen aber aufgrund der
// höheren priorität der lokalen version remote wieder geadded werden
NSMutableArray *localFoldersWithRemoteId = [NSMutableArray array];
[localFoldersWithRemoteId addObjectsFromArray:localFoldersWithRemoteIdArray];
NSMutableArray *usedLocalEntityVersion = [[[NSMutableArray alloc] init] autorelease];
for(GtdFolder *remoteFolder in remoteFolders)
{
BOOL foundLocalEntity = NO;
// durchsuche lokale Folder, ob gleiche id existiert
for(int i=0; i<[localFoldersWithRemoteId count]; i++)
{
Folder *localFolder = [localFoldersWithRemoteId objectAtIndex:i];
if([localFolder.remoteId integerValue] == remoteFolder.uid)
{
foundLocalEntity = YES;
[usedLocalEntityVersion addObject:localFolder];
[localFoldersWithRemoteId removeObject:localFolder];
break;
}
}
if(!foundLocalEntity)
{
// add local
Folder *newFolder = (Folder*)[Folder objectOfType:@"Folder"];
newFolder.name = remoteFolder.title;
newFolder.order = [NSNumber numberWithInteger:remoteFolder.order];
newFolder.remoteId = [NSNumber numberWithInteger:remoteFolder.uid];
newFolder.lastSyncDate = currentDate;
}
}
// füge nun remote gelöschte folder wieder hinzu, aber nur wenn sie nicht
// auch zufällig lokal als gekennzeichnet wurden
for(int i=0;i<[localFoldersWithRemoteId count];i++)
{
GtdFolder *remoteFolder = [[GtdFolder alloc] init];
Folder *localFolder = [localFoldersWithRemoteId objectAtIndex:i];
remoteFolder.title = localFolder.name;
remoteFolder.order = [localFolder.order integerValue];
if([localFolder.deleted intValue] == 0)
{
localFolder.lastSyncDate = currentDate;
localFolder.remoteId = [NSNumber numberWithInteger:[tdApi addFolder:remoteFolder error:&syncError]];
}
[remoteFolder release];
if(syncError != nil)
return NO;
}
// update die toodledo folder, bei allen foldern, die schon mal gesynct wurden
for(Folder *localFolder in usedLocalEntityVersion)
{
// update toodledo
GtdFolder *newFolder = [[GtdFolder alloc] init];
newFolder.title = localFolder.name;
newFolder.order = [localFolder.order integerValue];
newFolder.uid = [localFolder.remoteId integerValue];
// sende update request nur, wenn der folder nicht sowieso gelöscht wird
BOOL requestSuccessful = YES;
if([localFolder.deleted intValue] == 0)
{
localFolder.lastSyncDate = currentDate;
requestSuccessful = [tdApi editFolder:newFolder error:&syncError];
}
[newFolder release];
if(!requestSuccessful)
return NO;
}
// jetzt fehlen nur noch die noch nie gesyncten lokalen Folder
// --> toodledo-add
NSArray *unsyncedFolders = [Folder getUnsyncedFolders:&syncError];
if(syncError != nil)
return NO;
for(Folder *localFolder in unsyncedFolders)
{
GtdFolder *newFolder = [[GtdFolder alloc] init];
newFolder.title = localFolder.name;
newFolder.order = [localFolder.order integerValue];
newFolder.private = NO;
newFolder.uid = -1;
localFolder.remoteId = [NSNumber numberWithInteger:[tdApi addFolder:newFolder error:&syncError]];
localFolder.lastSyncDate = currentDate;
[newFolder release];
if(syncError != nil)
return NO;
}
// alle folder mit remoteId != nil && deleted == true ==> delete toodledo
NSArray *foldersToDeleteRemote = [Folder getRemoteStoredFoldersLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[foldersToDeleteRemote count]; i++)
{
Folder * folderToDeleteRemote = [foldersToDeleteRemote objectAtIndex:i];
GtdFolder *newFolder = [[GtdFolder alloc] init];
newFolder.uid = [folderToDeleteRemote.remoteId integerValue];
BOOL requestSuccessful = YES;
requestSuccessful = [tdApi deleteFolder:newFolder error:&syncError];
[newFolder release];
if(!requestSuccessful)
{
// ignoriere Fehler, dann wurde der Folder eben schon von einem
// anderen in der Zwischenzeit gelöscht
if(![syncError code] == GtdApiFolderNotDeletedError)
return NO;
syncError = nil;
}
}
// alle folder mit deleted == true lokal löschen
NSArray *foldersToDeleteLocally = [Folder getAllFoldersLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[foldersToDeleteLocally count]; i++)
{
Folder *folderToDeleteLocally = [foldersToDeleteLocally objectAtIndex:i];
[Folder deleteObjectFromPersistentStore:folderToDeleteLocally error:&syncError];
if(syncError != nil)
return NO;
}
return YES;
}
-(BOOL)syncFoldersPreferRemote
{
NSArray *remoteFolders = [tdApi getFolders:&syncError];
if(syncError != nil)
return NO;
NSArray *localFoldersWithRemoteIdArray = [Folder getRemoteStoredFolders:&syncError];
if(syncError != nil)
return NO;
// initialisiere zunächst mit allen bereits gesyncten Foldern
// sobald ein remote-pendant gefunden wurde, entferne folder aus dieser collection
// die übrig gebliebenen wurden remote entfernt, müssen daher aufgrund
// der höheren Priorität der remote Version lokal gelöscht werden
NSMutableArray *localFoldersWithRemoteId = [NSMutableArray array];
[localFoldersWithRemoteId addObjectsFromArray:localFoldersWithRemoteIdArray];
for(GtdFolder *remoteFolder in remoteFolders)
{
BOOL foundLocalEntity = NO;
// durchsuche lokale Folder, ob gleiche id existiert
for(int i=0; i<[localFoldersWithRemoteId count]; i++)
{
Folder *localFolder = [localFoldersWithRemoteId objectAtIndex:i];
if([localFolder.remoteId integerValue] == remoteFolder.uid)
{
foundLocalEntity = YES;
localFolder.deleted = [NSNumber numberWithInteger:0]; // verhindere möglichen Löschvorgang
// überschreibe lokale Felder
localFolder.name = remoteFolder.title;
localFolder.order = [NSNumber numberWithInteger:remoteFolder.order];
// weiter unten: nsset tasks
localFolder.lastSyncDate = currentDate;
[localFoldersWithRemoteId removeObject:localFolder];
break;
}
}
if(!foundLocalEntity)
{
// add local
Folder *newFolder = (Folder*)[Folder objectOfType:@"Folder"];
newFolder.name = remoteFolder.title;
newFolder.order = [NSNumber numberWithInteger:remoteFolder.order];
newFolder.remoteId = [NSNumber numberWithInteger:remoteFolder.uid];
newFolder.lastSyncDate = currentDate;
}
}
// merke alle lokalen Folder, zu denen kein remote-Pendant gefunden wurde
// zum löschen vor
for(int i=0;i<[localFoldersWithRemoteId count];i++)
{
Folder *localFolder = [localFoldersWithRemoteId objectAtIndex:i];
localFolder.deleted = [NSNumber numberWithInteger:1];
}
// alle folder mit remoteId == nil && deleted == false ==> add toodledo
NSArray *unsyncedFolders = [Folder getUnsyncedFolders:&syncError];
if(syncError != nil)
return NO;
for(Folder *localFolder in unsyncedFolders)
{
GtdFolder *newFolder = [[GtdFolder alloc] init];
newFolder.title = localFolder.name;
newFolder.order = [localFolder.order integerValue];
newFolder.private = NO;
newFolder.uid = -1;
localFolder.remoteId = [NSNumber numberWithInteger:[tdApi addFolder:newFolder error:&syncError]];
localFolder.lastSyncDate = currentDate;
[newFolder release];
if(syncError != nil)
return NO;
}
// alle folder mit deleted == true lokal löschen
NSArray *foldersToDeleteLocally = [Folder getAllFoldersLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[foldersToDeleteLocally count]; i++)
{
Folder *folderToDeleteLocally = [foldersToDeleteLocally objectAtIndex:i];
[Folder deleteObjectFromPersistentStore:folderToDeleteLocally error:&syncError];
if(syncError != nil)
return NO;
}
return YES;
}
-(BOOL)syncContextsPreferLocal
{
NSArray *remoteContexts = [tdApi getContexts:&syncError];
if(syncError != nil)
return NO;
NSArray *localContextsWithRemoteIdArray = [Context getRemoteStoredContexts:&syncError];
if(syncError != nil)
return NO;
// initialisiere zunächst mit allen bereits gesyncten Kontexten
// sobald ein remote-pendant gefunden wurde, entferne context aus dieser collection
// die übrig gebliebenen wurden remote entfernt, müssen aber aufgrund der
// höheren priorität der lokalen version remote wieder geadded werden
NSMutableArray *localContextsWithRemoteId = [NSMutableArray array];
[localContextsWithRemoteId addObjectsFromArray:localContextsWithRemoteIdArray];
NSMutableArray *usedLocalEntityVersion = [[[NSMutableArray alloc] init] autorelease];
for(GtdContext *remoteContext in remoteContexts)
{
BOOL foundLocalEntity = NO;
// durchsuche lokale Contexte, ob gleiche id existiert
for(int i=0; i<[localContextsWithRemoteId count]; i++)
{
Context *localContext = [localContextsWithRemoteId objectAtIndex:i];
if([localContext.remoteId integerValue] == remoteContext.uid)
{
foundLocalEntity = YES;
[usedLocalEntityVersion addObject:localContext];
[localContextsWithRemoteId removeObject:localContext];
break;
}
}
if(!foundLocalEntity)
{
// add local
Context *newContext = (Context*)[Context objectOfType:@"Context"];
newContext.name = remoteContext.title;
newContext.remoteId = [NSNumber numberWithInteger:remoteContext.uid];
newContext.lastSyncDate = currentDate;
}
}
// füge nun remote gelöschte contexts wieder hinzu, aber nur wenn sie nicht
// auch zufällig lokal als gekennzeichnet wurden
for(int i=0;i<[localContextsWithRemoteId count];i++)
{
GtdContext *remoteContext = [[GtdContext alloc] init];
Context *localContext = [localContextsWithRemoteId objectAtIndex:i];
remoteContext.title = localContext.name;
if([localContext.deleted intValue] == 0)
{
localContext.lastSyncDate = currentDate;
localContext.remoteId = [NSNumber numberWithInteger:[tdApi addContext:remoteContext error:&syncError]];
}
[remoteContext release];
if(syncError != nil)
return NO;
}
// update die toodledo context, bei allen contexten, die schon mal gesynct wurden
for(Context *localContext in usedLocalEntityVersion)
{
// update toodledo
GtdContext *newContext = [[GtdContext alloc] init];
newContext.title = localContext.name;
newContext.uid = [localContext.remoteId integerValue];
// sende update request nur, wenn der context nicht sowieso gelöscht wird
BOOL requestSuccessful = YES;
if([localContext.deleted intValue] == 0)
{
localContext.lastSyncDate = currentDate;
requestSuccessful = [tdApi editContext:newContext error:&syncError];
}
[newContext release];
if(!requestSuccessful)
return NO;
}
// jetzt fehlen nur noch die noch nie gesyncten lokalen Contexte
// --> toodledo-add
NSArray *unsyncedContexts = [Context getUnsyncedContexts:&syncError];
if(syncError != nil)
return NO;
for(Context *localContext in unsyncedContexts)
{
GtdContext *newContext = [[GtdContext alloc] init];
newContext.title = localContext.name;
newContext.uid = -1;
localContext.remoteId = [NSNumber numberWithInteger:[tdApi addContext:newContext error:&syncError]];
localContext.lastSyncDate = currentDate;
[newContext release];
if(syncError != nil)
return NO;
}
// alle contexte mit remoteId != nil && deleted == true ==> delete toodledo
NSArray *contextsToDeleteRemote = [Context getRemoteStoredContextsLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[contextsToDeleteRemote count]; i++)
{
Context * contextToDeleteRemote = [contextsToDeleteRemote objectAtIndex:i];
GtdContext *newContext = [[GtdContext alloc] init];
newContext.uid = [contextToDeleteRemote.remoteId integerValue];
BOOL requestSuccessful = YES;
requestSuccessful = [tdApi deleteContext:newContext error:&syncError];
[newContext release];
if(!requestSuccessful)
{
// ignoriere Fehler, dann wurde der Context eben schon von einem
// anderen in der Zwischenzeit gelöscht
if(![syncError code] == GtdApiContextNotDeletedError)
return NO;
syncError = nil;
}
}
// alle contexte mit deleted == true lokal löschen
NSArray *contextsToDeleteLocally = [Context getAllContextsLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[contextsToDeleteLocally count]; i++)
{
Context *contextToDeleteLocally = [contextsToDeleteLocally objectAtIndex:i];
[Context deleteObjectFromPersistentStore:contextToDeleteLocally error:&syncError];
if(syncError != nil)
return NO;
}
return YES;
}
-(BOOL)syncContextsPreferRemote
{
NSArray *remoteContexts = [tdApi getContexts:&syncError];
if(syncError != nil)
return NO;
NSArray *localContextsWithRemoteIdArray = [Context getRemoteStoredContexts:&syncError];
if(syncError != nil)
return NO;
// initialisiere zunächst mit allen bereits gesyncten Contextn
// sobald ein remote-pendant gefunden wurde, entferne context aus dieser collection
// die übrig gebliebenen wurden remote entfernt, müssen daher aufgrund
// der höheren Priorität der remote Version lokal gelöscht werden
NSMutableArray *localContextsWithRemoteId = [NSMutableArray array];
[localContextsWithRemoteId addObjectsFromArray:localContextsWithRemoteIdArray];
for(GtdContext *remoteContext in remoteContexts)
{
BOOL foundLocalEntity = NO;
// durchsuche lokale Context, ob gleiche id existiert
for(int i=0; i<[localContextsWithRemoteId count]; i++)
{
Context *localContext = [localContextsWithRemoteId objectAtIndex:i];
if([localContext.remoteId integerValue] == remoteContext.uid)
{
foundLocalEntity = YES;
localContext.deleted = [NSNumber numberWithInteger:0]; // verhindere möglichen Löschvorgang
// überschreibe lokale Felder
localContext.name = remoteContext.title;
// weiter unten: nsset tasks
localContext.lastSyncDate = currentDate;
[localContextsWithRemoteId removeObject:localContext];
break;
}
}
if(!foundLocalEntity)
{
// add local
Context *newContext = (Context*)[Context objectOfType:@"Context"];
newContext.name = remoteContext.title;
newContext.remoteId = [NSNumber numberWithInteger:remoteContext.uid];
newContext.lastSyncDate = currentDate;
}
}
// merke alle lokalen Context, zu denen kein remote-Pendant gefunden wurde
// zum löschen vor
for(int i=0;i<[localContextsWithRemoteId count];i++)
{
Context *localContext = [localContextsWithRemoteId objectAtIndex:i];
localContext.deleted = [NSNumber numberWithInteger:1];
}
// alle context mit remoteId == nil && deleted == false ==> add toodledo
NSArray *unsyncedContexts = [Context getUnsyncedContexts:&syncError];
if(syncError != nil)
return NO;
for(Context *localContext in unsyncedContexts)
{
GtdContext *newContext = [[GtdContext alloc] init];
newContext.title = localContext.name;
newContext.uid = -1;
localContext.remoteId = [NSNumber numberWithInteger:[tdApi addContext:newContext error:&syncError]];
localContext.lastSyncDate = currentDate;
[newContext release];
if(syncError != nil)
return NO;
}
// alle context mit deleted == true lokal löschen
NSArray *contextsToDeleteLocally = [Context getAllContextsLocallyDeleted:&syncError];
if(syncError != nil)
return NO;
for(int i=0; i<[contextsToDeleteLocally count]; i++)
{
Context *contextToDeleteLocally = [contextsToDeleteLocally objectAtIndex:i];
[Context deleteObjectFromPersistentStore:contextToDeleteLocally error:&syncError];
if(syncError != nil)
return NO;
}
return YES;
}
-(BOOL)syncTasksMatchDates
{
NSArray *remoteTasks = [tdApi getTasks:&syncError];
if(syncError != nil)
return NO;
NSArray *localTasksWithRemoteIdArray = [Task getRemoteStoredTasks:&syncError];
if(syncError != nil)
return NO;
// initialisiere zunächst mit allen bereits gesyncten Tasks
// sobald ein remote-pendant gefunden wurde, entferne task aus dieser collection
// die übrig gebliebenen wurden remote entfernt, müssen aber aufgrund der
// höheren priorität der lokalen version remote wieder geadded werden
NSMutableArray *localTasksWithRemoteId = [NSMutableArray array];
[localTasksWithRemoteId addObjectsFromArray:localTasksWithRemoteIdArray];
NSMutableArray *usedLocalEntityVersion = [[[NSMutableArray alloc] init] autorelease];
for(GtdTask *remoteTask in remoteTasks)
{
BOOL foundLocalEntity = NO;
// durchsuche lokale Task, ob gleiche id existiert
for(int i=0; i<[localTasksWithRemoteId count]; i++)
{
Task *localTask = [localTasksWithRemoteId objectAtIndex:i];
if([localTask.remoteId integerValue] == remoteTask.uid)
{
ALog(@"Das remoteDate: %@ das localDate: %@",remoteTask.date_modified,localTask.lastLocalModification);
if([remoteTask.date_modified compare:localTask.lastLocalModification] == NSOrderedDescending || localTask.lastLocalModification == nil) // Remote aktueller als Folder
{
localTask.deleted = [NSNumber numberWithInteger:0]; // verhindere möglichen Löschvorgang
// überschreibe lokale Felder
localTask.lastSyncDate = currentDate;
localTask.name = remoteTask.title;
localTask.creationDate = remoteTask.date_created;
//localTask.lastLocalModification = remoteTask.date_modified;
localTask.startDateAnnoy = remoteTask.date_start; // ???
if(remoteTask.hasDueDate)
localTask.dueDate = remoteTask.date_due;
else
localTask.dueDate = nil;
if(remoteTask.hasDueTime)
localTask.dueTime = remoteTask.date_due;
else
localTask.dueTime = nil;
NSMutableArray *tagsToRemove = [NSMutableArray array];
for(Tag *tag in localTask.tags)
{
[tagsToRemove addObject:tag];
}
for(Tag *tag in tagsToRemove)
{
[tag removeTasksObject:localTask];
}
[localTask removeTags:localTask.tags];
for(NSString *remoteTag in remoteTask.tags)
{
if(![remoteTag isEqualToString:@""])
{
Tag* tag = [Tag getTagWithName:remoteTag error:&syncError];
if(syncError != nil)
return NO;
if(tag == nil)
{
tag = (Tag*)[Tag objectOfType:@"Tag"];
tag.name = remoteTag;
}
if(![[tag tasks] containsObject:localTask])
[tag addTasksObject:localTask];
if(![[localTask tags] containsObject:tag])
[localTask addTagsObject:tag];
}
}
if(localTask.folder != nil)
{
[localTask.folder removeTasksObject:localTask];
localTask.folder = nil;
}
Folder *folder = [Folder getFolderWithRemoteId:[NSNumber numberWithInteger:remoteTask.folder] error:&syncError];
if(syncError != nil)
return NO;
if(folder != nil)
{
[folder addTasksObject:localTask];
[localTask setFolder:folder];
}
if(localTask.context != nil)
{
[localTask.context removeTasksObject:localTask];
localTask.context = nil;
}
Context *context = [Context getContextWithRemoteId:[NSNumber numberWithInteger:remoteTask.context] error:&syncError];
if(syncError != nil)
return NO;
if(context != nil)
{
[context addTasksObject:localTask];
[localTask setContext:context];
}
localTask.priority = [NSNumber numberWithInteger:remoteTask.priority];
localTask.isCompleted = (remoteTask.completed != nil ? [NSNumber numberWithInt:1] : [NSNumber numberWithInt:0]);
localTask.duration = [NSNumber numberWithInteger:remoteTask.length]; // number of minutes to complete???
localTask.note = remoteTask.note;
localTask.star = [NSNumber numberWithBool:remoteTask.star];
localTask.repeat = [NSNumber numberWithInteger:remoteTask.repeat];
//newTask.whatever = remoteTask.status; // wird bei uns nicht verwendet
localTask.reminder = [NSNumber numberWithInteger:remoteTask.reminder];
//newTask.parentId = remoteTask.parentId; // wird bei uns nicht verwendet
localTask.remoteId = [NSNumber numberWithInteger:remoteTask.uid];
localTask.lastSyncDate = currentDate;
}
else
{
[usedLocalEntityVersion addObject:localTask];
}
[localTasksWithRemoteId removeObject:localTask];
foundLocalEntity = YES;
break;
}
}
if(!foundLocalEntity)
{
// add local
Task *newTask = (Task*)[Task objectOfType:@"Task"];
newTask.name = remoteTask.title;
newTask.creationDate = remoteTask.date_created;
newTask.modificationDate = remoteTask.date_modified;
newTask.startDateAnnoy = remoteTask.date_start; // ???
if(remoteTask.hasDueDate)
newTask.dueDate = remoteTask.date_due;
else
newTask.dueDate = nil;
if(remoteTask.hasDueTime)
newTask.dueTime = remoteTask.date_due;
else
newTask.dueTime = nil;
for(NSString *remoteTag in remoteTask.tags)
{
if(![remoteTag isEqualToString:@""])
{
Tag* tag = [Tag getTagWithName:remoteTag error:&syncError];
if(syncError != nil)
return NO;
if(tag == nil)
{
tag = (Tag*)[Tag objectOfType:@"Tag"];
tag.name = remoteTag;
}
if(![[tag tasks] containsObject:newTask])
[tag addTasksObject:newTask];
if(![[newTask tags] containsObject:tag])
[newTask addTagsObject:tag];
}
}
Folder *folder = [Folder getFolderWithRemoteId:[NSNumber numberWithInteger:remoteTask.folder] error:&syncError];
if(syncError != nil)
return NO;
if(folder != nil)
{
[folder addTasksObject:newTask];
[newTask setFolder:folder];
}
Context *context = [Context getContextWithRemoteId:[NSNumber numberWithInteger:remoteTask.context] error:&syncError];
if(syncError != nil)
return NO;
if(context != nil)
{
[context addTasksObject:newTask];
[newTask setContext:context];
}
newTask.priority = [NSNumber numberWithInteger:remoteTask.priority];
newTask.isCompleted = (remoteTask.completed != nil ? [NSNumber numberWithInt:1] : [NSNumber numberWithInt:0]);
newTask.duration = [NSNumber numberWithInteger:remoteTask.length]; // number of minutes to complete???
newTask.note = remoteTask.note;
newTask.star = [NSNumber numberWithBool:remoteTask.star];
newTask.repeat = [NSNumber numberWithInteger:remoteTask.repeat];
//newTask.whatever = remoteTask.status; // wird bei uns nicht verwendet
newTask.reminder = [NSNumber numberWithInteger:remoteTask.reminder];
//newTask.parentId = remoteTask.parentId; // wird bei uns nicht verwendet
newTask.remoteId = [NSNumber numberWithInteger:remoteTask.uid];
newTask.lastSyncDate = currentDate;
}
}
// lösche alle remote gelöschten tasks, die nach der letzten lokalen änderung gelöscht wurden
NSArray *deletedTasks = [tdApi getDeleted:&syncError];
if(syncError != nil)
return NO;
for(GtdTask *deletedTask in deletedTasks)
{
for(int i=0;i<[localTasksWithRemoteId count];i++)
{
Task *localTask = [localTasksWithRemoteId objectAtIndex:i];
ALog(@"local task: %@ - date local %@ - date deleted %@", localTask, localTask.lastLocalModification, deletedTask.date_deleted);
if(deletedTask.uid == [localTask.remoteId integerValue] && ([deletedTask.date_deleted compare:localTask.lastLocalModification] == NSOrderedDescending || localTask.lastLocalModification == nil))
{
localTask.deleted = [NSNumber numberWithBool:YES];
[localTasksWithRemoteId removeObject:localTask];
}
}
}
// füge nun remote gelöschte task wieder hinzu, aber nur wenn sie nicht
// auch zufällig lokal als deleted gekennzeichnet wurden
for(int i=0;i<[localTasksWithRemoteId count];i++)
{
GtdTask *remoteTask = [[GtdTask alloc] init];
Task *localTask = [localTasksWithRemoteId objectAtIndex:i];
if([localTask.deleted intValue] == 0)
{
remoteTask.title = localTask.name;
remoteTask.date_created = localTask.creationDate;
remoteTask.date_modified = localTask.lastLocalModification;
remoteTask.date_start = localTask.startDateAnnoy;
remoteTask.date_due = localTask.dueDate;
if(localTask.dueTime == nil)
remoteTask.hasDueTime = NO;
else
remoteTask.hasDueTime = YES;
NSMutableArray *mutableTags = [NSMutableArray array];
for(Tag *tag in localTask.tags)
{
[mutableTags addObject:tag.name];
}
remoteTask.tags = [NSArray arrayWithArray:mutableTags];
remoteTask.folder = [localTask.folder.remoteId integerValue];
remoteTask.context = [localTask.context.remoteId integerValue];
remoteTask.priority = [localTask.priority integerValue];
remoteTask.completed = ([localTask.isCompleted boolValue] ? [NSDate dateWithTimeIntervalSince1970:0] : nil);