Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[expo-document-picker] Prevent crashing when picking folder #8930

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/expo-document-picker/CHANGELOG.md
Expand Up @@ -8,6 +8,8 @@

### 🐛 Bug fixes

- Fixed `getDocumentAsync` crashing when picking a folder on iOS. ([#8930](https://github.com/expo/expo/pull/8930) by [@lukmccall](https://github.com/lukmccall))

## 8.2.1 — 2020-05-29

*This version does not introduce any user-facing changes.*
Expand Down
Expand Up @@ -118,10 +118,8 @@ - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{

NSNumber *fileSize = nil;
NSError *fileSizeError = nil;
[url getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&fileSizeError];
unsigned long long fileSize = [EXDocumentPickerModule getFileSize:[url path] error:&fileSizeError];
if (fileSizeError) {
_reject(@"E_INVALID_FILE", @"Unable to get file size", fileSizeError);
_resolve = nil;
Expand Down Expand Up @@ -151,7 +149,7 @@ - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocum
@"type": @"success",
@"uri": [newUrl absoluteString],
@"name": [url lastPathComponent],
@"size": fileSize,
@"size": @(fileSize),
});
_resolve = nil;
_reject = nil;
Expand All @@ -164,4 +162,34 @@ - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
_reject = nil;
}

+ (unsigned long long)getFileSize:(NSString *)path error:(NSError **)error
{
NSDictionary<NSFileAttributeKey, id> *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:error];
if (*error) {
return 0;
}

if (fileAttributes.fileType != NSFileTypeDirectory) {
return fileAttributes.fileSize;
}

// The path is pointing to the folder
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:error];
if (*error) {
return 0;
}

NSEnumerator *contentsEnumurator = [contents objectEnumerator];
NSString *file;
unsigned long long folderSize = 0;
while (file = [contentsEnumurator nextObject]) {
folderSize += [EXDocumentPickerModule getFileSize:[path stringByAppendingPathComponent:file] error:error];
if (*error) {
return 0;
}
}

return folderSize;
}

@end