/
TiFilesystemFileProxy.m
527 lines (449 loc) Β· 13.4 KB
/
TiFilesystemFileProxy.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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#if defined(USE_TI_FILESYSTEM) || defined(USE_TI_DATABASE) || defined(USE_TI_MEDIA)
#include <sys/xattr.h>
#import "TiBase.h"
#import "TiUtils.h"
#import "TiBlob.h"
#import "TiFilesystemFileProxy.h"
#import "TiFilesystemFileStreamProxy.h"
#define FILE_TOSTR(x) \
([x isKindOfClass:[TiFilesystemFileProxy class]]) ? [(TiFilesystemFileProxy*)x nativePath] : [TiUtils stringValue:x]
static const char* backupAttr = "com.apple.MobileBackup";
@implementation TiFilesystemFileProxy
-(id)initWithFile:(NSString*)path_
{
if (self = [super init])
{
fm = [[NSFileManager alloc] init];
path = [path_ retain];
}
return self;
}
-(void)dealloc
{
RELEASE_TO_NIL(fm);
RELEASE_TO_NIL(path);
[super dealloc];
}
-(NSString*)apiName
{
return @"Ti.Filesystem.File";
}
-(id)nativePath
{
return [[NSURL fileURLWithPath:path] absoluteString];
}
-(id)exists:(id)args
{
return NUMBOOL([fm fileExistsAtPath:path]);
}
#define FILEATTR(propName,attrKey,throwError) \
-(id) propName \
{ \
NSError *error = nil; \
NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];\
if ((throwError) && error!=nil) \
{ \
[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION]; \
} \
return [resultDict objectForKey:attrKey];\
}
FILEATTR(readonly,NSFileImmutable,NO)
FILEATTR(modificationTimestamp,NSFileModificationDate,YES);
-(id)createTimestamp
{
NSError *error = nil;
NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];
if ((YES) && error!=nil)
{
[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION];
}
// Have to do this one up special because of 3.x bug where NSFileCreationDate is sometimes undefined
id result = [resultDict objectForKey:NSFileCreationDate];
if (result == nil) {
result = [resultDict objectForKey:NSFileModificationDate];
}
return result;
}
//TODO: Should this be a method or a property? Until then, do both.
-(id)createTimestamp:(id)args
{
return [self createTimestamp];
}
-(id)modificationTimestamp:(id)args
{
return [self modificationTimestamp];
}
-(id)symbolicLink
{
NSError *error = nil;
NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];
if (error!=nil)
{
[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION];
}
NSString * fileType = [resultDict objectForKey:NSFileType];
return NUMBOOL([fileType isEqualToString:NSFileTypeSymbolicLink]);
}
-(id)writeable
{
// Note: Despite previous incarnations claiming writeable is the proper API,
// writable is the correct spelling.
DEPRECATED_REPLACED_REMOVED(@"Filesystem.FileProxy.writeable",@"1.8.1", @"6.0.0", @"Filesystem.FileProxy.writable");
return [self writable];
}
-(id)writable
{
return NUMBOOL(![[self readonly] boolValue]);
}
#define FILENOOP(name) \
-(id)name\
{\
return NUMBOOL(NO);\
}\
FILENOOP(executable);
FILENOOP(hidden);
FILENOOP(setReadonly:(id)x);
FILENOOP(setExecutable:(id)x);
FILENOOP(setHidden:(id)x);
-(id)getDirectoryListing:(id)args
{
NSError * error=nil;
NSArray * resultArray = [fm contentsOfDirectoryAtPath:path error:&error];
if(error!=nil)
{
//TODO: what should be do?
}
return resultArray;
}
-(id)spaceAvailable:(id)args
{
NSError *error = nil;
NSDictionary * resultDict = [fm attributesOfFileSystemForPath:path error:&error];
if (error!=nil) return NUMBOOL(NO);
return [resultDict objectForKey:NSFileSystemFreeSize];
}
-(NSString *)getProtectionKey:(id)args
{
NSError *error = nil;
NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];
if (error != nil) {
NSLog(@"[ERROR] Error getting protection key: %@", [TiUtils messageFromError:error]);
return nil;
}
return [resultDict objectForKey:NSFileProtectionKey];
}
-(NSNumber *)setProtectionKey:(id)args
{
ENSURE_SINGLE_ARG(args, NSString);
NSError *error = nil;
[fm setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:args, NSFileProtectionKey, nil] ofItemAtPath:path error:&error];
if (error != nil) {
NSLog(@"[ERROR] Error setting protection key: %@", [TiUtils messageFromError:error]);
return NUMBOOL(NO);
}
return NUMBOOL(YES);
}
-(id)createDirectory:(id)args
{
BOOL result = NO;
if (![fm fileExistsAtPath:path])
{
BOOL recurse = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
result = [fm createDirectoryAtPath:path withIntermediateDirectories:recurse attributes:nil error:nil];
}
return NUMBOOL(result);
}
-(id)isFile:(id)unused
{
BOOL isDirectory;
return NUMBOOL([fm fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory);
}
-(id)isDirectory:(id)unused
{
BOOL isDirectory;
return NUMBOOL([fm fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory);
}
-(TiFilesystemFileStreamProxy *) open:(id) args {
NSNumber *mode = nil;
ENSURE_ARG_AT_INDEX(mode, args, 0, NSNumber);
ENSURE_VALUE_RANGE([mode intValue], TI_READ, TI_APPEND);
NSArray *payload = [NSArray arrayWithObjects:[self path], mode, nil];
return [[[TiFilesystemFileStreamProxy alloc] _initWithPageContext:[self executionContext] args:payload] autorelease];
}
-(id)createFile:(id)args
{
BOOL result = NO;
if(![fm fileExistsAtPath:path])
{
BOOL shouldCreate = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
if(shouldCreate)
{
[fm createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
//We don't care if this fails.
}
result = [[NSData data] writeToFile:path options:NSDataWritingFileProtectionComplete | NSDataWritingAtomic error:nil];
}
return NUMBOOL(result);
}
-(id)deleteDirectory:(id)args
{
BOOL result = NO;
BOOL isDirectory = NO;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDirectory];
if (exists && isDirectory)
{
NSError * error = nil;
BOOL shouldDelete = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
if (!shouldDelete)
{
NSArray * remainers = [fm contentsOfDirectoryAtPath:path error:&error];
if(error==nil)
{
if([remainers count]==0)
{
shouldDelete = YES;
}
}
}
if(shouldDelete)
{
result = [fm removeItemAtPath:path error:&error];
}
}
return NUMBOOL(result);
}
-(id)deleteFile:(id)args
{
BOOL result = NO;
BOOL isDirectory = YES;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDirectory];
if(exists && !isDirectory)
{
result = [fm removeItemAtPath:path error:nil];
}
return NUMBOOL(result);
}
-(NSString *)_grabFirstArgumentAsFileName_:(id)args {
NSString * arg = [args objectAtIndex:0];
NSString * file = FILE_TOSTR(arg);
NSURL * fileUrl = [NSURL URLWithString:file];
if([fileUrl isFileURL]){
file = [fileUrl path];
}
NSString * dest = [file stringByStandardizingPath];
return dest;
}
-(id)move:(id)args
{
ENSURE_TYPE(args,NSArray);
NSError * error=nil;
NSString * dest = [self _grabFirstArgumentAsFileName_:args];
if (![dest isAbsolutePath]) {
NSString * subpath = [path stringByDeletingLastPathComponent];
dest = [subpath stringByAppendingPathComponent:dest];
}
BOOL result = [fm moveItemAtPath:path toPath:dest error:&error];
return NUMBOOL(result);
}
-(id)rename:(id)args
{
ENSURE_TYPE(args,NSArray);
NSString * dest = [self _grabFirstArgumentAsFileName_:args];
NSString * ourSubpath = [path stringByDeletingLastPathComponent];
if ([dest isAbsolutePath]) {
NSString * destSubpath = [dest stringByDeletingLastPathComponent];
if (![ourSubpath isEqualToString:destSubpath]) {
return NUMBOOL(NO); // rename is not move
}
}
return [self move:args];
}
-(id)read:(id)args
{
BOOL exists = [fm fileExistsAtPath:path];
if(!exists) return nil;
return [[[TiBlob alloc] initWithFile:path] autorelease];
}
-(id)append:(id)args
{
ENSURE_TYPE(args,NSArray);
id arg = [args objectAtIndex:0];
if([arg isKindOfClass:[TiFile class]]) {
//allow the ability to append files to another file
//e.g. file.append(Ti.Filesystem.getFile('somewhere'));
TiFile *file_arg = (TiFile *) arg;
NSError *err = nil;
NSString *contents = [NSString stringWithContentsOfFile:[file_arg path] encoding:NSUTF8StringEncoding error:&err];
if(contents != nil && err == nil) {
arg = contents;
} else {
NSLog(@"[ERROR] Can't open file (%@) for reading!\n%@", [file_arg path], err);
return NUMBOOL(NO);
}
}
if ([arg isKindOfClass:[TiBlob class]] ||
[arg isKindOfClass:[NSString class]]) {
NSData *data = nil;
if([arg isKindOfClass:[NSString class]]) {
data = [arg dataUsingEncoding:NSUTF8StringEncoding];
} else {
data = [(TiBlob*) arg data];
}
if(data == nil) {
return NUMBOOL(NO);
}
if(![fm fileExistsAtPath:path]) {
//create the file if it doesn't exist already
NSError *writeError = nil;
[data writeToFile:path options:NSDataWritingFileProtectionComplete | NSDataWritingAtomic error:&writeError];
if(writeError != nil) {
NSLog(@"[ERROR] Could not write data to file at path \"%@\"", path);
}
return NUMBOOL(writeError == nil);
}
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:path];
unsigned long long offset = [handle seekToEndOfFile];
[handle writeData:data];
BOOL success = ([handle offsetInFile] - offset) == [data length];
[handle closeFile];
return NUMBOOL(success);
} else {
NSLog(@"[ERROR] Can only append blobs and strings");
}
return NUMBOOL(NO);
}
-(id)write:(id)args
{
ENSURE_TYPE(args,NSArray);
id arg = [args objectAtIndex:0];
//Short-circuit against non-supported types
if(!([arg isKindOfClass:[TiFile class]] || [arg isKindOfClass:[TiBlob class]]
|| [arg isKindOfClass:[NSString class]])) {
return NUMBOOL(NO);
}
if([args count] > 1) {
ENSURE_TYPE([args objectAtIndex:1], NSNumber);
//We have a second argument, is it truthy?
//If yes, we'll hand the args to -append:
NSNumber *append = [args objectAtIndex:1];
if([append boolValue] == YES) {
return [self append:[args subarrayWithRange:NSMakeRange(0, 1)]];
}
}
if ([arg isKindOfClass:[TiBlob class]])
{
TiBlob *blob = (TiBlob*)arg;
return NUMBOOL([blob writeTo:path error:nil]);
}
else if ([arg isKindOfClass:[TiFile class]])
{
TiFile *file = (TiFile*)arg;
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:[file path] toPath:path error:&error];
if (error!=nil)
{
NSLog(@"[ERROR] error writing file: %@ to: %@. Error: %@",[file path],path,error);
}
return NUMBOOL(error==nil);
}
NSString* dataString = [TiUtils stringValue:arg];
NSData* data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err = nil;
[data writeToFile:path options:NSDataWritingFileProtectionComplete | NSDataWritingAtomic error:&err];
if(err != nil) {
NSLog(@"[ERROR] Could not write data to file at path \"%@\" - details: %@", path, err);
}
return NUMBOOL(err == nil);
}
-(id)extension:(id)args
{
return [path pathExtension];
}
-(id)getParent:(id)args
{
return [path stringByDeletingLastPathComponent];
}
-(id)name
{
return [path lastPathComponent];
}
-(id)resolve:(id)args
{
return path;
}
-(id)description
{
return path;
}
+(id)makeTemp:(BOOL)isDirectory
{
NSString * tempDir = NSTemporaryDirectory();
NSError * error=nil;
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:tempDir])
{
[fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:&error];
if(error != nil)
{
//TODO: ?
return nil;
}
}
int timestamp = (int)(time(NULL) & 0xFFFFL);
NSString * resultPath;
do
{
resultPath = [tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%X",timestamp]];
timestamp ++;
} while ([fm fileExistsAtPath:resultPath]);
if(isDirectory)
{
[fm createDirectoryAtPath:resultPath withIntermediateDirectories:NO attributes:nil error:&error];
}
else
{
[[NSData data] writeToFile:resultPath options:NSDataWritingFileProtectionComplete | NSDataWritingAtomic error:&error];
}
if (error != nil)
{
//TODO: ?
return nil;
}
return [[[TiFilesystemFileProxy alloc] initWithFile:resultPath] autorelease];
}
-(NSNumber*)remoteBackup
{
u_int8_t value;
const char* fullPath = [[self path] fileSystemRepresentation];
ssize_t result = getxattr(fullPath, backupAttr, &value, sizeof(value), 0, 0);
if (result == -1) {
// Doesn't matter what errno is set to; this means that we're backing up.
return [NSNumber numberWithBool:YES];
}
// A value of 0 means backup, so:
return [NSNumber numberWithBool:!value];
}
-(void)setRemoteBackup:(NSNumber *)remoteBackup
{
// Value of 1 means nobackup
u_int8_t value = ![TiUtils boolValue:remoteBackup def:YES];
const char* fullPath = [[self path] fileSystemRepresentation];
int result = setxattr(fullPath, backupAttr, &value, sizeof(value), 0, 0);
if (result != 0) {
// Throw an exception with the errno
char* errmsg = strerror(errno);
[self throwException:@"Error setting remote backup flag:"
subreason:[NSString stringWithUTF8String:errmsg]
location:CODELOCATION];
return;
}
}
@end
#endif