fading_app_bar.dart 15 KB

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