-
Notifications
You must be signed in to change notification settings - Fork 3k
/
FileUtils.ts
346 lines (310 loc) · 12.3 KB
/
FileUtils.ts
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
import {Str} from 'expensify-common';
import {Alert, Linking, Platform} from 'react-native';
import ImageSize from 'react-native-image-size';
import type {FileObject} from '@components/AttachmentModal';
import DateUtils from '@libs/DateUtils';
import * as Localize from '@libs/Localize';
import Log from '@libs/Log';
import saveLastRoute from '@libs/saveLastRoute';
import CONST from '@src/CONST';
import getImageManipulator from './getImageManipulator';
import getImageResolution from './getImageResolution';
import type {ReadFileAsync, SplitExtensionFromFileName} from './types';
/**
* Show alert on successful attachment download
* @param successMessage
*/
function showSuccessAlert(successMessage?: string) {
Alert.alert(
Localize.translateLocal('fileDownload.success.title'),
// successMessage can be an empty string and we want to default to `Localize.translateLocal('fileDownload.success.message')`
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
successMessage || Localize.translateLocal('fileDownload.success.message'),
[
{
text: Localize.translateLocal('common.ok'),
style: 'cancel',
},
],
{cancelable: false},
);
}
/**
* Show alert on attachment download error
*/
function showGeneralErrorAlert() {
Alert.alert(Localize.translateLocal('fileDownload.generalError.title'), Localize.translateLocal('fileDownload.generalError.message'), [
{
text: Localize.translateLocal('common.cancel'),
style: 'cancel',
},
]);
}
/**
* Show alert on attachment download permissions error
*/
function showPermissionErrorAlert() {
Alert.alert(Localize.translateLocal('fileDownload.permissionError.title'), Localize.translateLocal('fileDownload.permissionError.message'), [
{
text: Localize.translateLocal('common.cancel'),
style: 'cancel',
},
{
text: Localize.translateLocal('common.settings'),
onPress: () => {
Linking.openSettings();
},
},
]);
}
/**
* Inform the users when they need to grant camera access and guide them to settings
*/
function showCameraPermissionsAlert() {
Alert.alert(
Localize.translateLocal('attachmentPicker.cameraPermissionRequired'),
Localize.translateLocal('attachmentPicker.expensifyDoesntHaveAccessToCamera'),
[
{
text: Localize.translateLocal('common.cancel'),
style: 'cancel',
},
{
text: Localize.translateLocal('common.settings'),
onPress: () => {
Linking.openSettings();
// In the case of ios, the App reloads when we update camera permission from settings
// we are saving last route so we can navigate to it after app reload
saveLastRoute();
},
},
],
{cancelable: false},
);
}
/**
* Extracts a filename from a given URL and sanitizes it for file system usage.
*
* This function takes a URL as input and performs the following operations:
* 1. Extracts the last segment of the URL.
* 2. Decodes the extracted segment from URL encoding to a plain string for better readability.
* 3. Replaces any characters in the decoded string that are illegal in file names
* with underscores.
*/
function getFileName(url: string): string {
const fileName = url.split('/').pop()?.split('?')[0].split('#')[0] ?? '';
if (!fileName) {
Log.warn('[FileUtils] Could not get attachment name', {url});
}
return decodeURIComponent(fileName).replace(CONST.REGEX.ILLEGAL_FILENAME_CHARACTERS, '_');
}
function isImage(fileName: string): boolean {
return CONST.FILE_TYPE_REGEX.IMAGE.test(fileName);
}
function isVideo(fileName: string): boolean {
return CONST.FILE_TYPE_REGEX.VIDEO.test(fileName);
}
/**
* Returns file type based on the uri
*/
function getFileType(fileUrl: string): string | undefined {
if (!fileUrl) {
return;
}
const fileName = getFileName(fileUrl);
if (!fileName) {
return;
}
if (isImage(fileName)) {
return CONST.ATTACHMENT_FILE_TYPE.IMAGE;
}
if (isVideo(fileName)) {
return CONST.ATTACHMENT_FILE_TYPE.VIDEO;
}
return CONST.ATTACHMENT_FILE_TYPE.FILE;
}
/**
* Returns the filename split into fileName and fileExtension
*/
const splitExtensionFromFileName: SplitExtensionFromFileName = (fullFileName) => {
const fileName = fullFileName.trim();
const splitFileName = fileName.split('.');
const fileExtension = splitFileName.length > 1 ? splitFileName.pop() : '';
return {fileName: splitFileName.join('.'), fileExtension: fileExtension ?? ''};
};
/**
* Returns the filename replacing special characters with underscore
*/
function cleanFileName(fileName: string): string {
return fileName.replace(/[^a-zA-Z0-9\-._]/g, '_');
}
function appendTimeToFileName(fileName: string): string {
const file = splitExtensionFromFileName(fileName);
let newFileName = `${file.fileName}-${DateUtils.getDBTime()}`;
// Replace illegal characters before trying to download the attachment.
newFileName = newFileName.replace(CONST.REGEX.ILLEGAL_FILENAME_CHARACTERS, '_');
if (file.fileExtension) {
newFileName += `.${file.fileExtension}`;
}
return newFileName;
}
/**
* Reads a locally uploaded file
* @param path - the blob url of the locally uploaded file
* @param fileName - name of the file to read
*/
const readFileAsync: ReadFileAsync = (path, fileName, onSuccess, onFailure = () => {}, fileType = '') =>
new Promise((resolve) => {
if (!path) {
resolve();
onFailure('[FileUtils] Path not specified');
return;
}
fetch(path)
.then((res) => {
// For some reason, fetch is "Unable to read uploaded file"
// on Android even though the blob is returned, so we'll ignore
// in that case
if (!res.ok && Platform.OS !== 'android') {
throw Error(res.statusText);
}
res.blob()
.then((blob) => {
// On Android devices, fetching blob for a file with name containing spaces fails to retrieve the type of file.
// In this case, let us fallback on fileType provided by the caller of this function.
const file = new File([blob], cleanFileName(fileName), {type: blob.type || fileType});
file.source = path;
// For some reason, the File object on iOS does not have a uri property
// so images aren't uploaded correctly to the backend
file.uri = path;
onSuccess(file);
resolve(file);
})
.catch((e) => {
console.debug('[FileUtils] Could not read uploaded file', e);
onFailure(e);
resolve();
});
})
.catch((e) => {
console.debug('[FileUtils] Could not read uploaded file', e);
onFailure(e);
resolve();
});
});
/**
* Converts a base64 encoded image string to a File instance.
* Adds a `uri` property to the File instance for accessing the blob as a URI.
*
* @param base64 - The base64 encoded image string.
* @param filename - Desired filename for the File instance.
* @returns The File instance created from the base64 string with an additional `uri` property.
*
* @example
* const base64Image = "data:image/png;base64,..."; // your base64 encoded image
* const imageFile = base64ToFile(base64Image, "example.png");
* console.log(imageFile.uri); // Blob URI
*/
function base64ToFile(base64: string, filename: string): File {
// Decode the base64 string
const byteString = atob(base64.split(',')[1]);
// Get the mime type from the base64 string
const mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
// Convert byte string to Uint8Array
const arrayBuffer = new ArrayBuffer(byteString.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i);
}
// Create a blob from the Uint8Array
const blob = new Blob([uint8Array], {type: mimeString});
// Create a File instance from the Blob
const file = new File([blob], filename, {type: mimeString, lastModified: Date.now()});
// Add a uri property to the File instance for accessing the blob as a URI
file.uri = URL.createObjectURL(blob);
return file;
}
function validateImageForCorruption(file: FileObject): Promise<{width: number; height: number} | void> {
if (!Str.isImage(file.name ?? '') || !file.uri) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
ImageSize.getSize(file.uri ?? '')
.then(() => resolve())
.catch(() => reject(new Error('Error reading file: The file is corrupted')));
});
}
/** Verify file format based on the magic bytes of the file - some formats might be identified by multiple signatures */
function verifyFileFormat({fileUri, formatSignatures}: {fileUri: string; formatSignatures: readonly string[]}) {
return fetch(fileUri)
.then((file) => file.arrayBuffer())
.then((arrayBuffer) => {
const uintArray = new Uint8Array(arrayBuffer, 4, 12);
const hexString = Array.from(uintArray)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
return hexString;
})
.then((hexSignature) => {
return formatSignatures.some((signature) => hexSignature.startsWith(signature));
});
}
function isLocalFile(receiptUri?: string | number): boolean {
if (!receiptUri) {
return false;
}
return typeof receiptUri === 'number' || receiptUri?.startsWith('blob:') || receiptUri?.startsWith('file:') || receiptUri?.startsWith('/');
}
function getFileResolution(targetFile: FileObject | undefined): Promise<{width: number; height: number} | null> {
if (!targetFile) {
return Promise.resolve(null);
}
// If the file already has width and height, return them directly
if ('width' in targetFile && 'height' in targetFile) {
return Promise.resolve({width: targetFile.width ?? 0, height: targetFile.height ?? 0});
}
// Otherwise, attempt to get the image resolution
return getImageResolution(targetFile)
.then(({width, height}) => ({width, height}))
.catch((error: Error) => {
Log.hmmm('Failed to get image resolution:', error);
return null;
});
}
function isHighResolutionImage(resolution: {width: number; height: number} | null): boolean {
return resolution !== null && (resolution.width > CONST.IMAGE_HIGH_RESOLUTION_THRESHOLD || resolution.height > CONST.IMAGE_HIGH_RESOLUTION_THRESHOLD);
}
const getImageDimensionsAfterResize = (file: FileObject) =>
ImageSize.getSize(file.uri ?? '').then(({width, height}) => {
const scaleFactor = CONST.MAX_IMAGE_DIMENSION / (width < height ? height : width);
const newWidth = Math.max(1, width * scaleFactor);
const newHeight = Math.max(1, height * scaleFactor);
return {width: newWidth, height: newHeight};
});
const resizeImageIfNeeded = (file: FileObject) => {
if (!file || !Str.isImage(file.name ?? '') || (file?.size ?? 0) <= CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
return Promise.resolve(file);
}
return getImageDimensionsAfterResize(file).then(({width, height}) => getImageManipulator({fileUri: file.uri ?? '', width, height, fileName: file.name ?? '', type: file.type}));
};
export {
showGeneralErrorAlert,
showSuccessAlert,
showPermissionErrorAlert,
showCameraPermissionsAlert,
splitExtensionFromFileName,
getFileName,
getFileType,
cleanFileName,
appendTimeToFileName,
readFileAsync,
base64ToFile,
isLocalFile,
validateImageForCorruption,
isImage,
getFileResolution,
isHighResolutionImage,
verifyFileFormat,
getImageDimensionsAfterResize,
resizeImageIfNeeded,
};