fading_app_bar.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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(context, 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(context, 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. const String bodyHighlight = "It will be deleted from all albums.";
  341. String body = "";
  342. if (isBothLocalAndRemote) {
  343. body = "This $fileType is in both ente and your device.";
  344. } else if (isRemoteOnly) {
  345. body = "This $fileType will be deleted from ente.";
  346. } else if (isLocalOnly) {
  347. body = "This $fileType will be deleted from your device.";
  348. } else {
  349. throw AssertionError("Unexpected state");
  350. }
  351. // Add option to delete from ente
  352. if (isBothLocalAndRemote || isRemoteOnly) {
  353. buttons.add(
  354. ButtonWidget(
  355. labelText: isBothLocalAndRemote ? "Delete from ente" : "Yes, delete",
  356. buttonType: ButtonType.neutral,
  357. buttonSize: ButtonSize.large,
  358. shouldStickToDarkTheme: true,
  359. buttonAction: ButtonAction.first,
  360. shouldSurfaceExecutionStates: true,
  361. isInAlert: true,
  362. onTap: () async {
  363. await deleteFilesFromRemoteOnly(context, [file]);
  364. showShortToast(context, "Moved to trash");
  365. if (isRemoteOnly) {
  366. Navigator.of(context, rootNavigator: true).pop();
  367. widget.onFileRemoved(file);
  368. }
  369. },
  370. ),
  371. );
  372. }
  373. // Add option to delete from local
  374. if (isBothLocalAndRemote || isLocalOnly) {
  375. buttons.add(
  376. ButtonWidget(
  377. labelText:
  378. isBothLocalAndRemote ? "Delete from device" : "Yes, delete",
  379. buttonType: ButtonType.neutral,
  380. buttonSize: ButtonSize.large,
  381. shouldStickToDarkTheme: true,
  382. buttonAction: ButtonAction.second,
  383. shouldSurfaceExecutionStates: false,
  384. isInAlert: true,
  385. onTap: () async {
  386. await deleteFilesOnDeviceOnly(context, [file]);
  387. if (isLocalOnly) {
  388. Navigator.of(context, rootNavigator: true).pop();
  389. widget.onFileRemoved(file);
  390. }
  391. },
  392. ),
  393. );
  394. }
  395. if (isBothLocalAndRemote) {
  396. buttons.add(
  397. ButtonWidget(
  398. labelText: "Delete from both",
  399. buttonType: ButtonType.neutral,
  400. buttonSize: ButtonSize.large,
  401. shouldStickToDarkTheme: true,
  402. buttonAction: ButtonAction.third,
  403. shouldSurfaceExecutionStates: true,
  404. isInAlert: true,
  405. onTap: () async {
  406. await deleteFilesFromEverywhere(context, [file]);
  407. Navigator.of(context, rootNavigator: true).pop();
  408. widget.onFileRemoved(file);
  409. },
  410. ),
  411. );
  412. }
  413. buttons.add(
  414. const ButtonWidget(
  415. labelText: "Cancel",
  416. buttonType: ButtonType.secondary,
  417. buttonSize: ButtonSize.large,
  418. shouldStickToDarkTheme: true,
  419. buttonAction: ButtonAction.fourth,
  420. isInAlert: true,
  421. ),
  422. );
  423. final ButtonAction? result = await showActionSheet(
  424. context: context,
  425. buttons: buttons,
  426. actionSheetType: ActionSheetType.defaultActionSheet,
  427. body: body,
  428. bodyHighlight: bodyHighlight,
  429. );
  430. if (result != null && result == ButtonAction.error) {
  431. showGenericErrorDialog(context: context);
  432. }
  433. }
  434. Future<void> _download(File file) async {
  435. final dialog = createProgressDialog(context, "Downloading...");
  436. await dialog.show();
  437. try {
  438. final FileType type = file.fileType;
  439. final bool downloadLivePhotoOnDroid =
  440. type == FileType.livePhoto && Platform.isAndroid;
  441. AssetEntity? savedAsset;
  442. final io.File? fileToSave = await getFile(file);
  443. //Disabling notifications for assets changing to insert the file into
  444. //files db before triggering a sync.
  445. PhotoManager.stopChangeNotify();
  446. if (type == FileType.image) {
  447. savedAsset = await PhotoManager.editor
  448. .saveImageWithPath(fileToSave!.path, title: file.title!);
  449. } else if (type == FileType.video) {
  450. savedAsset = await PhotoManager.editor
  451. .saveVideo(fileToSave!, title: file.title!);
  452. } else if (type == FileType.livePhoto) {
  453. final io.File? liveVideoFile =
  454. await getFileFromServer(file, liveVideo: true);
  455. if (liveVideoFile == null) {
  456. throw AssertionError("Live video can not be null");
  457. }
  458. if (downloadLivePhotoOnDroid) {
  459. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  460. } else {
  461. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  462. imageFile: fileToSave!,
  463. videoFile: liveVideoFile,
  464. title: file.title!,
  465. );
  466. }
  467. }
  468. if (savedAsset != null) {
  469. file.localID = savedAsset.id;
  470. await FilesDB.instance.insert(file);
  471. Bus.instance.fire(
  472. LocalPhotosUpdatedEvent(
  473. [file],
  474. source: "download",
  475. ),
  476. );
  477. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  478. _logger.severe('Failed to save assert of type $type');
  479. }
  480. showToast(context, "File saved to gallery");
  481. await dialog.hide();
  482. } catch (e) {
  483. _logger.warning("Failed to save file", e);
  484. await dialog.hide();
  485. showGenericErrorDialog(context: context);
  486. } finally {
  487. PhotoManager.startChangeNotify();
  488. LocalSyncService.instance.checkAndSync().ignore();
  489. }
  490. }
  491. Future<void> _saveLivePhotoOnDroid(
  492. io.File image,
  493. io.File video,
  494. File enteFile,
  495. ) async {
  496. debugPrint("Downloading LivePhoto on Droid");
  497. AssetEntity? savedAsset = await (PhotoManager.editor
  498. .saveImageWithPath(image.path, title: enteFile.title!));
  499. if (savedAsset == null) {
  500. throw Exception("Failed to save image of live photo");
  501. }
  502. IgnoredFile ignoreVideoFile = IgnoredFile(
  503. savedAsset.id,
  504. savedAsset.title ?? '',
  505. savedAsset.relativePath ?? 'remoteDownload',
  506. "remoteDownload",
  507. );
  508. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  509. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  510. file_path.extension(video.path);
  511. savedAsset = (await (PhotoManager.editor.saveVideo(
  512. video,
  513. title: videoTitle,
  514. )));
  515. if (savedAsset == null) {
  516. throw Exception("Failed to save video of live photo");
  517. }
  518. ignoreVideoFile = IgnoredFile(
  519. savedAsset.id,
  520. savedAsset.title ?? videoTitle,
  521. savedAsset.relativePath ?? 'remoteDownload',
  522. "remoteDownload",
  523. );
  524. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  525. }
  526. Future<void> _setAs(File file) async {
  527. final dialog = createProgressDialog(context, "Please wait...");
  528. await dialog.show();
  529. try {
  530. final io.File? fileToSave = await (getFile(file));
  531. if (fileToSave == null) {
  532. throw Exception("Fail to get file for setAs operation");
  533. }
  534. final m = MediaExtension();
  535. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  536. if (result == false) {
  537. showShortToast(context, "Something went wrong");
  538. }
  539. dialog.hide();
  540. } catch (e) {
  541. dialog.hide();
  542. _logger.severe("Failed to use as", e);
  543. showGenericErrorDialog(context: context);
  544. }
  545. }
  546. }