fading_app_bar.dart 18 KB

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