-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathOpenMetaBackup.m
2164 lines (1853 loc) · 73.9 KB
/
OpenMetaBackup.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
//
// OpenMetaBackup.m
// Fresh
//
// Created by Tom Andersen on 26/01/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#include <sys/xattr.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/unistd.h>
#import "OpenMeta.h"
#import "OpenMetaBackup.h"
NSString* OpenMetaBackupSingleFileDoneNote = @"OpenMetaBackupSingleFileDoneNote";
NSString* kBackupPath = @"~/Library/Application Support/OpenMeta/backups.noindex"; // i guess this should be some messy cocoa special folder lookup for application support
BOOL gDoOpenMetaBackups = YES; // mechanism for shutting down backups - place txt file at ~/Library/Application Support/OpenMeta/backups.noindex/No Backups Please.txt"
@interface OpenMetaBackup (Private)
+(NSString*)fsRefToPath:(FSRef*)inRef;
+(NSData*)aliasDataForFSRef:(FSRef*)inRef;
+(NSData*) aliasDataForPath:(NSString*)inPath;
+(NSString*) resolveAliasDataToPathFileIDFirst:(NSData*)inData osErr:(OSErr*)outErr;
+(NSString*) backupPathForMonthsBeforeNow:(int)inMonthsBeforeNow;
+(NSString*) backupPathForItem:(NSString*)inPath;
+(void)restoreMetadataSearchForFile:(NSString*)inPath withDelay:(NSTimeInterval)inDelay;
+(NSString*)hashString:(NSString*)inString;
+(NSThread*)backupThread;
+(void)enqueueBackupItem:(NSString*)inPath;
+(NSString*)truncatedPathComponent:(NSString*)aPathComponent;
+(void)backupMetadataNow:(NSString*)inPath;
+(int)restoreMetadataDict:(NSDictionary*)buDict toFile:(NSString*)inFile;
+(BOOL)backupThreadIsBusy;
+(BOOL)openMetaThreadIsBusy;
+(NSDate*)modDateOfFile:(NSString*)inPath;
+(NSDate*)creationDateOfFile:(NSString*)inPath;
+(void)singleFileQueueIsBusyError;
+(NSDictionary*)openMetaDictForPath:(NSString*)inPath;
@end
@implementation OpenMetaBackup
//----------------------------------------------------------------------
// OpenMetaBackup
//
// OpenMetaBackup - the idea is to store a backup of all user entered meta data - eg tags, ratings, etc.
// these are backed up to a folder in the application support folder Library/Application Support/OpenMeta/2009/1/lotsOfbackupfiles.omback
//
// When tags, etc are about to be set on a document and the document has no openmeta data set on it, we check to make sure that it is actually an empty doc,
// and not some doc that has had the metadata stripped away.
//
// Currently, any setting of an kMDItemOM* key will cause a backup to happen. Restore is attempted for Tags and ratings only - if you need to restore, then you have to call it yourself,
// which is easy.
//
//
//
// Created by Tom Andersen on 2009/01/26
//
//----------------------------------------------------------------------
#pragma mark backup and restore openmeta data
//----------------------------------------------------------------------
// backupMetadata
//
// Purpose: backs up metadata for the passed path.
// can be called many times in a row, will coalesce backup requests into one write
//
//
// Inputs: gDoOpenMetaBackups
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/26
//
//----------------------------------------------------------------------
+(void)backupMetadata:(NSString*)inPath;
{
if (!gDoOpenMetaBackups)
return;
if ([inPath length] == 0)
return;
// backups are handled by a thread that has a queue
NSThread* buThread = [self backupThread];
[self performSelector:@selector(enqueueBackupItem:) onThread:buThread withObject:inPath waitUntilDone:NO];
}
+(BOOL)hasTagsOrRatingsSet:(NSString*)inPath;
{
// if the ratings have been set OR removed, there will still be a time stamp for this.
if ([OpenMeta getXAttr:[OpenMeta openmetaTimeKey:(NSString*)kMDItemStarRating] path:inPath error:nil])
return YES;
// if the tags have been set OR removed, there will still be a time stamp for this.
if ([OpenMeta getXAttr:[OpenMeta openmetaTimeKey:(NSString*)kMDItemOMUserTags] path:inPath error:nil])
return YES;
return NO;
}
+(void)restoreMetadata:(NSString*)inPath withDelay:(NSTimeInterval)inDelay;
{
if (![[NSFileManager defaultManager] fileExistsAtPath:inPath])
return;
if ([self hasTagsOrRatingsSet:inPath])
return;
// if a file has nothing set on it, then either has never been tagged, or some process like adobe photoshop et al., has stripped off the tags. At this point we can't tell which, so we search for a restore.
[self restoreMetadataSearchForFile:inPath withDelay:inDelay];
}
//----------------------------------------------------------------------
// restoreMetadata (public call)
//
// Purpose: if there is openmeta data of any sort set on the file, this call returns without doing anything.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/26
//
//----------------------------------------------------------------------
+(void)restoreMetadata:(NSString*)inPath;
{
// the delay thing is used to work around a bug/problem with spotlight not noticing multiple changes to files in the same second.
[self restoreMetadata:inPath withDelay:0.0];
}
#pragma mark upgrade to kMDItemOMUserTags
//----------------------------------------------------------------------
// upgradeOpenMetaTokMDItemOM (public call)
//
// Purpose: Allows old applications using kOMUserTags to work with applications that use the newer format.
// this should be run in any major app that uses open meta until about 2010, say Feb. After that only run
// if user wants to run it?
//
// NOTE: Only call once per running of the application
//
// Created by Tom Andersen on 2009/10/08
//
//----------------------------------------------------------------------
+(void)upgradeOpenMetaTokMDItemOM;
{
static NSOperationQueue* operationQ = nil;
if (operationQ != nil)
return; // only call once
operationQ = [[NSOperationQueue alloc] init];
OpenMetaUpgradeOperation* newOperation = [[[OpenMetaUpgradeOperation alloc] init] autorelease];
[operationQ addOperation:newOperation];
}
#pragma mark backup and restore to from single file
NSOperationQueue* singleFileOperationQueue = nil;
+(NSOperationQueue*)singleFileQueue;
{
if (singleFileOperationQueue == nil)
singleFileOperationQueue = [[NSOperationQueue alloc] init];
return singleFileOperationQueue;
}
//----------------------------------------------------------------------
// backupAllMetadata (public call)
//
// Purpose: Make a single large backup file of all openmeta data. Data is obtained via a Spotlight Search on the passed keys.
// If the passed keys are empty or nil, then kMDItemOMUserTags, kMDItemStarRating and kMDItemOMManaged are backed up.
// This call is async. When the operation is done, a notification on the main thread will be sent out with a dictionary describing what happened.
//
// Inputs:
//
// Outputs: Note that all Openmeta data is backed up, not just the keys passed in. The passed in keys are for search only.
//
// Created by Tom Andersen on 2009/01/26
//
//----------------------------------------------------------------------
+(void)backupMetadataToSingleFile:(NSArray*)keysToSearch toFile:(NSString*)toFile;
{
if ([[[self singleFileQueue] operations] count] > 0)
{
[self singleFileQueueIsBusyError];
return;
}
OpenMetaBackupOperation* newOperation = [[[OpenMetaBackupOperation alloc] init] autorelease];
newOperation.keysToSearch = keysToSearch;
newOperation.singleFile = toFile;
newOperation.writeFile = YES;
[[self singleFileQueue] addOperation:newOperation];
}
+(void)restoreMetadataFromSingleFile:(NSString*)inBackupFile;
{
if ([[[self singleFileQueue] operations] count] > 0)
{
[self singleFileQueueIsBusyError];
return;
}
OpenMetaBackupOperation* newOperation = [[[OpenMetaBackupOperation alloc] init] autorelease];
newOperation.singleFile = inBackupFile;
newOperation.writeFile = NO;
[[self singleFileQueue] addOperation:newOperation];
}
#pragma mark backup paths and stamps
//----------------------------------------------------------------------
// calculateBackupFileName
//
// Purpose: the backup stap for the file - what the stamp should be for the passed path - NOT what is stored on disk
//
// Inputs: The stamp is a combination of a parital (full for short) file's name, a hash of the file name and a hash of the full path.
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(NSString*)calculateBackupFileName:(NSString*)inPath;
{
NSString* fileName = [self truncatedPathComponent:[inPath lastPathComponent]];
NSString* fileNameHash = [self hashString:[inPath lastPathComponent]]; // hash the name
NSString* folderHash = [self hashString:[inPath stringByDeletingLastPathComponent]]; // hash is for the parent folder - this allows for searching for renamed files in some cases...
NSString* buFileName = [fileName stringByAppendingString:@"__"];
buFileName = [buFileName stringByAppendingString:fileNameHash];
buFileName = [buFileName stringByAppendingString:@"__"];
buFileName = [buFileName stringByAppendingString:folderHash];
buFileName = [buFileName stringByAppendingString:@".omback"];
return buFileName;
}
//----------------------------------------------------------------------
// backupPathForMonthsBeforeNow
//
// Purpose: I store backups in month - dated folders. Once a month is over, i won't write any new files in that month. (there are very small time zone issues)
// Thus in the future, an optimized 'old' month searching db / fast access could be made...
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(NSString*) backupPathForMonthsBeforeNow:(int)inMonthsBeforeNow;
{
NSString* backupPath = [kBackupPath stringByExpandingTildeInPath];
// I changed the backup path to have .noindex on it, to prevent indexing by spotlight.
// In order to support older OpenMeta apps out there, I create a sym link that points from the old path to the new one.
if (gDoOpenMetaBackups && ![[NSFileManager defaultManager] fileExistsAtPath:backupPath])
{
NSString* oldBackupPath = [@"~/Library/Application Support/OpenMeta/backups" stringByExpandingTildeInPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:oldBackupPath])
rename([oldBackupPath fileSystemRepresentation], [backupPath fileSystemRepresentation]); // the old one was there, so rename it to the new .noindex name
else
[[NSFileManager defaultManager] createDirectoryAtPath:backupPath withIntermediateDirectories:YES attributes:nil error:nil]; // create it - this is likely a first run
symlink([backupPath fileSystemRepresentation], [oldBackupPath fileSystemRepresentation]); // create a link called backup that points to backup.noindex
}
NSCalendarDate* todaysDate = [NSCalendarDate calendarDate];
int theYear = [todaysDate yearOfCommonEra];
int theMonth = [todaysDate monthOfYear]; // 1 - 12 returned
// adjust:
theMonth -= inMonthsBeforeNow;
while (theMonth < 1)
{
theMonth += 12;
theYear -= 1;
}
backupPath = [backupPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", theYear]];
backupPath = [backupPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", theMonth]];
return backupPath;
}
//----------------------------------------------------------------------
// currentBackupPath
//
// Purpose: The path to the folder for the current months backups. Directory created if needed.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(NSString*) currentBackupPath;
{
NSString* bupath = [self backupPathForMonthsBeforeNow:0];
if (gDoOpenMetaBackups && ![[NSFileManager defaultManager] fileExistsAtPath:bupath])
[[NSFileManager defaultManager] createDirectoryAtPath:bupath withIntermediateDirectories:YES attributes:nil error:nil];
return bupath;
}
//----------------------------------------------------------------------
// truncatedPathComponent
//
// Purpose: backupStamps and backupfiles need to have filenames that are manageable. This truncs filenames by cutting in the middle.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(NSString*)truncatedPathComponent:(NSString*)aPathComponent;
{
if ([aPathComponent length] > 40)
{
// we need to trunc the same way every time... - take first 20 plus last twenty
aPathComponent = [[aPathComponent substringToIndex:20] stringByAppendingString:[aPathComponent substringFromIndex:[aPathComponent length] - 20]];
}
return aPathComponent;
}
//----------------------------------------------------------------------
// backupPathForItem
//
// Purpose: place to write backup file for passed item
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(NSString*) backupPathForItem:(NSString*)inPath;
{
// now create the special name that allows lookup:
// our file names are: the filename.extension__hash.omback
return [[self currentBackupPath] stringByAppendingPathComponent:[self calculateBackupFileName:inPath]];
}
#pragma mark restore all metadata - bulk
BOOL gOMRestoreThreadBusy = NO;
BOOL gOMIsTerminating = NO;
+(BOOL)backupDictsTheSame:(NSDictionary*)one two:(NSDictionary*)two;
{
if ([one count] != [two count])
return NO;
NSArray* keys = [one allKeys];
for (NSString* aKey in keys)
{
id obj1 = [one objectForKey:aKey];
id obj2 = [two objectForKey:aKey];
// if both objects are dates, they will compare non equal, even though they both were spawned by the same date: the stored date in a backup file is only good to the second, I think that the binary plist gets more resolution?
if ([obj1 isKindOfClass:[NSDate class]] && [obj2 isKindOfClass:[NSDate class]])
{
// compare the dates
NSTimeInterval difference = [obj1 timeIntervalSinceDate:obj2];
if (fabs(difference) > 2.0)
return NO;
}
else
{
if (![obj1 isEqual:obj2])
return NO;
}
}
return YES;
}
+(int)restoreMetadataFromBackupDictIfNeeded:(NSDictionary*)backupContents;
{
if ([backupContents count] == 0)
return 0;
NSString* filePath = [backupContents objectForKey:@"bu_path"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
OSErr theErr;
filePath = [self resolveAliasDataToPathFileIDFirst:[backupContents objectForKey:@"bu_alias"] osErr:&theErr];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
return 0; // could find no file to bu to.
}
// obtain the current state of affairs on the file by looking at a backup dict from the existing file:
NSDictionary* currentData = [OpenMetaBackup openMetaDictForPath:filePath];
NSDictionary* omDataFromBackup = [backupContents objectForKey:@"omDict"];
if ([currentData count] == 0 && [omDataFromBackup count] == 0)
return 0; // no data anywhere
if ([self backupDictsTheSame:currentData two:omDataFromBackup])
return 0;
// there is a difference between what is on the file and the backup stuff passed in.
// it could be that the backup stuff is old, etc. So look at that.
int numKeysSet = [self restoreMetadataDict:backupContents toFile:filePath];
#if KP_DEBUG
if (numKeysSet > 0)
NSLog(@"meta data repaired on %@ with %@", filePath, backupContents);
#endif
return numKeysSet;
}
//----------------------------------------------------------------------
// restoreMetadataFromBackupFileIfNeeded
//
// Purpose: restores kMDItemOM* data
//
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(int)restoreMetadataFromBackupFileIfNeeded:(NSString*)inPathToBUFile;
{
NSDictionary* backupContents = [NSDictionary dictionaryWithContentsOfFile:inPathToBUFile];
return [self restoreMetadataFromBackupDictIfNeeded:backupContents];
}
//----------------------------------------------------------------------
// tellUserRestoreFinished
//
// Purpose: will show a modal dialog when the restore is finished.
//
// Inputs: you can override the strings in a localization file
//
// Outputs:
//
// Created by Tom Andersen on 2009/03/11
//
//----------------------------------------------------------------------
+(void)tellUserRestoreFinished:(NSNumber*)inNumberOfFilesRestored;
{
NSString* title = NSLocalizedString(@"Open Meta Restore Done", @"");
NSString* comments = NSLocalizedString(@"No files needed to have meta data such as tags and ratings restored.", @"");
if ([inNumberOfFilesRestored intValue] > 0)
{
comments = NSLocalizedString(@"%1 files had meta data such as tags and ratings restored.", @"");
comments = [comments stringByReplacingOccurrencesOfString:@"%1" withString:[inNumberOfFilesRestored stringValue]];
}
// There is some UI in the OpenMeta code. If you don't want to or can't link to UI, then define OPEN_META_NO_UI in the compiler settings.
// ie: in the target info in XCode set : Preprocessor Macros Not Used In Precompiled Headers OPEN_META_NO_UI=1
#if OPEN_META_NO_UI
NSLog(@" %@ \n %@ ", title, comments);
#else
NSRunAlertPanel( title,
comments,
nil,
nil,
nil,
nil);
#endif
}
//----------------------------------------------------------------------
// restoreAllMetadata
//
// Purpose: should be run as a 'job' on a thread to restore metadata to every file it can find that has no metadata set.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/26
//
//----------------------------------------------------------------------
+(void)restoreAllMetadata:(NSNumber*)tellUserWhenDoneNS;
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
BOOL tellUserWhenDone = [tellUserWhenDoneNS boolValue];
// go through files, opening up as needed the filePath metadata...
// when i find one that needs restoring, also issue a call to add it to this month's list of edits.
// look through the previous 12 months for data.
// when i find it needs restoring, also issue a call to add it to this month's list of edits.
int count;
int numFilesFixed = 0;
int numFilesChecked = 0;
for (count = 0; count < 36; count++)
{
NSString* backupDir = [self backupPathForMonthsBeforeNow:count];
NSArray* fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:backupDir error:nil];
// the file name and folder name in the backup file filename may be truncated:
for (NSString* aFileName in fileNames)
{
NSAutoreleasePool* innerPool = [[NSAutoreleasePool alloc] init];
// our file names have: the filename.extension__pathhash.omback
// just plow through, restoring...
numFilesFixed += [self restoreMetadataFromBackupFileIfNeeded:[backupDir stringByAppendingPathComponent:aFileName]];
numFilesChecked++;
if (!tellUserWhenDone)
[NSThread sleepForTimeInterval:0.05]; // don't push too hard if we are running lazily (not telling the user when we are done)
if (gOMIsTerminating)
{
[innerPool release];
[pool release];
gOMRestoreThreadBusy = NO;
return;
}
[innerPool release];
}
}
#if KP_DEBUG
NSLog(@"%d files checked for restore", numFilesChecked);
#endif
if (tellUserWhenDone)
{
NSNumber* numFilesFixedNS = [NSNumber numberWithInt:numFilesFixed];
[self performSelectorOnMainThread:@selector(tellUserRestoreFinished:) withObject:numFilesFixedNS waitUntilDone:YES];
}
[pool release];
gOMRestoreThreadBusy = NO;
}
//----------------------------------------------------------------------
// restoreAllMetadataOnBackgroundThread
//
// Purpose:
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(void)restoreAllMetadataOnBackgroundThread:(BOOL)tellUserWhenDone;
{
if (gOMRestoreThreadBusy)
{
NSLog(@"meta data restore already running");
return;
}
gOMRestoreThreadBusy = YES;
NSNumber* tellUserWhenDoneNS = [NSNumber numberWithBool:tellUserWhenDone];
[NSThread detachNewThreadSelector:@selector(restoreAllMetadata:) toTarget:self withObject:tellUserWhenDoneNS];
}
+(BOOL)restoreThreadIsBusy;
{
return gOMRestoreThreadBusy;
}
//----------------------------------------------------------------------
// appIsTerminating
//
// Purpose: call this to tell restore and other functions running in the background to gracefully exit.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(void)appIsTerminating;
{
gOMIsTerminating = YES;
while ([OpenMetaBackup openMetaThreadIsBusy])
[NSThread sleepForTimeInterval:0.1];
}
//----------------------------------------------------------------------
// openMetaThreadIsBusy
//
// Purpose: returns true if some backup thread is working on stuff
//
// usage: at terminate
// while ([OpenMetaBackup openMetaThreadIsBusy])
// [NSThread sleepForTimeInterval:0.1];
//
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(BOOL)openMetaThreadIsBusy;
{
if ([self restoreThreadIsBusy] || [self backupThreadIsBusy])
return YES;
return NO;
}
#pragma mark copy old kOM tags to new kMDItemOM tags
//----------------------------------------------------------------------
// copyTagsFromOldKeyTokMDItemOMIfNeeded
//
// Purpose: Oct 8, 2009 : if user has old and new api on the system, then they will sometimes enter keys using the old api.
// before doing a get tags for editing type of event,
//
// Inputs: THE DICT is NOT the entire file - just the actual backed up data - the omDict.
//
// Outputs:
//
// Created by Tom Andersen on 2009/10/08
//
//----------------------------------------------------------------------
+(void)copyTagsFromOldKeyTokMDItemOMIfNeeded:(NSString*)inPath;
{
NSError* error = nil;
// if someone is using an older api, tags will be set with:
// org.openmetainfo:kOMUserTags [array of tags]
// org.openmetainfo.time:kOMUserTags [NSDate]
// With the new api, they will set tags like
// org.openmetainfo:kMDItemOMUserTags [array of tags]
// org.openmetainfo.time:kMDItemOMUserTags [NSDate]
// we compare the two dates. If the kOMUserTagTime is newer than kMDItemOMUserTagTime, then we copy tags from kOMUserTags into kMDItemOMUserTags
NSDate* thekOMDate = [OpenMeta getXAttr:@"org.openmetainfo.time:kOMUserTags" path:inPath error:&error];
NSDate* thekMDItemOMDate = [OpenMeta getXAttr:@"org.openmetainfo.time:kMDItemOMUserTags" path:inPath error:&error];
if (thekOMDate == nil)
return; // there was no date information on the file.
// to compare dates they both need to be there:
if (thekOMDate == nil)
thekOMDate = [NSDate distantPast];
if (thekMDItemOMDate == nil)
thekMDItemOMDate = [NSDate distantPast];
// can't use compare, as that is sub - second, and the dates in plists are not that accurate.
NSTimeInterval dateCompare = [thekOMDate timeIntervalSinceDate:thekMDItemOMDate];
// positive values indicate that the thekOMDate is later than the thekMDItemOMDate date, so we should use it.
// note that if the tags were wiped out by a cocoa nsdocument based save in 10.6, then the times will have been wiped away.
// in that case, dateCompare should be <= 0, so we won't rewrite them.
if (dateCompare >= 2.0)
{
NSArray* thekOMTags = [OpenMeta getXAttr:@"org.openmetainfo:kOMUserTags" path:inPath error:&error];
NSArray* thekMDItemOMTags = [OpenMeta getXAttr:@"org.openmetainfo:kMDItemOMUserTags" path:inPath error:&error];
// someone could have erased the tags using an older api, etc, so we should honour that kind of thing?
if (![thekOMTags isEqualToArray:thekMDItemOMTags])
{
// set the tags,
// set user tags,
[OpenMeta setXAttr:thekOMTags forKey:@"org.openmetainfo:kMDItemOMUserTags" path:inPath];
[OpenMeta setXAttr:thekOMTags forKey:@"com.apple.metadata:kMDItemOMUserTags" path:inPath];
[OpenMeta setXAttr:thekOMDate forKey:@"org.openmetainfo.time:kMDItemOMUserTags" path:inPath];
}
}
}
#pragma mark restoring metadata
//----------------------------------------------------------------------
// restoreMetadataDict
//
// Purpose: Oct 8, 2009 : changing OpenMeta prefix to work with Snow Leopard bug
//
// Inputs: THE DICT is NOT the entire file - just the actual backed up data - the omDict.
//
// Outputs:
//
// Created by Tom Andersen on 2009/10/08
//
//----------------------------------------------------------------------
+(int)restoreOldMetadataKey:(NSString*)aKey fromDict:(NSDictionary*)omDict toFile:(NSString*)inFile;
{
// the passed key is an 'old' kOM key. We only set 'new' format data, and only do that if there is no openmetainfo org stuff on the file.
// this keeps things simple.
id dataInBU = [omDict objectForKey:aKey];
if (dataInBU)
{
NSError* error = nil;
// only set data that is not already set - the idea of a backup is only replace if missing...
// if there is new format data on disk then we are done.
NSString* newKey = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:kOM" withString:@"org.openmetainfo:kMDItemOM"];
id data = [OpenMeta getXAttr:newKey path:inFile error:&error];
if (data)
return 0;
NSString* newTimeKey = [newKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:" withString:@"org.openmetainfo.time:"];
// There was no org.openmetainfo on the file... what about com.apple.metadata?
NSString* newKeySpotlight = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:kOM" withString:@"com.apple.metadata:kMDItemOM"];
data = [OpenMeta getXAttr:newKeySpotlight path:inFile error:&error];
if (data)
{
// repair the data - but use the existing on disk data - it will likely be newer, and is likely from 10.6 save bug issue
[OpenMeta setXAttr:data forKey:newKey path:inFile];
// set the date as now:
[OpenMeta setXAttr:[NSDate date] forKey:newTimeKey path:inFile];
return 1;
}
// there was no data of any sort, so use what we have, but update the data:
NSString* oldTimeKey = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:" withString:@"org.openmetainfo.time:"];
NSDate* dateInBU = [omDict objectForKey:oldTimeKey];
BOOL writeDate = (dateInBU != nil);
NSString* oldAppleMetaDataKey = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:" withString:@"com.apple.metadata:"];
[OpenMeta setXAttr:dataInBU forKey:newKey path:inFile];
if ([omDict objectForKey:oldAppleMetaDataKey])
[OpenMeta setXAttr:dataInBU forKey:newKeySpotlight path:inFile];
// if the backup date is 'real' then write it too:
if (writeDate)
[OpenMeta setXAttr:dateInBU forKey:newTimeKey path:inFile];
return 1;
}
return 0;
}
//----------------------------------------------------------------------
// restoreMetadataDict
//
// Purpose: Sep 1, 2009 : only restore open meta data
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(int)restoreMetadataDict:(NSDictionary*)buDict toFile:(NSString*)inFile;
{
NSDictionary* omDict = [buDict objectForKey:@"omDict"];
int numKeysRestored = 0;
NSError* error = nil;
for (NSString* aKey in [omDict allKeys])
{
// only restore open meta data:
// backward compatibility kOM
if ([aKey hasPrefix:@"org.openmetainfo.kOM"])
{
// this is an older backup record. We need to handle this differently:
numKeysRestored += [self restoreOldMetadataKey:aKey fromDict:omDict toFile:inFile];
}
else if ([aKey hasPrefix:@"org.openmetainfo:"])
{
id dataInBU = [omDict objectForKey:aKey];
if (dataInBU)
{
// Compare dates
// get the dates on the attribute on disk and the attribute in the backup dict:
NSString* timeKey = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:" withString:@"org.openmetainfo.time:"];
NSDate* dateOnDisk = [OpenMeta getXAttr:timeKey path:inFile error:&error];
NSDate* dateInBU = [omDict objectForKey:timeKey];
BOOL writeDate = (dateInBU != nil);
// to compare dates they both need to be there:
if (dateOnDisk == nil)
dateOnDisk = [NSDate distantPast];
if (dateInBU == nil)
dateInBU = [NSDate distantPast];
NSString* appleMetaDataKey = [aKey stringByReplacingOccurrencesOfString:@"org.openmetainfo:" withString:@"com.apple.metadata:"];
// can't use compare, as that is sub - second, and the dates in the backup files are only accurate to the second.
NSTimeInterval dateCompare = [dateInBU timeIntervalSinceDate:dateOnDisk]; // positive values indicate that the dateInBackup is newer than the on disk date.
if (fabs(dateCompare) < 2.0)
{
// the dates are the same. Only set if the data is missing on disk
id objectOnDisk = [OpenMeta getXAttr:aKey path:inFile error:&error];
if (objectOnDisk == nil)
{
numKeysRestored++;
[OpenMeta setXAttr:dataInBU forKey:aKey path:inFile];
if ([omDict objectForKey:appleMetaDataKey])
[OpenMeta setXAttr:dataInBU forKey:appleMetaDataKey path:inFile];
// if the backup date is 'real' then write it too:
if (writeDate)
[OpenMeta setXAttr:dateInBU forKey:timeKey path:inFile];
}
}
else if (dateCompare >= 2.0)
{
// the backup time is later than the on disk time - the data is old.
numKeysRestored++;
[OpenMeta setXAttr:dataInBU forKey:aKey path:inFile];
if ([omDict objectForKey:appleMetaDataKey])
[OpenMeta setXAttr:dataInBU forKey:appleMetaDataKey path:inFile];
// if the backup date is 'real' then write it too:
if (writeDate)
[OpenMeta setXAttr:dateInBU forKey:timeKey path:inFile];
}
}
}
}
return numKeysRestored;
}
+(BOOL)modDateOfFile:(NSString*)inBackupPath isAfterCreationDateOf:(NSString*)inFile;
{
NSDate* modDate = [self modDateOfFile:inBackupPath];
NSDate* creationDate = [self creationDateOfFile:inFile];
NSComparisonResult compareResult = [modDate compare:creationDate];
if (compareResult == NSOrderedSame || compareResult == NSOrderedDescending)
return YES;
return NO;
}
//----------------------------------------------------------------------
// restoreMetadataFromBackupFile
//
// Purpose: restores data to the passed path. Will only restore if the passed path matches the alias or the stored path. (we also check filename in emergency)
//
// Inputs:
//
// Outputs: Returns YES if the dictionary looked like it was the right one for the file.
// Does NOT tell you if any restore was actually done.
//
// Created by Tom Andersen on 2009/01/28
//
//----------------------------------------------------------------------
+(BOOL)restoreMetadataFromBackupFile:(NSString*)inPathToBUFile toFile:(NSString*)inPath withDelay:(NSTimeInterval)inDelay;
{
NSDictionary* backupContents = [NSDictionary dictionaryWithContentsOfFile:inPathToBUFile];
if ([backupContents count] == 0)
return NO;
// if an alias path comes back, then we know there is a file there.
OSErr theErr;
NSString* aliasPath = [self resolveAliasDataToPathFileIDFirst:[backupContents objectForKey:@"bu_alias"] osErr:&theErr];
// if the path is right, then look at restoring and returning:
if ([inPath isEqualToString:[backupContents objectForKey:@"bu_path"]])
{
// Another tweak: Applications, and perhaps other file types like to use path based tags - when you update an application,
// you want the tags to be reapplied.
if ([[inPath pathExtension] isEqualToString:@"app"])
{
if (inDelay > 0.0)
[NSThread sleepForTimeInterval:inDelay];
[self restoreMetadataDict:backupContents toFile:inPath];
return YES;
}
// the path is the same as the backup path.
// we can still trip over the 'Picture 1" scenario - Picture 1 lands on the desktop and is promptly tagged
// then renamed and moved. So the tags are on the moved file.
// when the next screenshot comes down the pipe, the alias will point to the moved file, which is what we want
// but if the alias does not work, then we know that the original is nowhere to be found, so we can add tags to this file.
if ([aliasPath length] == 0 || [inPath isEqualToString:aliasPath])
{
if (inDelay > 0.0)
[NSThread sleepForTimeInterval:inDelay];
[self restoreMetadataDict:backupContents toFile:inPath];
return YES;
}
}
// if the alias resolves to the path
if ([inPath isEqualToString:aliasPath])
{
// the file has moved. Or it seems likely that the file has moved.
if ([self modDateOfFile:inPathToBUFile isAfterCreationDateOf:inPath])
{
if (inDelay > 0.0)
[NSThread sleepForTimeInterval:inDelay];
[self restoreMetadataDict:backupContents toFile:inPath];
}
return YES;
}
return NO;
}
//----------------------------------------------------------------------
// modDateOfFile
//
// Purpose:
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/04/30
//
//----------------------------------------------------------------------
+(NSDate*)modDateOfFile:(NSString*)inPath;
{
NSDate* modDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:inPath error:nil] objectForKey:NSFileModificationDate];
if (modDate == nil)
modDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; // that way asking for a non existent directory will also cache nicely
return modDate;
}
+(NSDate*)creationDateOfFile:(NSString*)inPath;
{
NSDate* creationDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:inPath error:nil] objectForKey:NSFileCreationDate];
if (creationDate == nil)
creationDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; // that way asking for a non existent directory will also cache nicely
return creationDate;
}
//----------------------------------------------------------------------
// cachedContentsOfDirectoryAtPath
//
// Purpose: returns contents of directory - open meta keeps a cached copy for performance reasons.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/04/30
//
//----------------------------------------------------------------------
+(NSArray*)cachedContentsOfDirectoryAtPath:(NSString*)inPath;
{
static NSMutableDictionary* cachedDirectories = nil;
if (cachedDirectories == nil)
cachedDirectories = [[NSMutableDictionary alloc] init];
@synchronized(cachedDirectories)
{
NSDictionary* cachedPaths = [cachedDirectories objectForKey:inPath];
if (cachedPaths)
{
// if the date is good, then return with info.
if ([[cachedPaths objectForKey:@"modDate"] isEqual:[self modDateOfFile:inPath]])
{
return [[[cachedPaths objectForKey:@"files"] retain] autorelease]; // the retain autorelease makes for thread safe
}
}
// ok - we got to here - it means that we have to make a new entry in the dict:
NSArray* fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:inPath error:nil];
if (fileNames == nil)
fileNames = [NSArray array]; // if someone asks for non exitent file, we cache that as an empty array with a date at the reference date
cachedPaths = [NSDictionary dictionaryWithObjectsAndKeys:fileNames, @"files", [self modDateOfFile:inPath], @"modDate", nil];
[cachedDirectories setObject:cachedPaths forKey:inPath];
return fileNames; // since we just made them in this thread they are auto released in the right pool.
}
return nil; // compiler happy
}
//----------------------------------------------------------------------
// cachedContentsOfDirectoryAtPathAsString
//
// Purpose: returns all the filenames in a directory mashed together in one c string (utf8 file sys rep), nil terminated.
//
// Inputs:
//
// Outputs:
//
// Created by Tom Andersen on 2009/05/19
//
//----------------------------------------------------------------------
+(char*)cachedContentsOfDirectoryAtPathAsString:(NSString*)inPath;
{
static NSMutableDictionary* cachedDirectoriesCStrings = nil;
if (cachedDirectoriesCStrings == nil)
cachedDirectoriesCStrings = [[NSMutableDictionary alloc] init];
@synchronized(cachedDirectoriesCStrings)
{
NSDictionary* cachedPaths = [cachedDirectoriesCStrings objectForKey:inPath];
if (cachedPaths)
{
// if the date is good, then return with info.
if ([[cachedPaths objectForKey:@"modDate"] isEqual:[self modDateOfFile:inPath]])
{
NSData* theData = [[[cachedPaths objectForKey:@"mashedFileNames"] retain] autorelease]; // the retain autorelease makes for thread safe
char* longCString = (char*) [theData bytes];