-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimages.dart
More file actions
725 lines (651 loc) · 19.8 KB
/
images.dart
File metadata and controls
725 lines (651 loc) · 19.8 KB
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:extended_text/extended_text.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:gal/gal.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:piwigo_ng/domain/models/album_model.dart';
import 'package:piwigo_ng/domain/models/image_model.dart';
import 'package:piwigo_ng/data/services/api/api_error.dart';
import 'package:piwigo_ng/data/services/api/upload.dart';
import 'package:piwigo_ng/data/services/local/chunked_uploader.dart';
import 'package:piwigo_ng/data/services/local/notification_service.dart';
import 'package:piwigo_ng/data/services/local/preferences_service.dart';
import 'package:piwigo_ng/utils/localizations.dart';
import 'package:piwigo_ng/utils/settings.dart';
import 'package:share_plus/share_plus.dart';
import 'albums.dart';
import 'api_client.dart';
Future<ApiResponse<ImageModel>> getImage(
int imageId,
) async {
Map<String, dynamic> queries = {
'format': 'json',
'method': 'pwg.images.getInfo',
'image_id': imageId,
};
try {
Response response = await ApiClient.get(queryParameters: queries);
if (response.statusCode == 200) {
var data = json.decode(response.data);
if (data['stat'] == 'fail') {
return ApiResponse(error: ApiErrors.error);
}
var jsonImage = data['result'];
ImageModel image = ImageModel.fromJson(jsonImage);
return ApiResponse<ImageModel>(data: image);
}
} on DioException catch (e) {
debugPrint('Fetch images: ${e.message}');
} on Error catch (e) {
debugPrint('Fetch images: $e\n${e.stackTrace}');
}
return ApiResponse(error: ApiErrors.error);
}
Future<ApiResponse<List<ImageModel>>> fetchImages(
int albumID, [
int page = 0,
]) async {
Map<String, dynamic> queries = {
'format': 'json',
'method': 'pwg.categories.getImages',
'cat_id': albumID,
'order': Preferences.getImageSort.value,
'per_page': Settings.defaultElementPerPage,
'page': page,
};
try {
Response response = await ApiClient.get(queryParameters: queries);
if (response.statusCode == 200) {
var jsonImages = tryParseJson(response.data)['result']['images'];
List<ImageModel> images = List<ImageModel>.from(
jsonImages.map((image) => ImageModel.fromJson(image)),
);
return ApiResponse<List<ImageModel>>(data: images);
}
} on DioException catch (e) {
debugPrint('Fetch images: ${e.message}');
} catch (e) {
debugPrint('Fetch images: $e');
}
return ApiResponse(error: ApiErrors.fetchImagesError);
}
Future<ApiResponse<Map>> searchImages(
String searchQuery, [
int page = 0,
]) async {
Map<String, dynamic> query = {
'format': 'json',
'method': 'pwg.images.search',
'query': searchQuery,
'order': Preferences.getImageSort.value,
'per_page': Settings.defaultElementPerPage,
'page': page,
};
try {
Response response = await ApiClient.get(queryParameters: query);
if (response.statusCode == 200) {
final Map<String, dynamic> result = json.decode(response.data);
if (result['err'] == 1002) {
return ApiResponse<Map>(data: {
'total_count': 0,
'images': [],
});
}
final jsonImages = result['result']['images'];
List<ImageModel> images = List<ImageModel>.from(
jsonImages.map((image) => ImageModel.fromJson(image)),
);
return ApiResponse<Map>(data: {
'total_count': result['result']['paging']['total_count'],
'images': images,
});
}
} on DioException catch (e) {
debugPrint('Search images: ${e.message}');
} on Error catch (e) {
debugPrint('Search images: ${e.stackTrace}');
}
return ApiResponse(error: ApiErrors.searchImagesError);
}
Future<ApiResponse<Map>> fetchFavorites([
int page = 0,
]) async {
Map<String, dynamic> query = {
'format': 'json',
'method': 'pwg.users.favorites.getList',
'order': Preferences.getImageSort.value,
'per_page': Settings.defaultElementPerPage,
'page': page,
};
try {
Response response = await ApiClient.get(queryParameters: query);
if (response.statusCode == 200) {
final Map<String, dynamic> result = json.decode(response.data);
if (result['stat'] == 'fail') {
return ApiResponse<Map>(data: {
'total_count': 0,
'images': [],
});
}
final jsonImages = result['result']['images'];
List<ImageModel> images = List<ImageModel>.from(
jsonImages.map((image) {
image['is_favorite'] = true;
return ImageModel.fromJson(image);
}),
);
return ApiResponse<Map>(data: {
'total_count': result['result']['paging']['count'],
'images': images,
});
}
} on DioException catch (e) {
debugPrint('Fetch favorites: ${e.message}');
} on Error catch (e) {
debugPrint('Fetch favorites: ${e.stackTrace}');
}
return ApiResponse(error: ApiErrors.error);
}
Future<ApiResponse<Map>> fetchTagImages(int tagID, [int page = 0]) async {
Map<String, String> query = {
"format": "json",
"method": "pwg.tags.getImages",
"tag_id": tagID.toString(),
"per_page": "100",
"page": page.toString(),
};
try {
Response response = await ApiClient.get(queryParameters: query);
if (response.statusCode == 200) {
final Map<String, dynamic> result = json.decode(response.data);
if (result['stat'] == 'fail') {
return ApiResponse<Map>(data: {
'total_count': 0,
'images': [],
});
}
final jsonImages = result['result']['images'];
List<ImageModel> images = List<ImageModel>.from(
jsonImages.map((image) {
image['tags'] = null;
return ImageModel.fromJson(image);
}),
);
print(result['result']['paging']);
return ApiResponse<Map>(data: {
'total_count': result['result']['paging']['total_count'],
'images': images,
});
}
} on DioException catch (e) {
debugPrint('Fetch tag images: ${e.message}');
} on Error catch (e) {
debugPrint('Fetch tag images: ${e.stackTrace}');
}
return ApiResponse(error: ApiErrors.error);
}
Future<String?> pickDirectoryPath() async {
return await FilePicker.platform.getDirectoryPath();
}
Future<void> _showDownloadNotification({
bool success = true,
String? payload,
}) async {
if (!Preferences.getDownloadNotification) return;
final android = AndroidNotificationDetails(
'piwigo-ng-download',
'Piwigo NG Download',
channelDescription: 'piwigo_ng',
priority: Priority.defaultPriority,
importance: Importance.defaultImportance,
);
await showLocalNotification(
id: 0,
title: success ? appStrings.downloadImageSuccess_title : appStrings.downloadImageFail_title,
body: success ? appStrings.downloadImageSuccess_message : appStrings.deleteImageFail_message,
details: android,
payload: payload,
);
}
Future<bool> share(
List<ImageModel> images,
) async {
List<XFile>? filesPath = await downloadImages(
images,
showNotification: false,
cached: true,
);
print(filesPath);
if (filesPath == null || filesPath.isEmpty) return false;
try {
SharePlus.instance.share(ShareParams(files: filesPath));
return true;
} catch (e) {
debugPrint("$e");
}
return false;
}
Future<List<XFile>?> downloadImages(
List<ImageModel> images, {
bool showNotification = true,
bool cached = false,
}) async {
String? dirPath = (await getTemporaryDirectory()).path;
if (!cached) {
dirPath = Preferences.getDownloadDestination ?? await pickDirectoryPath();
}
if (dirPath == null) return null;
final List<XFile> files = [];
await Future.forEach(images, (ImageModel image) async {
XFile? file = await downloadImage(dirPath!, image);
if (file != null) {
files.add(file);
}
});
if (showNotification && Preferences.getDownloadNotification) {
if (files.isNotEmpty) {
await _showDownloadNotification(
success: true,
payload: files.length == 1 ? files.single.path : '$dirPath\\',
);
} else {
await _showDownloadNotification(success: false);
}
}
return files;
}
Future<XFile?> downloadImage(
String dirPath,
ImageModel image,
) async {
String localPath = path.join(dirPath, image.file);
if (!await askMediaPermission()) return null;
try {
await ApiClient.download(
path: 'action.php',
queryParameters: {
'id': image.id,
'part': 'e',
},
outputPath: localPath,
);
await Gal.putImage(localPath);
return XFile(localPath);
} on DioException catch (e) {
debugPrint("Download images: ${e.message}");
} on Error catch (e) {
debugPrint("Download images: ${e.stackTrace}");
}
return null;
}
Future<int> deleteImages(
List<ImageModel> imageList,
AlbumModel? album,
DeleteAlbumModes mode,
) async {
int nbSuccess = 0;
for (ImageModel image in imageList) {
bool response = false;
if (album == null) {
response = await deleteImage(image);
} else {
switch (mode) {
case DeleteAlbumModes.noDelete:
response = await removeImage(image, album.id);
break;
default:
response = await deleteImage(image);
break;
}
}
if (response == true) {
nbSuccess++;
}
}
return nbSuccess;
}
Future<bool> deleteImage(
ImageModel image,
) async {
Map<String, String> queries = {
'format': 'json',
'method': 'pwg.images.delete',
};
FormData formData = FormData.fromMap({
'image_id': image.id,
'pwg_token': appPreferences.getString(Preferences.tokenKey),
});
try {
Response response = await ApiClient.post(
data: formData,
queryParameters: queries,
);
if (response.statusCode == 200) {
return true;
}
} on DioException catch (e) {
debugPrint('Delete images: ${e.message}');
} on Error catch (e) {
debugPrint('Delete images: ${e.stackTrace}');
}
return false;
}
Future<int> removeImages(
List<ImageModel> images,
int albumId,
) async {
int nbSuccess = 0;
for (ImageModel image in images) {
bool response = await removeImage(image, albumId);
if (response == true) {
nbSuccess++;
}
}
return nbSuccess;
}
Future<bool> removeImage(
ImageModel image,
int albumId,
) async {
final List<int> albums = image.categories.map<int>((album) => album['id']).toList();
albums.removeWhere((album) => album == albumId);
if (albums.isEmpty) {
deleteImage(image);
}
final Map<String, dynamic> queries = {
'format': 'json',
'method': 'pwg.images.setInfo',
};
final FormData formData = FormData.fromMap({
'image_id': image.id,
'categories': albums,
'multiple_value_mode': 'replace',
});
try {
Response response = await ApiClient.post(data: formData, queryParameters: queries);
if (response.statusCode == 200) {
return true;
}
} on DioException catch (e) {
debugPrint('Remove images: ${e.message}');
} on Error catch (e) {
debugPrint('Remove images: ${e.stackTrace}');
}
return false;
}
Future<int> moveImages(
List<ImageModel> images,
int oldAlbumId,
int newAlbumId,
) async {
int nbMoved = 0;
for (var image in images) {
bool response = await moveImage(image, oldAlbumId, newAlbumId);
if (response) {
nbMoved++;
}
}
return nbMoved;
}
Future<bool> moveImage(
ImageModel image,
int oldAlbumId,
int newAlbumId,
) async {
final List<int> albums = image.categories.map<int>((album) => album['id']).toList();
albums.removeWhere((id) => id == oldAlbumId);
albums.add(newAlbumId);
Map<String, String> queries = {
'format': 'json',
'method': 'pwg.images.setInfo',
};
FormData formData = FormData.fromMap({
'image_id': image.id,
'categories': albums,
'multiple_value_mode': 'replace',
});
try {
Response response = await ApiClient.post(data: formData, queryParameters: queries);
if (response.statusCode == 200) {
return true;
}
} on DioException catch (e) {
debugPrint('Move images: ${e.message}');
} on Error catch (e) {
debugPrint('Move images: ${e.stackTrace}');
}
return false;
}
Future<int> assignImages(
List<ImageModel> images,
int albumId,
) async {
int nbAssigned = 0;
for (ImageModel image in images) {
final List<int> categories = image.categories.map<int>((album) => album['id']).toList();
categories.add(albumId);
bool response = await assignImage(image.id, categories);
if (response == true) {
nbAssigned++;
}
}
return nbAssigned;
}
Future<bool> assignImage(
int imageId,
List<int> categories,
) async {
final Map<String, dynamic> queries = {
'format': 'json',
'method': 'pwg.images.setInfo',
};
final FormData formData = FormData.fromMap({
'image_id': imageId,
'categories': categories,
'multiple_value_mode': 'append',
});
try {
Response response = await ApiClient.post(data: formData, queryParameters: queries);
if (response.statusCode == 200) {
return true;
}
} on DioException catch (e) {
debugPrint('Assign images: ${e.message}');
} on Error catch (e) {
debugPrint('Assign images: ${e.stackTrace}');
}
return false;
}
Future<int> editImages(
List<ImageModel> images, [
Map<String, dynamic> info = const {},
]) async {
int nbEdited = 0;
for (ImageModel image in images) {
bool response = await editImage(
image,
info: info,
single: images.length == 1,
);
if (response == true) {
nbEdited++;
}
}
return nbEdited;
}
Future<bool> editImage(
ImageModel image, {
Map<String, dynamic> info = const {},
bool single = true,
}) async {
final Map<String, String> queries = {
'format': 'json',
'method': 'pwg.images.setInfo',
};
Map<String, dynamic> form = {
'image_id': image.id,
'single_value_mode': 'replace',
'multiple_value_mode': single ? 'replace' : 'append',
};
if (info['title'] != null) form['name'] = info['title'];
if (info['description'] != null) form['comment'] = info['description'];
if (info['author'] != null) form['author'] = info['author'];
if (info['level'] != null) form['level'] = info['level'];
if (info['tags'] != null) form['tag_ids'] = info['tags'];
final FormData formData = FormData.fromMap(form);
print(formData.fields);
try {
Response response = await ApiClient.post(
data: formData,
queryParameters: queries,
);
if (response.statusCode == 200) {
return true;
}
} on DioException catch (e) {
debugPrint('Edit images: ${e.message}');
} on Error catch (e) {
debugPrint('Edit images: ${e.stackTrace}');
}
return false;
}
/// Return a list of files that are not in the server
Future<List<File>> checkImagesNotExist(
List<File> files, {
bool returnExistFiles = false,
}) async {
Map<String, File> md5sumList = {};
for (File file in files) {
String md5sum = await ChunkedUploader.generateMd5(file.openRead());
md5sumList[md5sum] = file;
}
final Map<String, String> queries = {
'format': 'json',
'method': 'pwg.images.exist',
'md5sum_list': md5sumList.keys.join(','),
};
try {
Response response = await ApiClient.get(
queryParameters: queries,
);
Map<String, dynamic> data = json.decode(response.data);
if (data['stat'] == 'fail') return [];
print(data['result']);
Map<String, dynamic> existResult = data['result'];
if (returnExistFiles) {
existResult.removeWhere((key, value) => value == null);
} else {
existResult.removeWhere((key, value) => value != null);
}
return existResult.keys.map((md5sum) => md5sumList[md5sum]!).toList();
} on DioException catch (e) {
debugPrint('Edit images: ${e.message}');
} on Error catch (e) {
debugPrint('Edit images: ${e.stackTrace}');
}
return [];
}
String? removeUrlProtocol(String? url) {
if (url == null) return null;
url = url.replaceFirst('http://', '');
url = url.replaceFirst('https://', '');
return url;
}
String? cleanImageUrl(String? originalUrl) {
if (originalUrl == null) return null;
final String okUrl = originalUrl;
// TEMPORARY PATCH for case where $conf['original_url_protection'] = 'images';
/// See https://github.com/Piwigo/Piwigo-Mobile/issues/503
String patchedUrl = okUrl.replaceAll('&part=', '&part=');
// Servers may return incorrect URLs
/// See https://tools.ietf.org/html/rfc3986#section-2
Uri? serverUrl = Uri.tryParse(patchedUrl);
if (serverUrl == null) {
// URL not RFC compliant!
String leftUrl = patchedUrl;
// Remove protocol header
leftUrl = removeUrlProtocol(patchedUrl) ?? leftUrl;
// Retrieve authority
int endAuthority = leftUrl.indexOf('/');
// No path, incomplete URL —> return image.jpg but should never happen
if (endAuthority == -1) return null;
leftUrl = leftUrl.substring(endAuthority);
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// So we remove the path to avoid a duplicate if necessary
String? loginUrl = appPreferences.getString(Preferences.serverUrlKey);
loginUrl = removeUrlProtocol(loginUrl);
if (loginUrl != null && loginUrl.isNotEmpty && leftUrl.startsWith(loginUrl)) {
leftUrl = leftUrl.substring(loginUrl.length);
}
// Retrieve path
int endQuery = leftUrl.indexOf('?');
if (endQuery != -1) {
String query = leftUrl.substring(0, endQuery);
query.replaceAll('??', '?');
String encodedQuery = Uri.encodeComponent(query);
leftUrl.substring(0, query.length);
String encodedPath = Uri.encodeComponent(leftUrl);
serverUrl = Uri.tryParse("$loginUrl$encodedQuery$encodedPath");
} else {
// No query -> remaining string is a path
String encodedPath = Uri.encodeComponent(leftUrl);
serverUrl = Uri.tryParse("$loginUrl$encodedPath");
}
// Last check
if (serverUrl == null) {
// Could not apply percent encoding —> return nil
return null;
}
}
// Servers may return image URLs different from those used to login (e.g. wrong server settings)
// We only keep the path+query because we only accept to download images from the same server.
String cleanPath = serverUrl.path;
// todo : parameterString
String query = serverUrl.query;
if (query.isNotEmpty) {
cleanPath.joinChar("?$query");
}
String fragment = serverUrl.fragment;
if (fragment.isNotEmpty) {
cleanPath.joinChar("#$fragment");
}
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// and images may not be in the same path
String? loginPath = appPreferences.getString(Preferences.serverUrlKey);
loginPath = removeUrlProtocol(loginPath);
if (loginPath != null && loginPath.isNotEmpty) {
if (cleanPath.startsWith(loginPath)) {
cleanPath = cleanPath.substring(loginPath.length);
} else if (cleanPath.endsWith(loginPath)) {
cleanPath = cleanPath.substring(0, cleanPath.length - loginPath.length);
}
}
// Remove the .php?, i? prefixes if any
String prefix = '';
int pos = cleanPath.indexOf('?');
if (pos != -1) {
prefix = cleanPath.substring(0, pos);
}
// Path may not be encoded
String decodedPath = Uri.decodeComponent(cleanPath);
if (cleanPath == decodedPath) {
String test = Uri.encodeComponent(cleanPath);
cleanPath = test;
}
// Compile final URL using the one provided at login
String encodedImageUrl = "${serverUrl.scheme}://$loginPath$prefix$cleanPath";
if (kDebugMode) {
if (encodedImageUrl != originalUrl) {
print("=> originalURL:$originalUrl");
print(" encodedURL:$encodedImageUrl");
print(
" path=${serverUrl.path}, parameterString=${serverUrl.data}, query:${serverUrl.query}, fragment:${serverUrl.fragment}");
}
}
return encodedImageUrl;
}