-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfilemanager.dart
315 lines (278 loc) · 10.2 KB
/
filemanager.dart
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
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:filesize/filesize.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_archive/flutter_archive.dart';
import 'package:path/path.dart';
import 'package:oktoast/oktoast.dart';
import 'cachemanager.dart';
import 'server.dart';
import 'network.dart';
import 'statemanager.dart';
class FileManager {
static String currentFile = '';
static String currentFullPath = '';
static String currentPath = '';
static int currentLength = 0;
static List archivedFiles = [];
static String archivedLast = '';
static bool fileImported = false;
static bool fileImportPending = false;
static bool multipleFiles = false;
static bool allowWatcher = false;
static bool lockWatcher = false;
static bool directAccessMode = false;
final int directAccessModeNoMESMaxAPI = 29;
final String directAccessPath = '/storage/emulated/0';
final bool allowMultipleFiles = (Platform.isAndroid);
/*
!!! This determines if DAM is allowed on Android 11 or later in the build !!!
If `true`, remove `MANAGE_EXTERNAL_STORAGE` from `AndroidManifest.xml`
If `false`, add `<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>` into `AndroidManifest.xml`
!!! By default when it comes to Git, this should be set to `false` and with the MES permission in place !!!
*/
final bool isPlayStoreFriendly = false;
Map<String, dynamic> readInfo() {
return {
'name': currentFile,
'path': currentFullPath,
'pathpart': currentPath,
'length': currentLength,
'archived': archivedFiles,
};
}
Future<String> filePickerPath() async {
String pickerDir =
FileManager.directAccessMode
? directAccessPath
: (await getTemporaryDirectory()).path + '/file_picker';
return pickerDir;
}
bool directModeDetect(String path) {
bool result = false;
if (path.startsWith(directAccessPath)) {
result = true;
}
return result;
}
String fileSizeHuman(int length, BuildContext context) {
String _sizeHuman = filesize(length, 2);
_sizeHuman = _sizeHuman.replaceAll(
'TB',
AppLocalizations.of(context)!.page_imported_sizesymbol_tb,
);
_sizeHuman = _sizeHuman.replaceAll(
'GB',
AppLocalizations.of(context)!.page_imported_sizesymbol_gb,
);
_sizeHuman = _sizeHuman.replaceAll(
'MB',
AppLocalizations.of(context)!.page_imported_sizesymbol_mb,
);
_sizeHuman = _sizeHuman.replaceAll(
'KB',
AppLocalizations.of(context)!.page_imported_sizesymbol_kb,
);
_sizeHuman = _sizeHuman.replaceAll(
' B',
' ' + AppLocalizations.of(context)!.page_imported_sizesymbol_b,
);
_sizeHuman = _sizeHuman.replaceAll(
'.',
AppLocalizations.of(context)!.page_imported_decimalseparator,
);
return _sizeHuman;
}
Future selectFile(
BuildContext context, [
Map<String, dynamic> fileSelection = const {},
]) async {
FileManager.fileImportPending = true;
Map<String, dynamic> result = {'files': {}};
String pickerDir = await FileManager().filePickerPath();
Directory sourceDir = Directory(pickerDir);
// Ensure file picker directory exists first
bool dirExists = await sourceDir.exists();
if (!dirExists) {
if (directAccessMode) {
showToast(AppLocalizations.of(context)!.dam_path_not_found);
return;
}
Directory sourceDirCreated = await sourceDir.create();
sourceDir = sourceDirCreated;
}
if (!directAccessMode && fileSelection.length == 0) {
// Default file picker
FilePickerResult? resultFilePicker = await FilePicker.platform.pickFiles(
allowMultiple: allowMultipleFiles,
);
if (resultFilePicker != null) {
// File picker handler
for (int i = 0; i < resultFilePicker.files.length; i++) {
if (resultFilePicker.files[i].path == null) continue;
File fileToMove = File(resultFilePicker.files[i].path ?? '');
String fileToMoveName = resultFilePicker.files[i].name;
String fileToMoveNewPath =
await filePickerPath() + '/' + fileToMoveName;
// Check if selection has multiple files of the same name
for (int j = 0; j < result['files'].length; j++) {
if (result['files'][j]['name'] == fileToMoveName) {
fileToMoveName =
Server().tokenGenerator('0123456789abcdef', 6) +
'_' +
fileToMoveName;
fileToMoveNewPath = await filePickerPath() + '/' + fileToMoveName;
}
}
await fileToMove.rename(fileToMoveNewPath);
result['files'].addAll({
i: {
'name': fileToMoveName,
'path': fileToMoveNewPath,
'size': resultFilePicker.files[i].size,
},
});
}
}
} else if (fileSelection.length > 0 &&
directModeDetect(fileSelection['files'][0]['path'])) {
// Direct access mode
final File selectedFile = File(fileSelection['files'][0]['path']);
if (selectedFile.existsSync()) {
fileSelection['files'][0]['size'] = selectedFile.lengthSync();
} else {
// File was selected but no longer exists
pageTypeCurrent = PageType.fileremoved;
await Server().shutdownServer(context);
return;
}
result = fileSelection;
} else {
// Share sheet handler
// Move files selected via share sheet into usual directory for archiving
for (int i = 0; i < fileSelection['files'].length; i++) {
File fileRename = File(fileSelection['files'][i]['path']);
File fileRenamed = await fileRename.rename(
pickerDir + '/' + fileSelection['files'][i]['name'],
);
fileSelection['files'][i]['path'] = fileRenamed.path;
}
result = fileSelection;
}
if (result.containsKey('files') && result['files'].length == 0) {
FileManager.fileImportPending = false;
return;
}
await Network().internalIP();
if (Network.interfaceList.isEmpty) {
pageTypeCurrent = PageType.noconnection;
await Server().shutdownServer(context);
return;
}
// Only perform file processing if at least one file is selected
if (result.containsKey('files') && result['files'].length > 0) {
FileManager.allowWatcher = false;
// Clear out existing watcher subscription
if (!FileManager.allowWatcher) {
if (StateManager.importWatchdog != null &&
StateManager.importWatchdog?.cancel != null) {
await StateManager.importWatchdog?.cancel();
}
}
multipleFiles = (result['files'].length > 1);
List<String> cacheExceptionList = [];
archivedFiles = [];
for (int i = 0; i < result['files'].length; i++) {
archivedFiles.add({
'file': result['files'][i]['name'],
'size': result['files'][i]['size'],
});
cacheExceptionList.add(result['files'][i]['path'] ?? '');
}
// Empty last archive entry if current selection does not contain multiple files
if (!multipleFiles) archivedLast = '';
// Exclude previously created archive (if any) initially
if (archivedLast.isEmpty) cacheExceptionList.add(archivedLast);
// Cache handling
await CacheManager().deleteCache(context, cacheExceptionList, true);
String _currentFile = '';
String _currentFullPath = '';
String _currentPath = '';
int _currentLength = 0;
if (multipleFiles) {
// Prepare archive name
String archiveName =
Server().tokenGenerator('1234567890ABCDEF', 8) + '.zip';
String fullPickerPath = await filePickerPath();
String fullArchivePath = fullPickerPath + '/' + archiveName;
List<File> files = [];
for (int i = 0; i < result['files'].length; i++) {
await File(
result['files'][i]['path'] ??
fullPickerPath + '/' + result['files'][i]['name'],
).exists().then((_) async {
files.add(
File(
result['files'][i]['path'] ??
fullPickerPath + '/' + result['files'][i]['name'],
),
);
});
}
final zipFile = File(fullArchivePath);
try {
await ZipFile.createFromFiles(
sourceDir: sourceDir,
files: files,
zipFile: zipFile,
).then(
(_) async => {
for (int i = 0; i < result['files'].length; i++)
{
await File(
result['files'][i]['path'] ??
fullPickerPath + '/' + result['files'][i]['name'],
).delete(),
},
},
);
} catch (e) {
showToast(
AppLocalizations.of(context)!.page_imported_archive_failed +
e.toString(),
);
return;
}
// Get length of created archive
int archiveSize = await File(fullArchivePath).length();
_currentFile = archiveName;
_currentFullPath = fullArchivePath;
_currentPath = fullPickerPath;
_currentLength = archiveSize;
archivedLast = _currentFullPath;
} else {
_currentFile = result['files'][0]['name'];
_currentFullPath = result['files'][0]['path'] ?? '';
_currentPath = dirname(result['files'][0]['path'] ?? '');
_currentLength = result['files'][0]['size'];
archivedFiles = [];
archivedLast = '';
}
// Set file information
FileManager.currentFile = _currentFile;
FileManager.currentFullPath = _currentFullPath;
FileManager.currentPath = _currentPath;
FileManager.currentLength = _currentLength;
FileManager.fileImported = true;
FileManager.allowWatcher = true;
FileManager.lockWatcher = false;
StateManager.fileTampered = PageType.fileremoved;
pageTypeCurrent = PageType.imported;
// Initiate server
await Network().fetchInterfaces(context);
}
FileManager.fileImportPending = false;
}
}