fading_app_bar.dart 16 KB

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