fading_app_bar.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 s = SelectedFiles();
  260. s.files.add(widget.file);
  261. createCollectionSheet(
  262. s,
  263. null,
  264. context,
  265. actionType: CollectionActionType.unHide,
  266. );
  267. }
  268. Widget _getFavoriteButton() {
  269. return FutureBuilder<bool>(
  270. future: FavoritesService.instance.isFavorite(widget.file),
  271. builder: (context, snapshot) {
  272. if (snapshot.hasData) {
  273. return _getLikeButton(widget.file, snapshot.data);
  274. } else {
  275. return _getLikeButton(widget.file, false);
  276. }
  277. },
  278. );
  279. }
  280. Widget _getLikeButton(File file, bool? isLiked) {
  281. return LikeButton(
  282. isLiked: isLiked,
  283. onTap: (oldValue) async {
  284. final isLiked = !oldValue;
  285. bool hasError = false;
  286. if (isLiked) {
  287. final shouldBlockUser = file.uploadedFileID == null;
  288. late ProgressDialog dialog;
  289. if (shouldBlockUser) {
  290. dialog = createProgressDialog(context, "Adding to favorites...");
  291. await dialog.show();
  292. }
  293. try {
  294. await FavoritesService.instance.addToFavorites(context, file);
  295. } catch (e, s) {
  296. _logger.severe(e, s);
  297. hasError = true;
  298. showToast(context, "Sorry, could not add this to favorites!");
  299. } finally {
  300. if (shouldBlockUser) {
  301. await dialog.hide();
  302. }
  303. }
  304. } else {
  305. try {
  306. await FavoritesService.instance.removeFromFavorites(context, file);
  307. } catch (e, s) {
  308. _logger.severe(e, s);
  309. hasError = true;
  310. showToast(context, "Sorry, could not remove this from favorites!");
  311. }
  312. }
  313. return hasError ? oldValue : isLiked;
  314. },
  315. likeBuilder: (isLiked) {
  316. return Icon(
  317. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  318. color:
  319. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  320. size: 24,
  321. );
  322. },
  323. );
  324. }
  325. Future<void> _showSingleFileDeleteSheet(File file) async {
  326. final List<ButtonWidget> buttons = [];
  327. final String fileType = file.fileType == FileType.video ? "video" : "photo";
  328. final bool isBothLocalAndRemote =
  329. file.uploadedFileID != null && file.localID != null;
  330. final bool isLocalOnly =
  331. file.uploadedFileID == null && file.localID != null;
  332. final bool isRemoteOnly =
  333. file.uploadedFileID != null && file.localID == null;
  334. const String bodyHighlight = "It will be deleted from all albums.";
  335. String body = "";
  336. if (isBothLocalAndRemote) {
  337. body = "This $fileType is in both ente and your device.";
  338. } else if (isRemoteOnly) {
  339. body = "This $fileType will be deleted from ente.";
  340. } else if (isLocalOnly) {
  341. body = "This $fileType will be deleted from your device.";
  342. } else {
  343. throw AssertionError("Unexpected state");
  344. }
  345. // Add option to delete from ente
  346. if (isBothLocalAndRemote || isRemoteOnly) {
  347. buttons.add(
  348. ButtonWidget(
  349. labelText: isBothLocalAndRemote ? "Delete from ente" : "Yes, delete",
  350. buttonType: ButtonType.neutral,
  351. buttonSize: ButtonSize.large,
  352. shouldStickToDarkTheme: true,
  353. buttonAction: ButtonAction.first,
  354. shouldSurfaceExecutionStates: true,
  355. isInAlert: true,
  356. onTap: () async {
  357. await deleteFilesFromRemoteOnly(context, [file]);
  358. showShortToast(context, "Moved to trash");
  359. if (isRemoteOnly) {
  360. Navigator.of(context, rootNavigator: true).pop();
  361. widget.onFileRemoved(file);
  362. }
  363. },
  364. ),
  365. );
  366. }
  367. // Add option to delete from local
  368. if (isBothLocalAndRemote || isLocalOnly) {
  369. buttons.add(
  370. ButtonWidget(
  371. labelText:
  372. isBothLocalAndRemote ? "Delete from device" : "Yes, delete",
  373. buttonType: ButtonType.neutral,
  374. buttonSize: ButtonSize.large,
  375. shouldStickToDarkTheme: true,
  376. buttonAction: ButtonAction.second,
  377. shouldSurfaceExecutionStates: false,
  378. isInAlert: true,
  379. onTap: () async {
  380. await deleteFilesOnDeviceOnly(context, [file]);
  381. if (isLocalOnly) {
  382. Navigator.of(context, rootNavigator: true).pop();
  383. widget.onFileRemoved(file);
  384. }
  385. },
  386. ),
  387. );
  388. }
  389. if (isBothLocalAndRemote) {
  390. buttons.add(
  391. ButtonWidget(
  392. labelText: "Delete from both",
  393. buttonType: ButtonType.neutral,
  394. buttonSize: ButtonSize.large,
  395. shouldStickToDarkTheme: true,
  396. buttonAction: ButtonAction.third,
  397. shouldSurfaceExecutionStates: true,
  398. isInAlert: true,
  399. onTap: () async {
  400. await deleteFilesFromEverywhere(context, [file]);
  401. Navigator.of(context, rootNavigator: true).pop();
  402. widget.onFileRemoved(file);
  403. },
  404. ),
  405. );
  406. }
  407. buttons.add(
  408. const ButtonWidget(
  409. labelText: "Cancel",
  410. buttonType: ButtonType.secondary,
  411. buttonSize: ButtonSize.large,
  412. shouldStickToDarkTheme: true,
  413. buttonAction: ButtonAction.fourth,
  414. isInAlert: true,
  415. ),
  416. );
  417. final actionResult = await showActionSheet(
  418. context: context,
  419. buttons: buttons,
  420. actionSheetType: ActionSheetType.defaultActionSheet,
  421. body: body,
  422. bodyHighlight: bodyHighlight,
  423. );
  424. if (actionResult?.action != null &&
  425. actionResult!.action == ButtonAction.error) {
  426. showGenericErrorDialog(context: context);
  427. }
  428. }
  429. Future<void> _download(File file) async {
  430. final dialog = createProgressDialog(context, "Downloading...");
  431. await dialog.show();
  432. try {
  433. final FileType type = file.fileType;
  434. final bool downloadLivePhotoOnDroid =
  435. type == FileType.livePhoto && Platform.isAndroid;
  436. AssetEntity? savedAsset;
  437. final io.File? fileToSave = await getFile(file);
  438. //Disabling notifications for assets changing to insert the file into
  439. //files db before triggering a sync.
  440. PhotoManager.stopChangeNotify();
  441. if (type == FileType.image) {
  442. savedAsset = await PhotoManager.editor
  443. .saveImageWithPath(fileToSave!.path, title: file.title!);
  444. } else if (type == FileType.video) {
  445. savedAsset = await PhotoManager.editor
  446. .saveVideo(fileToSave!, title: file.title!);
  447. } else if (type == FileType.livePhoto) {
  448. final io.File? liveVideoFile =
  449. await getFileFromServer(file, liveVideo: true);
  450. if (liveVideoFile == null) {
  451. throw AssertionError("Live video can not be null");
  452. }
  453. if (downloadLivePhotoOnDroid) {
  454. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  455. } else {
  456. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  457. imageFile: fileToSave!,
  458. videoFile: liveVideoFile,
  459. title: file.title!,
  460. );
  461. }
  462. }
  463. if (savedAsset != null) {
  464. file.localID = savedAsset.id;
  465. await FilesDB.instance.insert(file);
  466. Bus.instance.fire(
  467. LocalPhotosUpdatedEvent(
  468. [file],
  469. source: "download",
  470. ),
  471. );
  472. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  473. _logger.severe('Failed to save assert of type $type');
  474. }
  475. showToast(context, "File saved to gallery");
  476. await dialog.hide();
  477. } catch (e) {
  478. _logger.warning("Failed to save file", e);
  479. await dialog.hide();
  480. showGenericErrorDialog(context: context);
  481. } finally {
  482. PhotoManager.startChangeNotify();
  483. LocalSyncService.instance.checkAndSync().ignore();
  484. }
  485. }
  486. Future<void> _saveLivePhotoOnDroid(
  487. io.File image,
  488. io.File video,
  489. File enteFile,
  490. ) async {
  491. debugPrint("Downloading LivePhoto on Droid");
  492. AssetEntity? savedAsset = await (PhotoManager.editor
  493. .saveImageWithPath(image.path, title: enteFile.title!));
  494. if (savedAsset == null) {
  495. throw Exception("Failed to save image of live photo");
  496. }
  497. IgnoredFile ignoreVideoFile = IgnoredFile(
  498. savedAsset.id,
  499. savedAsset.title ?? '',
  500. savedAsset.relativePath ?? 'remoteDownload',
  501. "remoteDownload",
  502. );
  503. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  504. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  505. file_path.extension(video.path);
  506. savedAsset = (await (PhotoManager.editor.saveVideo(
  507. video,
  508. title: videoTitle,
  509. )));
  510. if (savedAsset == null) {
  511. throw Exception("Failed to save video of live photo");
  512. }
  513. ignoreVideoFile = IgnoredFile(
  514. savedAsset.id,
  515. savedAsset.title ?? videoTitle,
  516. savedAsset.relativePath ?? 'remoteDownload',
  517. "remoteDownload",
  518. );
  519. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  520. }
  521. Future<void> _setAs(File file) async {
  522. final dialog = createProgressDialog(context, "Please wait...");
  523. await dialog.show();
  524. try {
  525. final io.File? fileToSave = await (getFile(file));
  526. if (fileToSave == null) {
  527. throw Exception("Fail to get file for setAs operation");
  528. }
  529. final m = MediaExtension();
  530. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  531. if (result == false) {
  532. showShortToast(context, "Something went wrong");
  533. }
  534. dialog.hide();
  535. } catch (e) {
  536. dialog.hide();
  537. _logger.severe("Failed to use as", e);
  538. showGenericErrorDialog(context: context);
  539. }
  540. }
  541. }