fading_app_bar.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. import 'dart:io';
  2. import 'dart:io' as io;
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:like_button/like_button.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:media_extension/media_extension.dart';
  8. import 'package:path/path.dart' as file_path;
  9. import 'package:photo_manager/photo_manager.dart';
  10. import 'package:photos/core/event_bus.dart';
  11. import 'package:photos/db/files_db.dart';
  12. import 'package:photos/events/local_photos_updated_event.dart';
  13. import 'package:photos/models/file.dart';
  14. import 'package:photos/models/file_type.dart';
  15. import 'package:photos/models/ignored_file.dart';
  16. import 'package:photos/models/selected_files.dart';
  17. import 'package:photos/models/trash_file.dart';
  18. import 'package:photos/services/collections_service.dart';
  19. import 'package:photos/services/favorites_service.dart';
  20. import 'package:photos/services/hidden_service.dart';
  21. import 'package:photos/services/ignored_files_service.dart';
  22. import 'package:photos/services/local_sync_service.dart';
  23. import 'package:photos/ui/common/progress_dialog.dart';
  24. import 'package:photos/ui/components/action_sheet_widget.dart';
  25. import 'package:photos/ui/components/button_widget.dart';
  26. import 'package:photos/ui/components/models/button_type.dart';
  27. import 'package:photos/ui/create_collection_sheet.dart';
  28. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  29. import 'package:photos/utils/delete_file_util.dart';
  30. import 'package:photos/utils/dialog_util.dart';
  31. import 'package:photos/utils/file_util.dart';
  32. import 'package:photos/utils/toast_util.dart';
  33. class FadingAppBar extends StatefulWidget implements PreferredSizeWidget {
  34. final File file;
  35. final Function(File) onFileRemoved;
  36. final double height;
  37. final bool shouldShowActions;
  38. final int? userID;
  39. const FadingAppBar(
  40. this.file,
  41. this.onFileRemoved,
  42. this.userID,
  43. this.height,
  44. this.shouldShowActions, {
  45. Key? key,
  46. }) : super(key: key);
  47. @override
  48. Size get preferredSize => Size.fromHeight(height);
  49. @override
  50. FadingAppBarState createState() => FadingAppBarState();
  51. }
  52. class FadingAppBarState extends State<FadingAppBar> {
  53. final _logger = Logger("FadingAppBar");
  54. bool _shouldHide = false;
  55. @override
  56. Widget build(BuildContext context) {
  57. return CustomAppBar(
  58. IgnorePointer(
  59. ignoring: _shouldHide,
  60. child: AnimatedOpacity(
  61. opacity: _shouldHide ? 0 : 1,
  62. duration: const Duration(milliseconds: 150),
  63. child: Container(
  64. decoration: BoxDecoration(
  65. gradient: LinearGradient(
  66. begin: Alignment.topCenter,
  67. end: Alignment.bottomCenter,
  68. colors: [
  69. Colors.black.withOpacity(0.72),
  70. Colors.black.withOpacity(0.6),
  71. Colors.transparent,
  72. ],
  73. stops: const [0, 0.2, 1],
  74. ),
  75. ),
  76. child: _buildAppBar(),
  77. ),
  78. ),
  79. ),
  80. Size.fromHeight(Platform.isAndroid ? 80 : 96),
  81. );
  82. }
  83. void hide() {
  84. setState(() {
  85. _shouldHide = true;
  86. });
  87. }
  88. void show() {
  89. if (mounted) {
  90. setState(() {
  91. _shouldHide = false;
  92. });
  93. }
  94. }
  95. AppBar _buildAppBar() {
  96. debugPrint("building app bar");
  97. final List<Widget> actions = [];
  98. final isTrashedFile = widget.file is TrashFile;
  99. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  100. final bool isOwnedByUser =
  101. widget.file.ownerID == null || widget.file.ownerID == widget.userID;
  102. final bool isFileUploaded = widget.file.isUploaded;
  103. bool isFileHidden = false;
  104. if (isOwnedByUser && isFileUploaded) {
  105. isFileHidden = CollectionsService.instance
  106. .getCollectionByID(widget.file.collectionID!)
  107. ?.isHidden() ??
  108. false;
  109. }
  110. // only show fav option for files owned by the user
  111. if (isOwnedByUser && !isFileHidden && isFileUploaded) {
  112. actions.add(_getFavoriteButton());
  113. }
  114. actions.add(
  115. PopupMenuButton(
  116. itemBuilder: (context) {
  117. final List<PopupMenuItem> items = [];
  118. if (widget.file.isRemoteFile) {
  119. items.add(
  120. PopupMenuItem(
  121. value: 1,
  122. child: Row(
  123. children: [
  124. Icon(
  125. Platform.isAndroid
  126. ? Icons.download
  127. : CupertinoIcons.cloud_download,
  128. color: Theme.of(context).iconTheme.color,
  129. ),
  130. const Padding(
  131. padding: EdgeInsets.all(8),
  132. ),
  133. const Text("Download"),
  134. ],
  135. ),
  136. ),
  137. );
  138. }
  139. // options for files owned by the user
  140. if (isOwnedByUser) {
  141. items.add(
  142. PopupMenuItem(
  143. value: 2,
  144. child: Row(
  145. children: [
  146. Icon(
  147. Platform.isAndroid
  148. ? Icons.delete_outline
  149. : CupertinoIcons.delete,
  150. color: Theme.of(context).iconTheme.color,
  151. ),
  152. const Padding(
  153. padding: EdgeInsets.all(8),
  154. ),
  155. const Text("Delete"),
  156. ],
  157. ),
  158. ),
  159. );
  160. }
  161. if ((widget.file.fileType == FileType.image ||
  162. widget.file.fileType == FileType.livePhoto) &&
  163. Platform.isAndroid) {
  164. items.add(
  165. PopupMenuItem(
  166. value: 3,
  167. child: Row(
  168. children: [
  169. Icon(
  170. Icons.wallpaper_outlined,
  171. color: Theme.of(context).iconTheme.color,
  172. ),
  173. const Padding(
  174. padding: EdgeInsets.all(8),
  175. ),
  176. const Text("Set as"),
  177. ],
  178. ),
  179. ),
  180. );
  181. }
  182. if (isOwnedByUser && widget.file.isUploaded) {
  183. if (!isFileHidden) {
  184. items.add(
  185. PopupMenuItem(
  186. value: 4,
  187. child: Row(
  188. children: [
  189. Icon(
  190. Icons.visibility_off,
  191. color: Theme.of(context).iconTheme.color,
  192. ),
  193. const Padding(
  194. padding: EdgeInsets.all(8),
  195. ),
  196. const Text("Hide"),
  197. ],
  198. ),
  199. ),
  200. );
  201. } else {
  202. items.add(
  203. PopupMenuItem(
  204. value: 5,
  205. child: Row(
  206. children: [
  207. Icon(
  208. Icons.visibility,
  209. color: Theme.of(context).iconTheme.color,
  210. ),
  211. const Padding(
  212. padding: EdgeInsets.all(8),
  213. ),
  214. const Text("Unhide"),
  215. ],
  216. ),
  217. ),
  218. );
  219. }
  220. }
  221. return items;
  222. },
  223. onSelected: (dynamic value) async {
  224. if (value == 1) {
  225. _download(widget.file);
  226. } else if (value == 2) {
  227. await _showSingleFileDeleteSheet(widget.file);
  228. } else if (value == 3) {
  229. _setAs(widget.file);
  230. } else if (value == 4) {
  231. _handleHideRequest(context);
  232. } else if (value == 5) {
  233. _handleUnHideRequest(context);
  234. }
  235. },
  236. ),
  237. );
  238. return AppBar(
  239. iconTheme:
  240. const IconThemeData(color: Colors.white), //same for both themes
  241. actions: shouldShowActions ? actions : [],
  242. elevation: 0,
  243. backgroundColor: const Color(0x00000000),
  244. );
  245. }
  246. Future<void> _handleHideRequest(BuildContext context) async {
  247. try {
  248. final hideResult =
  249. await CollectionsService.instance.hideFiles(context, [widget.file]);
  250. if (hideResult) {
  251. widget.onFileRemoved(widget.file);
  252. }
  253. } catch (e, s) {
  254. _logger.severe("failed to update file visibility", e, s);
  255. await showGenericErrorDialog(context: context);
  256. }
  257. }
  258. Future<void> _handleUnHideRequest(BuildContext context) async {
  259. final selectedFiles = SelectedFiles();
  260. selectedFiles.files.add(widget.file);
  261. showCollectionActionSheet(
  262. context,
  263. selectedFiles: selectedFiles,
  264. actionType: CollectionActionType.unHide,
  265. );
  266. }
  267. Widget _getFavoriteButton() {
  268. return FutureBuilder<bool>(
  269. future: FavoritesService.instance.isFavorite(widget.file),
  270. builder: (context, snapshot) {
  271. if (snapshot.hasData) {
  272. return _getLikeButton(widget.file, snapshot.data);
  273. } else {
  274. return _getLikeButton(widget.file, false);
  275. }
  276. },
  277. );
  278. }
  279. Widget _getLikeButton(File file, bool? isLiked) {
  280. return LikeButton(
  281. isLiked: isLiked,
  282. onTap: (oldValue) async {
  283. final isLiked = !oldValue;
  284. bool hasError = false;
  285. if (isLiked) {
  286. final shouldBlockUser = file.uploadedFileID == null;
  287. late ProgressDialog dialog;
  288. if (shouldBlockUser) {
  289. dialog = createProgressDialog(context, "Adding to favorites...");
  290. await dialog.show();
  291. }
  292. try {
  293. await FavoritesService.instance.addToFavorites(context, file);
  294. } catch (e, s) {
  295. _logger.severe(e, s);
  296. hasError = true;
  297. showToast(context, "Sorry, could not add this to favorites!");
  298. } finally {
  299. if (shouldBlockUser) {
  300. await dialog.hide();
  301. }
  302. }
  303. } else {
  304. try {
  305. await FavoritesService.instance.removeFromFavorites(context, file);
  306. } catch (e, s) {
  307. _logger.severe(e, s);
  308. hasError = true;
  309. showToast(context, "Sorry, could not remove this from favorites!");
  310. }
  311. }
  312. return hasError ? oldValue : isLiked;
  313. },
  314. likeBuilder: (isLiked) {
  315. return Icon(
  316. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  317. color:
  318. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  319. size: 24,
  320. );
  321. },
  322. );
  323. }
  324. Future<void> _showSingleFileDeleteSheet(File file) async {
  325. final List<ButtonWidget> buttons = [];
  326. final String fileType = file.fileType == FileType.video ? "video" : "photo";
  327. final bool isBothLocalAndRemote =
  328. file.uploadedFileID != null && file.localID != null;
  329. final bool isLocalOnly =
  330. file.uploadedFileID == null && file.localID != null;
  331. final bool isRemoteOnly =
  332. file.uploadedFileID != null && file.localID == null;
  333. const String bodyHighlight = "It will be deleted from all albums.";
  334. String body = "";
  335. if (isBothLocalAndRemote) {
  336. body = "This $fileType is in both ente and your device.";
  337. } else if (isRemoteOnly) {
  338. body = "This $fileType will be deleted from ente.";
  339. } else if (isLocalOnly) {
  340. body = "This $fileType will be deleted from your device.";
  341. } else {
  342. throw AssertionError("Unexpected state");
  343. }
  344. // Add option to delete from ente
  345. if (isBothLocalAndRemote || isRemoteOnly) {
  346. buttons.add(
  347. ButtonWidget(
  348. labelText: isBothLocalAndRemote ? "Delete from ente" : "Yes, delete",
  349. buttonType: ButtonType.neutral,
  350. buttonSize: ButtonSize.large,
  351. shouldStickToDarkTheme: true,
  352. buttonAction: ButtonAction.first,
  353. shouldSurfaceExecutionStates: true,
  354. isInAlert: true,
  355. onTap: () async {
  356. await deleteFilesFromRemoteOnly(context, [file]);
  357. showShortToast(context, "Moved to trash");
  358. if (isRemoteOnly) {
  359. Navigator.of(context, rootNavigator: true).pop();
  360. widget.onFileRemoved(file);
  361. }
  362. },
  363. ),
  364. );
  365. }
  366. // Add option to delete from local
  367. if (isBothLocalAndRemote || isLocalOnly) {
  368. buttons.add(
  369. ButtonWidget(
  370. labelText:
  371. isBothLocalAndRemote ? "Delete from device" : "Yes, delete",
  372. buttonType: ButtonType.neutral,
  373. buttonSize: ButtonSize.large,
  374. shouldStickToDarkTheme: true,
  375. buttonAction: ButtonAction.second,
  376. shouldSurfaceExecutionStates: false,
  377. isInAlert: true,
  378. onTap: () async {
  379. await deleteFilesOnDeviceOnly(context, [file]);
  380. if (isLocalOnly) {
  381. Navigator.of(context, rootNavigator: true).pop();
  382. widget.onFileRemoved(file);
  383. }
  384. },
  385. ),
  386. );
  387. }
  388. if (isBothLocalAndRemote) {
  389. buttons.add(
  390. ButtonWidget(
  391. labelText: "Delete from both",
  392. buttonType: ButtonType.neutral,
  393. buttonSize: ButtonSize.large,
  394. shouldStickToDarkTheme: true,
  395. buttonAction: ButtonAction.third,
  396. shouldSurfaceExecutionStates: true,
  397. isInAlert: true,
  398. onTap: () async {
  399. await deleteFilesFromEverywhere(context, [file]);
  400. Navigator.of(context, rootNavigator: true).pop();
  401. widget.onFileRemoved(file);
  402. },
  403. ),
  404. );
  405. }
  406. buttons.add(
  407. const ButtonWidget(
  408. labelText: "Cancel",
  409. buttonType: ButtonType.secondary,
  410. buttonSize: ButtonSize.large,
  411. shouldStickToDarkTheme: true,
  412. buttonAction: ButtonAction.fourth,
  413. isInAlert: true,
  414. ),
  415. );
  416. final actionResult = await showActionSheet(
  417. context: context,
  418. buttons: buttons,
  419. actionSheetType: ActionSheetType.defaultActionSheet,
  420. body: body,
  421. bodyHighlight: bodyHighlight,
  422. );
  423. if (actionResult?.action != null &&
  424. actionResult!.action == ButtonAction.error) {
  425. showGenericErrorDialog(context: context);
  426. }
  427. }
  428. Future<void> _download(File file) async {
  429. final dialog = createProgressDialog(context, "Downloading...");
  430. await dialog.show();
  431. try {
  432. final FileType type = file.fileType;
  433. final bool downloadLivePhotoOnDroid =
  434. type == FileType.livePhoto && Platform.isAndroid;
  435. AssetEntity? savedAsset;
  436. final io.File? fileToSave = await getFile(file);
  437. //Disabling notifications for assets changing to insert the file into
  438. //files db before triggering a sync.
  439. PhotoManager.stopChangeNotify();
  440. if (type == FileType.image) {
  441. savedAsset = await PhotoManager.editor
  442. .saveImageWithPath(fileToSave!.path, title: file.title!);
  443. } else if (type == FileType.video) {
  444. savedAsset = await PhotoManager.editor
  445. .saveVideo(fileToSave!, title: file.title!);
  446. } else if (type == FileType.livePhoto) {
  447. final io.File? liveVideoFile =
  448. await getFileFromServer(file, liveVideo: true);
  449. if (liveVideoFile == null) {
  450. throw AssertionError("Live video can not be null");
  451. }
  452. if (downloadLivePhotoOnDroid) {
  453. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  454. } else {
  455. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  456. imageFile: fileToSave!,
  457. videoFile: liveVideoFile,
  458. title: file.title!,
  459. );
  460. }
  461. }
  462. if (savedAsset != null) {
  463. file.localID = savedAsset.id;
  464. await FilesDB.instance.insert(file);
  465. Bus.instance.fire(
  466. LocalPhotosUpdatedEvent(
  467. [file],
  468. source: "download",
  469. ),
  470. );
  471. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  472. _logger.severe('Failed to save assert of type $type');
  473. }
  474. showToast(context, "File saved to gallery");
  475. await dialog.hide();
  476. } catch (e) {
  477. _logger.warning("Failed to save file", e);
  478. await dialog.hide();
  479. showGenericErrorDialog(context: context);
  480. } finally {
  481. PhotoManager.startChangeNotify();
  482. LocalSyncService.instance.checkAndSync().ignore();
  483. }
  484. }
  485. Future<void> _saveLivePhotoOnDroid(
  486. io.File image,
  487. io.File video,
  488. File enteFile,
  489. ) async {
  490. debugPrint("Downloading LivePhoto on Droid");
  491. AssetEntity? savedAsset = await (PhotoManager.editor
  492. .saveImageWithPath(image.path, title: enteFile.title!));
  493. if (savedAsset == null) {
  494. throw Exception("Failed to save image of live photo");
  495. }
  496. IgnoredFile ignoreVideoFile = IgnoredFile(
  497. savedAsset.id,
  498. savedAsset.title ?? '',
  499. savedAsset.relativePath ?? 'remoteDownload',
  500. "remoteDownload",
  501. );
  502. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  503. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  504. file_path.extension(video.path);
  505. savedAsset = (await (PhotoManager.editor.saveVideo(
  506. video,
  507. title: videoTitle,
  508. )));
  509. if (savedAsset == null) {
  510. throw Exception("Failed to save video of live photo");
  511. }
  512. ignoreVideoFile = IgnoredFile(
  513. savedAsset.id,
  514. savedAsset.title ?? videoTitle,
  515. savedAsset.relativePath ?? 'remoteDownload',
  516. "remoteDownload",
  517. );
  518. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  519. }
  520. Future<void> _setAs(File file) async {
  521. final dialog = createProgressDialog(context, "Please wait...");
  522. await dialog.show();
  523. try {
  524. final io.File? fileToSave = await (getFile(file));
  525. if (fileToSave == null) {
  526. throw Exception("Fail to get file for setAs operation");
  527. }
  528. final m = MediaExtension();
  529. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  530. if (result == false) {
  531. showShortToast(context, "Something went wrong");
  532. }
  533. dialog.hide();
  534. } catch (e) {
  535. dialog.hide();
  536. _logger.severe("Failed to use as", e);
  537. showGenericErrorDialog(context: context);
  538. }
  539. }
  540. }