-
Notifications
You must be signed in to change notification settings - Fork 3
/
iPhotoFilesystem.m
638 lines (514 loc) · 19.2 KB
/
iPhotoFilesystem.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
/*
iPhotoFilesystem.m
iMediaBrowse
Copyright [2009] by Phillip Bogle
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <sys/xattr.h>
#import <sys/stat.h>
#import <MacFUSE/MacFUSE.h>
#import "iPhotoFilesystem.h"
#import "WatchDog.h"
#define TEST_ALBUM_PATH nil
// #define TEST_ALBUM_PATH ([NSHomeDirectory() stringByAppendingString: @"/ExtAlbumData.xml"])
@implementation iPhotoFilesystem
// NOTE: It is fine to remove the below sections that are marked as 'Optional'.
// The core set of file system operations. This class will serve as the delegate
// for GMUserFileSystemFilesystem. For more details, see the section on
// GMUserFileSystemOperations found in the documentation at:
// http://macfuse.googlecode.com/svn/trunk/core/sdk-objc/Documentation/index.html
#pragma mark Directory Contents
- (id) init
{
if (self = [super init]) {
[self parsePhotos];
}
return self;
}
- (NSMutableDictionary *) folderForKey: (NSString *) iPhotoKey nameKey: (NSString *) nameKey idKey: (NSString *) idKey
{
if (!iPhotoKey || !nameKey || !idKey) {
return nil;
}
NSArray * listOfFolders = [_iPhotoDatabase objectForKey: iPhotoKey];
NSMutableDictionary *folderDictionary = [[[NSMutableDictionary alloc] init] autorelease];
NSEnumerator * enumerator = [listOfFolders objectEnumerator];
NSDictionary * current;
while (current = [enumerator nextObject])
{
NSString *name = [current objectForKey: nameKey];
// see if we need to strip hi characters
bool stripHiChars = false;
for (int i=0, len = name.length; i < len; i++) {
if ([name characterAtIndex: i] > 128) {
stripHiChars = true;
break;
}
}
if (stripHiChars) {
name = [NSMutableString stringWithString: name];
CFStringNormalize((CFMutableStringRef)name, kCFStringNormalizationFormD);
}
if ([name rangeOfString: @" "].location >= 0) {
// replace spaces with underscores for command line friendliness
name = [name stringByReplacingOccurrencesOfString: @" " withString: @"_"];
}
/*
* For Rolls, prepend with the date of the roll (for easy directory sorting)
*/
if ([iPhotoKey isEqualToString:@"List of Rolls"]){
NSNumber *dateInterval = [current objectForKey: @"RollDateAsTimerInterval"];
if (dateInterval) {
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate: [dateInterval intValue]];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"yyy-MM-dd_"];
NSString *dateString = [dateFormat stringFromDate:date];
name = [dateString stringByAppendingString:name];
}
}
/*if (stripHiChars) {
NSMutableString *s = [[NSMutableString alloc] init];
for (int i=0; i < name.length; i++) {
unsigned char ch = [name characterAtIndex: i];
if (ch > 128) {
[s appendString: @"?"];
} else {
[s appendFormat: @"%c", ch];
}
}
name = s;
}
name = [NSString stringWithCString: [name UTF8String]];
*/
if ([folderDictionary valueForKey: name]) {
// name collision, uniquify the name with the roll ID
name = [NSString stringWithFormat: @"%@_%@", name, [current objectForKey: idKey]];
}
[current setValue: name forKey: nameKey];
NSString * albumType= [current valueForKey: @"Album Type"];
NSString * parent = [current valueForKey:@"Parent"];
NSLog(@"Album Name: %@, Album type: %@, Parent: %@", name, albumType, parent);
if (parent == NULL) {
[folderDictionary setValue: current forKey: name ];
if ([iPhotoKey isEqualTo:@"List of Albums"]) {
//NSLog(@"Album Name: %@, Album type: %@", name, albumType);
}
}
} // end loop through albums
return folderDictionary;
}
- (NSString *) libraryPath
{
if (_libraryPath) {
return _libraryPath;
}
// debugging
NSString *libraryPath = nil;
NSString *testAlbumPath = TEST_ALBUM_PATH;
if (testAlbumPath) {
libraryPath = [testAlbumPath copy];
} else {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSDictionary* appPrefs = [ud persistentDomainForName:@"com.apple.iApps"];
NSArray *dbs = [appPrefs objectForKey:@"iPhotoRecentDatabases"];
if ([dbs count] > 0) {
NSURL *url = [NSURL URLWithString:[dbs objectAtIndex:0]];
if ([url isFileURL]) {
libraryPath = [[url path] copy];
}
}
if (!libraryPath) {
libraryPath = [[NSHomeDirectory() stringByAppendingString:
@"/Pictures/iPhoto Library/AlbumData.xml"]
copy];
}
}
_libraryPath = libraryPath;
return _libraryPath;
}
- (void)parsePhotos
{
_iPhotoDatabase = [[NSDictionary alloc] initWithContentsOfFile: [self libraryPath]];
_rootDict = [[NSMutableDictionary alloc] init];
NSString * iPhotoVersionString = [_iPhotoDatabase objectForKey:@"Application Version"];
int majorVersion = [iPhotoVersionString intValue];
// ------------------------------------------
// cache information about all of the albums
NSArray * listOfAlbums = [_iPhotoDatabase objectForKey:@"List of Albums"];
NSEnumerator * imageEnumerator = [listOfAlbums objectEnumerator];
_dateDict = [[NSMutableDictionary alloc] init];
[_rootDict setObject: [self folderForKey: @"List of Albums" nameKey: @"AlbumName" idKey: @"AlbumId"] forKey: @"Albums"];
if (majorVersion >= 7) {
[_rootDict setObject: [self folderForKey: @"List of Rolls" nameKey: @"RollName" idKey: @"RollID"] forKey: @"Rolls"];
} else {
[_rootDict setObject: [self folderForKey: @"List of Rolls" nameKey: @"AlbumName" idKey: @"AlbumID"] forKey: @"Rolls"];
}
[_rootDict setObject: _dateDict forKey: @"Dates"];
_imageDict = [_iPhotoDatabase objectForKey:@"Master Image List"];
[_imageDict retain];
_imageNameDict = [[NSMutableDictionary alloc] init];
imageEnumerator = [_imageDict keyEnumerator];
id key;
while ((key = [imageEnumerator nextObject])) {
NSDictionary *image = [_imageDict objectForKey: key];
NSString *path = [image objectForKey: @"ImagePath"];
NSString *name= [path lastPathComponent];
if (!name) { continue; }
NSNumber *dateInterval = [image objectForKey: @"DateAsTimerInterval"];
if (!dateInterval) { continue; }
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate: [dateInterval intValue]];
[self addImageKey: key forDate: date];
if ([_imageNameDict objectForKey: name]) {
// name collision, uniquify the name with the roll ID
name = [NSString stringWithFormat: @"%@.%@", [image objectForKey: @"Roll"], name];
}
[image setValue: name forKey: @"ImageName"];
[_imageNameDict setValue: image forKey: name];
}
}
- (NSMutableDictionary *) folderForDate: (NSDate *) date
{
if (!date) {
return nil;
}
NSString *dateFolderName = [date descriptionWithCalendarFormat:@"%Y-%m" timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
NSMutableDictionary *dateFolder = [_dateDict objectForKey: dateFolderName];
if (!dateFolder) {
dateFolder = [[NSMutableDictionary alloc] init];
[_dateDict setValue: dateFolder forKey: dateFolderName];
[dateFolder setObject: [[NSMutableArray alloc] init] forKey: @"KeyList"];
}
return dateFolder;
}
- (NSMutableArray *) keyListForDate: (NSDate *) date
{
return [[self folderForDate: date] objectForKey: @"KeyList"];
}
- (void) addImageKey: (NSString *)key forDate: (NSDate *) date
{
[[self keyListForDate: date] addObject: key];
}
- (void) dealloc
{
[_imageDict release];
[_rootDict release];
[_iPhotoDatabase release];
[_dateDict release];
[_libraryPath release];
[super dealloc];
}
- (NSDictionary *)libraryNodeForPath: (NSString *)path
{
NSArray *pathComponents = [path pathComponents];
if (pathComponents.count < 1) {
return nil;
}
NSDictionary *node = _rootDict;
// look up each path component, starting at 1 to skip "/"
for (int i=1, count = [pathComponents count]; i < count; i++) {
NSString *pathComponent = [pathComponents objectAtIndex: i];
NSArray *keylist = [node objectForKey: @"KeyList"];
if (keylist) {
node = [_imageNameDict objectForKey: pathComponent];
} else {
node = [node objectForKey: pathComponent];
}
}
return node;
}
- (NSString *)fileNameForPath: (NSString *)path
{
NSDictionary *node = [self libraryNodeForPath: path];
NSString *result = node ? [NSString stringWithCString: [[node objectForKey: @"ImagePath"] UTF8String] encoding: NSUTF8StringEncoding] : nil;
return result;
}
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path
error:(NSError **)error
{
NSDictionary *node = [self libraryNodeForPath: path];
NSArray *keylist = [node objectForKey: @"KeyList"];
if (keylist) {
NSMutableArray *contents = [[NSMutableArray alloc] init];
NSEnumerator * keyEnumerator = [keylist objectEnumerator];
NSString *currentKey;
while (currentKey = [keyEnumerator nextObject]) {
NSDictionary *image = [_imageDict objectForKey: currentKey];
NSString *imageName = [image objectForKey: @"ImageName"];
[contents addObject: imageName];
}
return contents;
} else {
return [[node allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
}
#pragma mark Getting Attributes
- (NSDictionary *)attributesOfItemAtPath:(NSString *)path userData:(id)ud error:(NSError **)error
{
/*
NSString* p = [rootPath_ stringByAppendingString:path];
NSDictionary* attribs = [[NSFileManager defaultManager] attributesOfItemAtPath:p error:error];
return attribs;
*/
NSDictionary *node = [self libraryNodeForPath: path];
if (!node) {
return nil;
}
NSArray *pathComponents = [path pathComponents];
BOOL isDirectory = [node objectForKey: @"MediaType"] == nil;
if (isDirectory) {
// look up the attributes of the first image
NSDictionary* attribs = nil;
NSArray *keys = [node objectForKey: @"KeyList"];
if ([keys count] > 0) {
NSDictionary *child = [_imageDict objectForKey: [keys objectAtIndex: 0]];
attribs =[[NSFileManager defaultManager] attributesOfItemAtPath: [child objectForKey: @"ImagePath"] error: nil] ;
}
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
/* [NSNumber numberWithInt:mode], NSFilePosixPermissions,
[NSNumber numberWithInt:geteuid()], NSFileOwnerAccountID,
[NSNumber numberWithInt:getegid()], NSFileGroupOwnerAccountID, */
attribs ? [attribs objectForKey: NSFileCreationDate] : [NSDate date] , NSFileCreationDate,
attribs ? [attribs objectForKey: NSFileModificationDate] : [NSDate date], NSFileModificationDate,
NSFileTypeDirectory, NSFileType,
nil];
return result;
} else if (![[pathComponents objectAtIndex: 1] isEqual: @"System"]) {
NSString *p = [self fileNameForPath: path];
NSDictionary* result = p ? [[NSFileManager defaultManager] attributesOfItemAtPath: p error:error] : nil;
return result;
} else {
return nil;
}
}
- (NSDictionary *)attributesOfFileSystemForPath:(NSString *)path
error:(NSError **)error
{
NSDictionary* d =[[NSFileManager defaultManager] attributesOfFileSystemForPath: @"/" error:error];
return d;
}
- (NSArray *)extendedAttributesOfItemAtPath:(NSString *)path error:(NSError **)error {
NSString *p = [self fileNameForPath: path];
if (!p) return nil;
ssize_t size = listxattr([p UTF8String], nil, 0, 0);
if ( size < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return nil;
}
NSMutableData* data = [NSMutableData dataWithLength:size];
size = listxattr([p UTF8String], [data mutableBytes], [data length], 0);
if ( size < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return nil;
}
NSMutableArray* contents = [NSMutableArray array];
char* ptr = (char *)[data bytes];
while ( ptr < ((char *)[data bytes] + size) ) {
NSString* s = [NSString stringWithUTF8String:ptr];
[contents addObject:s];
ptr += ([s length] + 1);
}
return contents;
}
- (NSData *)valueOfExtendedAttribute:(NSString *)name
ofItemAtPath:(NSString *)path
position:(off_t)position
error:(NSError **)error {
NSString *p = [self fileNameForPath: path];
if (!p) return nil;
ssize_t size = getxattr([p UTF8String], [name UTF8String], nil, 0,
position, 0);
if ( size < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return nil;
}
NSMutableData* data = [NSMutableData dataWithLength:size];
size = getxattr([p UTF8String], [name UTF8String],
[data mutableBytes], [data length],
position, 0);
if ( size < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return nil;
}
return data;
}
#pragma mark File Contents
- (BOOL)openFileAtPath:(NSString *)path
mode:(int)mode
userData:(id *)userData
error:(NSError **)error {
NSString* p = [self fileNameForPath: path];
int fd = open([p UTF8String], mode);
if ( fd < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return NO;
}
*userData = [NSNumber numberWithLong:fd];
return YES;
}
- (void)releaseFileAtPath:(NSString *)path userData:(id)userData {
NSNumber* num = (NSNumber *)userData;
int fd = [num longValue];
close(fd);
}
- (int)readFileAtPath:(NSString *)path
userData:(id)userData
buffer:(char *)buffer
size:(size_t)size
offset:(off_t)offset
error:(NSError **)error
{
NSNumber* num = (NSNumber *)userData;
int fd = [num longValue];
int ret = pread(fd, buffer, size, offset);
if ( ret < 0 ) {
*error = [NSError errorWithPOSIXCode:errno];
return -1;
}
return ret;
}
/*
#pragma mark Symbolic Links (Optional)
- (NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path
error:(NSError **)error {
*error = [NSError errorWithPOSIXCode:ENOENT];
return NO;
}
*/
/*
#pragma mark FinderInfo and ResourceFork (Optional)
- (NSDictionary *)finderAttributesAtPath:(NSString *)path
error:(NSError **)error {
NSDictionary* attribs = nil;
if ([self videoAtPath:path]) {
NSNumber* finderFlags = [NSNumber numberWithLong:kHasCustomIcon];
attribs = [NSDictionary dictionaryWithObject:finderFlags
forKey:kGMUserFileSystemFinderFlagsKey];
}
return attribs;
}
- (NSDictionary *)resourceAttributesAtPath:(NSString *)path
error:(NSError **)error
{
NSMutableDictionary* attribs = nil;
YTVideo* video = [self videoAtPath:path];
if (video) {
attribs = [NSMutableDictionary dictionary];
NSURL* url = [video playerURL];
if (url) {
[attribs setObject:url forKey:kGMUserFileSystemWeblocURLKey];
}
url = [video thumbnailURL];
if (url) {
NSImage* image = [[[NSImage alloc] initWithContentsOfURL:url] autorelease];
NSData* icnsData = [image icnsDataWithWidth:256];
[attribs setObject:icnsData forKey:kGMUserFileSystemCustomIconDataKey];
}
}
return attribs;
}
*/
@end
@implementation iPhotoFilesystemWithReloading
- (id) init
{
if (self = [super init]) {
_lock = [[NSLock alloc] init];
_lastReparseTime = nil;
[self reload];
[[Watchdog sharedWatchdog] watchLibrary: self];
}
return self;
}
- (iPhotoFilesystem *) fileSystem
{
[_lock lock];
iPhotoFilesystem *result = _iPhotoFileSystem;
[_lock unlock];
return result;
}
- (void)reload
{
const int minimumReparseInterval = 5;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow: -minimumReparseInterval];
if (!_lastReparseTime || [_lastReparseTime compare: date] < 0) {
iPhotoFilesystem *newFileSystem = [[iPhotoFilesystem alloc] init];
[_lock lock];
[_iPhotoFileSystem release];
_iPhotoFileSystem = newFileSystem;
[_lastReparseTime release];
_lastReparseTime = [[NSDate alloc] init];
[_lock unlock];
}
}
- (NSString *) libraryPath
{
return [[self fileSystem] libraryPath];
}
- (void) dealloc
{
[[Watchdog sharedWatchdog] forgetLibrary:self];
[_iPhotoFileSystem release];
[_lock release];
[_lastReparseTime release];
[super dealloc];
}
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error
{
return [[self fileSystem] contentsOfDirectoryAtPath: path error: error];
}
- (NSDictionary *)attributesOfItemAtPath:(NSString *)path userData:(id) ud error:(NSError **)error
{
return [[self fileSystem] attributesOfItemAtPath: path userData: ud error: error];
}
- (NSDictionary *)attributesOfFileSystemForPath:(NSString *)path error:(NSError **)error
{
return [[self fileSystem] attributesOfFileSystemForPath: path error: error];
}
- (NSData *)valueOfExtendedAttribute:(NSString *)name
ofItemAtPath:(NSString *)path
position:(off_t)position
error:(NSError **)error
{
return [[self fileSystem] valueOfExtendedAttribute:name ofItemAtPath:path position: position error: error];
}
- (BOOL)openFileAtPath:(NSString *)path
mode:(int)mode
userData:(id *)userData
error:(NSError **)error
{
return [[self fileSystem] openFileAtPath:path mode:mode userData: userData error: error];
}
- (void)releaseFileAtPath:(NSString *)path userData:(id)userData
{
return [[self fileSystem] releaseFileAtPath: path userData: userData];
}
- (int)readFileAtPath:(NSString *)path
userData:(id)userData
buffer:(char *)buffer
size:(size_t)size
offset:(off_t)offset
error:(NSError **)error
{
return [[self fileSystem] readFileAtPath: path userData:userData buffer:buffer size:size offset:offset error:error];
}
- (NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path
error:(NSError **)error
{
return [[self fileSystem] destinationOfSymbolicLinkAtPath: path error: error];
}
/*
- (NSData *) contentsAtPath: (NSString *) path
{
return [[self fileSystem] contentsAtPath: path];
}
*/
@end