fading_app_bar.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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: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/trash_file.dart';
  18. import 'package:photos/services/favorites_service.dart';
  19. import 'package:photos/services/ignored_files_service.dart';
  20. import 'package:photos/services/local_sync_service.dart';
  21. import 'package:photos/ui/common/progress_dialog.dart';
  22. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  23. import 'package:photos/utils/delete_file_util.dart';
  24. import 'package:photos/utils/dialog_util.dart';
  25. import 'package:photos/utils/file_util.dart';
  26. import 'package:photos/utils/toast_util.dart';
  27. class FadingAppBar extends StatefulWidget implements PreferredSizeWidget {
  28. final File file;
  29. final Function(File) onFileDeleted;
  30. final double height;
  31. final bool shouldShowActions;
  32. final int userID;
  33. const FadingAppBar(
  34. this.file,
  35. this.onFileDeleted,
  36. this.userID,
  37. this.height,
  38. this.shouldShowActions, {
  39. Key key,
  40. }) : super(key: key);
  41. @override
  42. Size get preferredSize => Size.fromHeight(height);
  43. @override
  44. FadingAppBarState createState() => FadingAppBarState();
  45. }
  46. class FadingAppBarState extends State<FadingAppBar> {
  47. final _logger = Logger("FadingAppBar");
  48. bool _shouldHide = false;
  49. @override
  50. Widget build(BuildContext context) {
  51. return CustomAppBar(
  52. IgnorePointer(
  53. ignoring: _shouldHide,
  54. child: AnimatedOpacity(
  55. opacity: _shouldHide ? 0 : 1,
  56. duration: const Duration(milliseconds: 150),
  57. child: Container(
  58. decoration: BoxDecoration(
  59. gradient: LinearGradient(
  60. begin: Alignment.topCenter,
  61. end: Alignment.bottomCenter,
  62. colors: [
  63. Colors.black.withOpacity(0.72),
  64. Colors.black.withOpacity(0.6),
  65. Colors.transparent,
  66. ],
  67. stops: const [0, 0.2, 1],
  68. ),
  69. ),
  70. child: _buildAppBar(),
  71. ),
  72. ),
  73. ),
  74. height: Platform.isAndroid ? 80 : 96,
  75. );
  76. }
  77. void hide() {
  78. setState(() {
  79. _shouldHide = true;
  80. });
  81. }
  82. void show() {
  83. if (mounted) {
  84. setState(() {
  85. _shouldHide = false;
  86. });
  87. }
  88. }
  89. AppBar _buildAppBar() {
  90. debugPrint("building app bar");
  91. final List<Widget> actions = [];
  92. final isTrashedFile = widget.file is TrashFile;
  93. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  94. // only show fav option for files owned by the user
  95. if (widget.file.ownerID == null || widget.file.ownerID == widget.userID) {
  96. actions.add(_getFavoriteButton());
  97. }
  98. actions.add(
  99. PopupMenuButton(
  100. itemBuilder: (context) {
  101. final List<PopupMenuItem> items = [];
  102. if (widget.file.isRemoteFile) {
  103. items.add(
  104. PopupMenuItem(
  105. value: 1,
  106. child: Row(
  107. children: [
  108. Icon(
  109. Platform.isAndroid
  110. ? Icons.download
  111. : CupertinoIcons.cloud_download,
  112. color: Theme.of(context).iconTheme.color,
  113. ),
  114. const Padding(
  115. padding: EdgeInsets.all(8),
  116. ),
  117. const Text("Download"),
  118. ],
  119. ),
  120. ),
  121. );
  122. }
  123. // options for files owned by the user
  124. if (widget.file.ownerID == null ||
  125. widget.file.ownerID == widget.userID) {
  126. items.add(
  127. PopupMenuItem(
  128. value: 2,
  129. child: Row(
  130. children: [
  131. Icon(
  132. Platform.isAndroid
  133. ? Icons.delete_outline
  134. : CupertinoIcons.delete,
  135. color: Theme.of(context).iconTheme.color,
  136. ),
  137. const Padding(
  138. padding: EdgeInsets.all(8),
  139. ),
  140. const Text("Delete"),
  141. ],
  142. ),
  143. ),
  144. );
  145. }
  146. if ((widget.file.fileType == FileType.image ||
  147. widget.file.fileType == FileType.livePhoto) &&
  148. Platform.isAndroid) {
  149. items.add(
  150. PopupMenuItem(
  151. value: 3,
  152. child: Row(
  153. children: [
  154. Icon(
  155. Icons.wallpaper_outlined,
  156. color: Theme.of(context).iconTheme.color,
  157. ),
  158. const Padding(
  159. padding: EdgeInsets.all(8),
  160. ),
  161. const Text("Use as"),
  162. ],
  163. ),
  164. ),
  165. );
  166. }
  167. return items;
  168. },
  169. onSelected: (value) {
  170. if (value == 1) {
  171. _download(widget.file);
  172. } else if (value == 2) {
  173. _showDeleteSheet(widget.file);
  174. } else if (value == 3) {
  175. _setAs(widget.file);
  176. }
  177. },
  178. ),
  179. );
  180. return AppBar(
  181. iconTheme:
  182. const IconThemeData(color: Colors.white), //same for both themes
  183. actions: shouldShowActions ? actions : [],
  184. elevation: 0,
  185. backgroundColor: const Color(0x00000000),
  186. );
  187. }
  188. Widget _getFavoriteButton() {
  189. return FutureBuilder(
  190. future: FavoritesService.instance.isFavorite(widget.file),
  191. builder: (context, snapshot) {
  192. if (snapshot.hasData) {
  193. return _getLikeButton(widget.file, snapshot.data);
  194. } else {
  195. return _getLikeButton(widget.file, false);
  196. }
  197. },
  198. );
  199. }
  200. Widget _getLikeButton(File file, bool isLiked) {
  201. return LikeButton(
  202. isLiked: isLiked,
  203. onTap: (oldValue) async {
  204. final isLiked = !oldValue;
  205. bool hasError = false;
  206. if (isLiked) {
  207. final shouldBlockUser = file.uploadedFileID == null;
  208. ProgressDialog dialog;
  209. if (shouldBlockUser) {
  210. dialog = createProgressDialog(context, "Adding to favorites...");
  211. await dialog.show();
  212. }
  213. try {
  214. await FavoritesService.instance.addToFavorites(file);
  215. } catch (e, s) {
  216. _logger.severe(e, s);
  217. hasError = true;
  218. showToast(context, "Sorry, could not add this to favorites!");
  219. } finally {
  220. if (shouldBlockUser) {
  221. await dialog.hide();
  222. }
  223. }
  224. } else {
  225. try {
  226. await FavoritesService.instance.removeFromFavorites(file);
  227. } catch (e, s) {
  228. _logger.severe(e, s);
  229. hasError = true;
  230. showToast(context, "Sorry, could not remove this from favorites!");
  231. }
  232. }
  233. return hasError ? oldValue : isLiked;
  234. },
  235. likeBuilder: (isLiked) {
  236. return Icon(
  237. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  238. color:
  239. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  240. size: 24,
  241. );
  242. },
  243. );
  244. }
  245. void _showDeleteSheet(File file) {
  246. final List<Widget> actions = [];
  247. if (file.uploadedFileID == null || file.localID == null) {
  248. actions.add(
  249. CupertinoActionSheetAction(
  250. isDestructiveAction: true,
  251. onPressed: () async {
  252. await deleteFilesFromEverywhere(context, [file]);
  253. Navigator.of(context, rootNavigator: true).pop();
  254. widget.onFileDeleted(file);
  255. },
  256. child: const Text("Everywhere"),
  257. ),
  258. );
  259. } else {
  260. // uploaded file which is present locally too
  261. actions.add(
  262. CupertinoActionSheetAction(
  263. isDestructiveAction: true,
  264. onPressed: () async {
  265. await deleteFilesOnDeviceOnly(context, [file]);
  266. showToast(context, "File deleted from device");
  267. Navigator.of(context, rootNavigator: true).pop();
  268. // TODO: Fix behavior when inside a device folder
  269. },
  270. child: const Text("Device"),
  271. ),
  272. );
  273. actions.add(
  274. CupertinoActionSheetAction(
  275. isDestructiveAction: true,
  276. onPressed: () async {
  277. await deleteFilesFromRemoteOnly(context, [file]);
  278. showShortToast(context, "Moved to trash");
  279. Navigator.of(context, rootNavigator: true).pop();
  280. // TODO: Fix behavior when inside a collection
  281. },
  282. child: const Text("ente"),
  283. ),
  284. );
  285. actions.add(
  286. CupertinoActionSheetAction(
  287. isDestructiveAction: true,
  288. onPressed: () async {
  289. await deleteFilesFromEverywhere(context, [file]);
  290. Navigator.of(context, rootNavigator: true).pop();
  291. widget.onFileDeleted(file);
  292. },
  293. child: const Text("Everywhere"),
  294. ),
  295. );
  296. }
  297. final action = CupertinoActionSheet(
  298. title: const Text("Delete file?"),
  299. actions: actions,
  300. cancelButton: CupertinoActionSheetAction(
  301. child: const Text("Cancel"),
  302. onPressed: () {
  303. Navigator.of(context, rootNavigator: true).pop();
  304. },
  305. ),
  306. );
  307. showCupertinoModalPopup(context: context, builder: (_) => action);
  308. }
  309. Future<void> _download(File file) async {
  310. final dialog = createProgressDialog(context, "Downloading...");
  311. await dialog.show();
  312. final FileType type = file.fileType;
  313. // save and track image for livePhoto/image and video for FileType.video
  314. final io.File fileToSave = await getFile(file);
  315. final savedAsset = type == FileType.video
  316. ? (await PhotoManager.editor.saveVideo(fileToSave, title: file.title))
  317. : (await PhotoManager.editor
  318. .saveImageWithPath(fileToSave.path, title: file.title));
  319. // immediately track assetID to avoid duplicate upload
  320. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  321. file.localID = savedAsset.id;
  322. await FilesDB.instance.insert(file);
  323. if (type == FileType.livePhoto) {
  324. final io.File liveVideo = await getFileFromServer(file, liveVideo: true);
  325. if (liveVideo == null) {
  326. _logger.warning("Failed to find live video" + file.tag);
  327. } else {
  328. final videoTitle = file_path.basenameWithoutExtension(file.title) +
  329. file_path.extension(liveVideo.path);
  330. final savedAsset = (await PhotoManager.editor.saveVideo(
  331. liveVideo,
  332. title: videoTitle,
  333. ));
  334. final ignoreVideoFile = IgnoredFile(
  335. savedAsset.id,
  336. savedAsset.title ?? videoTitle,
  337. savedAsset.relativePath ?? 'remoteDownload',
  338. "remoteDownload",
  339. );
  340. debugPrint("IgnoreFile for auto-upload ${ignoreVideoFile.toString()}");
  341. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  342. }
  343. }
  344. Bus.instance.fire(LocalPhotosUpdatedEvent([file]));
  345. await dialog.hide();
  346. if (file.fileType == FileType.livePhoto) {
  347. showToast(context, "Photo and video saved to gallery");
  348. } else {
  349. showToast(context, "File saved to gallery");
  350. }
  351. }
  352. Future<void> _setAs(File file) async {
  353. final dialog = createProgressDialog(context, "Please wait...");
  354. await dialog.show();
  355. try {
  356. final io.File fileToSave = await getFile(file);
  357. var m = MediaExtension();
  358. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  359. if (result == false) {
  360. showShortToast(context, "Something went wrong");
  361. }
  362. dialog.hide();
  363. } catch (e) {
  364. dialog.hide();
  365. _logger.severe("Failed to use as", e);
  366. showGenericErrorDialog(context);
  367. }
  368. }
  369. }