-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
FileUtils.js
173 lines (160 loc) · 4.9 KB
/
FileUtils.js
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
import {Alert, Linking, Platform} from 'react-native';
import CONST from '../../CONST';
import * as Localize from '../Localize';
import DateUtils from '../DateUtils';
/**
* Show alert on successful attachment download
*/
function showSuccessAlert() {
Alert.alert(
Localize.translateLocal('fileDownload.success.title'),
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(),
},
]);
}
/**
* Generate a random file name with timestamp and file extension
* @param {String} url
* @returns {String}
*/
function getAttachmentName(url) {
if (!url) {
return '';
}
return `${DateUtils.getDBTime()}.${url.split(/[#?]/)[0].split('.').pop().trim()}`;
}
/**
* @param {String} fileName
* @returns {Boolean}
*/
function isImage(fileName) {
return CONST.FILE_TYPE_REGEX.IMAGE.test(fileName);
}
/**
* @param {String} fileName
* @returns {Boolean}
*/
function isVideo(fileName) {
return CONST.FILE_TYPE_REGEX.VIDEO.test(fileName);
}
/**
* Returns file type based on the uri
* @param {String} fileUrl
* @returns {String}
*/
function getFileType(fileUrl) {
if (!fileUrl) {
return;
}
const fileName = fileUrl.split('/').pop().split('?')[0].split('#')[0];
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
*
* @param {String} fullFileName
* @returns {Object}
*/
function splitExtensionFromFileName(fullFileName) {
const fileName = fullFileName.trim();
const splitFileName = fileName.split('.');
const fileExtension = splitFileName.length > 1 ? splitFileName.pop() : '';
return {fileName: splitFileName.join('.'), fileExtension};
}
/**
* Returns the filename replacing special characters with underscore
*
* @param {String} fileName
* @returns {String}
*/
function cleanFileName(fileName) {
return fileName.replace(/[^a-zA-Z0-9\-._]/g, '_');
}
/**
* @param {String} fileName
* @returns {String}
*/
function appendTimeToFileName(fileName) {
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 {String} path - the blob url of the locally uplodaded file
* @param {String} fileName
* @returns {Promise}
*/
const readFileAsync = (path, fileName) =>
new Promise((resolve) => {
if (!path) {
resolve();
}
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);
}
return res.blob();
})
.then((blob) => {
const file = new File([blob], cleanFileName(fileName));
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;
resolve(file);
})
.catch((e) => {
console.debug('[FileUtils] Could not read uploaded file', e);
resolve();
});
});
export {showGeneralErrorAlert, showSuccessAlert, showPermissionErrorAlert, splitExtensionFromFileName, getAttachmentName, getFileType, cleanFileName, appendTimeToFileName, readFileAsync};