fading_app_bar.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/generated/l10n.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/magic_metadata.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/collection_action_sheet.dart';
  26. import 'package:photos/ui/common/progress_dialog.dart';
  27. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  28. import 'package:photos/utils/dialog_util.dart';
  29. import 'package:photos/utils/file_util.dart';
  30. import "package:photos/utils/magic_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. Size.fromHeight(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. Text(S.of(context).download),
  133. ],
  134. ),
  135. ),
  136. );
  137. }
  138. // options for files owned by the user
  139. if (isOwnedByUser && !isFileHidden) {
  140. final bool isArchived =
  141. widget.file.magicMetadata.visibility == visibilityArchive;
  142. items.add(
  143. PopupMenuItem(
  144. value: 2,
  145. child: Row(
  146. children: [
  147. Icon(
  148. isArchived ? Icons.unarchive : Icons.archive_outlined,
  149. color: Theme.of(context).iconTheme.color,
  150. ),
  151. const Padding(
  152. padding: EdgeInsets.all(8),
  153. ),
  154. Text(
  155. isArchived
  156. ? S.of(context).unarchive
  157. : S.of(context).archive,
  158. ),
  159. ],
  160. ),
  161. ),
  162. );
  163. }
  164. if ((widget.file.fileType == FileType.image ||
  165. widget.file.fileType == FileType.livePhoto) &&
  166. Platform.isAndroid) {
  167. items.add(
  168. PopupMenuItem(
  169. value: 3,
  170. child: Row(
  171. children: [
  172. Icon(
  173. Icons.wallpaper_outlined,
  174. color: Theme.of(context).iconTheme.color,
  175. ),
  176. const Padding(
  177. padding: EdgeInsets.all(8),
  178. ),
  179. Text(S.of(context).setAs),
  180. ],
  181. ),
  182. ),
  183. );
  184. }
  185. if (isOwnedByUser && widget.file.isUploaded) {
  186. if (!isFileHidden) {
  187. items.add(
  188. PopupMenuItem(
  189. value: 4,
  190. child: Row(
  191. children: [
  192. Icon(
  193. Icons.visibility_off,
  194. color: Theme.of(context).iconTheme.color,
  195. ),
  196. const Padding(
  197. padding: EdgeInsets.all(8),
  198. ),
  199. Text(S.of(context).hide),
  200. ],
  201. ),
  202. ),
  203. );
  204. } else {
  205. items.add(
  206. PopupMenuItem(
  207. value: 5,
  208. child: Row(
  209. children: [
  210. Icon(
  211. Icons.visibility,
  212. color: Theme.of(context).iconTheme.color,
  213. ),
  214. const Padding(
  215. padding: EdgeInsets.all(8),
  216. ),
  217. Text(S.of(context).unhide),
  218. ],
  219. ),
  220. ),
  221. );
  222. }
  223. }
  224. return items;
  225. },
  226. onSelected: (dynamic value) async {
  227. if (value == 1) {
  228. _download(widget.file);
  229. } else if (value == 2) {
  230. await _toggleFileArchiveStatus(widget.file);
  231. } else if (value == 3) {
  232. _setAs(widget.file);
  233. } else if (value == 4) {
  234. _handleHideRequest(context);
  235. } else if (value == 5) {
  236. _handleUnHideRequest(context);
  237. }
  238. },
  239. ),
  240. );
  241. return AppBar(
  242. iconTheme:
  243. const IconThemeData(color: Colors.white), //same for both themes
  244. actions: shouldShowActions ? actions : [],
  245. elevation: 0,
  246. backgroundColor: const Color(0x00000000),
  247. );
  248. }
  249. Future<void> _handleHideRequest(BuildContext context) async {
  250. try {
  251. final hideResult =
  252. await CollectionsService.instance.hideFiles(context, [widget.file]);
  253. if (hideResult) {
  254. widget.onFileRemoved(widget.file);
  255. }
  256. } catch (e, s) {
  257. _logger.severe("failed to update file visibility", e, s);
  258. await showGenericErrorDialog(context: context);
  259. }
  260. }
  261. Future<void> _handleUnHideRequest(BuildContext context) async {
  262. final selectedFiles = SelectedFiles();
  263. selectedFiles.files.add(widget.file);
  264. showCollectionActionSheet(
  265. context,
  266. selectedFiles: selectedFiles,
  267. actionType: CollectionActionType.unHide,
  268. );
  269. }
  270. Widget _getFavoriteButton() {
  271. return FutureBuilder<bool>(
  272. future: FavoritesService.instance.isFavorite(widget.file),
  273. builder: (context, snapshot) {
  274. if (snapshot.hasData) {
  275. return _getLikeButton(widget.file, snapshot.data);
  276. } else {
  277. return _getLikeButton(widget.file, false);
  278. }
  279. },
  280. );
  281. }
  282. Widget _getLikeButton(File file, bool? isLiked) {
  283. return LikeButton(
  284. isLiked: isLiked,
  285. onTap: (oldValue) async {
  286. final isLiked = !oldValue;
  287. bool hasError = false;
  288. if (isLiked) {
  289. final shouldBlockUser = file.uploadedFileID == null;
  290. late ProgressDialog dialog;
  291. if (shouldBlockUser) {
  292. dialog =
  293. createProgressDialog(context, S.of(context).addingToFavorites);
  294. await dialog.show();
  295. }
  296. try {
  297. await FavoritesService.instance.addToFavorites(context, file);
  298. } catch (e, s) {
  299. _logger.severe(e, s);
  300. hasError = true;
  301. showToast(context, S.of(context).sorryCouldNotAddToFavorites);
  302. } finally {
  303. if (shouldBlockUser) {
  304. await dialog.hide();
  305. }
  306. }
  307. } else {
  308. try {
  309. await FavoritesService.instance.removeFromFavorites(context, file);
  310. } catch (e, s) {
  311. _logger.severe(e, s);
  312. hasError = true;
  313. showToast(context, S.of(context).sorryCouldNotRemoveFromFavorites);
  314. }
  315. }
  316. return hasError ? oldValue : isLiked;
  317. },
  318. likeBuilder: (isLiked) {
  319. return Icon(
  320. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  321. color:
  322. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  323. size: 24,
  324. );
  325. },
  326. );
  327. }
  328. Future<void> _toggleFileArchiveStatus(File file) async {
  329. final bool isArchived =
  330. widget.file.magicMetadata.visibility == visibilityArchive;
  331. await changeVisibility(
  332. context,
  333. [widget.file],
  334. isArchived ? visibilityVisible : visibilityArchive,
  335. );
  336. if (mounted) {
  337. setState(() {});
  338. }
  339. }
  340. Future<void> _download(File file) async {
  341. final dialog = createProgressDialog(context, "Downloading...");
  342. await dialog.show();
  343. try {
  344. final FileType type = file.fileType;
  345. final bool downloadLivePhotoOnDroid =
  346. type == FileType.livePhoto && Platform.isAndroid;
  347. AssetEntity? savedAsset;
  348. final io.File? fileToSave = await getFile(file);
  349. //Disabling notifications for assets changing to insert the file into
  350. //files db before triggering a sync.
  351. PhotoManager.stopChangeNotify();
  352. if (type == FileType.image) {
  353. savedAsset = await PhotoManager.editor
  354. .saveImageWithPath(fileToSave!.path, title: file.title!);
  355. } else if (type == FileType.video) {
  356. savedAsset = await PhotoManager.editor
  357. .saveVideo(fileToSave!, title: file.title!);
  358. } else if (type == FileType.livePhoto) {
  359. final io.File? liveVideoFile =
  360. await getFileFromServer(file, liveVideo: true);
  361. if (liveVideoFile == null) {
  362. throw AssertionError("Live video can not be null");
  363. }
  364. if (downloadLivePhotoOnDroid) {
  365. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  366. } else {
  367. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  368. imageFile: fileToSave!,
  369. videoFile: liveVideoFile,
  370. title: file.title!,
  371. );
  372. }
  373. }
  374. if (savedAsset != null) {
  375. file.localID = savedAsset.id;
  376. await FilesDB.instance.insert(file);
  377. Bus.instance.fire(
  378. LocalPhotosUpdatedEvent(
  379. [file],
  380. source: "download",
  381. ),
  382. );
  383. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  384. _logger.severe('Failed to save assert of type $type');
  385. }
  386. showToast(context, S.of(context).fileSavedToGallery);
  387. await dialog.hide();
  388. } catch (e) {
  389. _logger.warning("Failed to save file", e);
  390. await dialog.hide();
  391. showGenericErrorDialog(context: context);
  392. } finally {
  393. PhotoManager.startChangeNotify();
  394. LocalSyncService.instance.checkAndSync().ignore();
  395. }
  396. }
  397. Future<void> _saveLivePhotoOnDroid(
  398. io.File image,
  399. io.File video,
  400. File enteFile,
  401. ) async {
  402. debugPrint("Downloading LivePhoto on Droid");
  403. AssetEntity? savedAsset = await (PhotoManager.editor
  404. .saveImageWithPath(image.path, title: enteFile.title!));
  405. if (savedAsset == null) {
  406. throw Exception("Failed to save image of live photo");
  407. }
  408. IgnoredFile ignoreVideoFile = IgnoredFile(
  409. savedAsset.id,
  410. savedAsset.title ?? '',
  411. savedAsset.relativePath ?? 'remoteDownload',
  412. "remoteDownload",
  413. );
  414. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  415. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  416. file_path.extension(video.path);
  417. savedAsset = (await (PhotoManager.editor.saveVideo(
  418. video,
  419. title: videoTitle,
  420. )));
  421. if (savedAsset == null) {
  422. throw Exception("Failed to save video of live photo");
  423. }
  424. ignoreVideoFile = IgnoredFile(
  425. savedAsset.id,
  426. savedAsset.title ?? videoTitle,
  427. savedAsset.relativePath ?? 'remoteDownload',
  428. "remoteDownload",
  429. );
  430. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  431. }
  432. Future<void> _setAs(File file) async {
  433. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  434. await dialog.show();
  435. try {
  436. final io.File? fileToSave = await (getFile(file));
  437. if (fileToSave == null) {
  438. throw Exception("Fail to get file for setAs operation");
  439. }
  440. final m = MediaExtension();
  441. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  442. if (result == false) {
  443. showShortToast(context, S.of(context).somethingWentWrong);
  444. }
  445. dialog.hide();
  446. } catch (e) {
  447. dialog.hide();
  448. _logger.severe("Failed to use as", e);
  449. showGenericErrorDialog(context: context);
  450. }
  451. }
  452. }