fading_app_bar.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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(isArchived
  155. ? S.of(context).unarchive
  156. : S.of(context).archive),
  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. Text(S.of(context).setAs),
  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. Text(S.of(context).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. Text(S.of(context).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 _toggleFileArchiveStatus(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 selectedFiles = SelectedFiles();
  261. selectedFiles.files.add(widget.file);
  262. showCollectionActionSheet(
  263. context,
  264. selectedFiles: selectedFiles,
  265. actionType: CollectionActionType.unHide,
  266. );
  267. }
  268. Widget _getFavoriteButton() {
  269. return FutureBuilder<bool>(
  270. future: FavoritesService.instance.isFavorite(widget.file),
  271. builder: (context, snapshot) {
  272. if (snapshot.hasData) {
  273. return _getLikeButton(widget.file, snapshot.data);
  274. } else {
  275. return _getLikeButton(widget.file, false);
  276. }
  277. },
  278. );
  279. }
  280. Widget _getLikeButton(File file, bool? isLiked) {
  281. return LikeButton(
  282. isLiked: isLiked,
  283. onTap: (oldValue) async {
  284. final isLiked = !oldValue;
  285. bool hasError = false;
  286. if (isLiked) {
  287. final shouldBlockUser = file.uploadedFileID == null;
  288. late ProgressDialog dialog;
  289. if (shouldBlockUser) {
  290. dialog =
  291. createProgressDialog(context, S.of(context).addingToFavorites);
  292. await dialog.show();
  293. }
  294. try {
  295. await FavoritesService.instance.addToFavorites(context, file);
  296. } catch (e, s) {
  297. _logger.severe(e, s);
  298. hasError = true;
  299. showToast(context, S.of(context).sorryCouldNotAddToFavorites);
  300. } finally {
  301. if (shouldBlockUser) {
  302. await dialog.hide();
  303. }
  304. }
  305. } else {
  306. try {
  307. await FavoritesService.instance.removeFromFavorites(context, file);
  308. } catch (e, s) {
  309. _logger.severe(e, s);
  310. hasError = true;
  311. showToast(context, S.of(context).sorryCouldNotRemoveFromFavorites);
  312. }
  313. }
  314. return hasError ? oldValue : isLiked;
  315. },
  316. likeBuilder: (isLiked) {
  317. return Icon(
  318. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  319. color:
  320. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  321. size: 24,
  322. );
  323. },
  324. );
  325. }
  326. Future<void> _toggleFileArchiveStatus(File file) async {
  327. final bool isArchived =
  328. widget.file.magicMetadata.visibility == visibilityArchive;
  329. await changeVisibility(
  330. context,
  331. [widget.file],
  332. isArchived ? visibilityVisible : visibilityArchive,
  333. );
  334. if (mounted) {
  335. setState(() {});
  336. }
  337. }
  338. Future<void> _download(File file) async {
  339. final dialog = createProgressDialog(context, "Downloading...");
  340. await dialog.show();
  341. try {
  342. final FileType type = file.fileType;
  343. final bool downloadLivePhotoOnDroid =
  344. type == FileType.livePhoto && Platform.isAndroid;
  345. AssetEntity? savedAsset;
  346. final io.File? fileToSave = await getFile(file);
  347. //Disabling notifications for assets changing to insert the file into
  348. //files db before triggering a sync.
  349. PhotoManager.stopChangeNotify();
  350. if (type == FileType.image) {
  351. savedAsset = await PhotoManager.editor
  352. .saveImageWithPath(fileToSave!.path, title: file.title!);
  353. } else if (type == FileType.video) {
  354. savedAsset = await PhotoManager.editor
  355. .saveVideo(fileToSave!, title: file.title!);
  356. } else if (type == FileType.livePhoto) {
  357. final io.File? liveVideoFile =
  358. await getFileFromServer(file, liveVideo: true);
  359. if (liveVideoFile == null) {
  360. throw AssertionError("Live video can not be null");
  361. }
  362. if (downloadLivePhotoOnDroid) {
  363. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  364. } else {
  365. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  366. imageFile: fileToSave!,
  367. videoFile: liveVideoFile,
  368. title: file.title!,
  369. );
  370. }
  371. }
  372. if (savedAsset != null) {
  373. file.localID = savedAsset.id;
  374. await FilesDB.instance.insert(file);
  375. Bus.instance.fire(
  376. LocalPhotosUpdatedEvent(
  377. [file],
  378. source: "download",
  379. ),
  380. );
  381. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  382. _logger.severe('Failed to save assert of type $type');
  383. }
  384. showToast(context, S.of(context).fileSavedToGallery);
  385. await dialog.hide();
  386. } catch (e) {
  387. _logger.warning("Failed to save file", e);
  388. await dialog.hide();
  389. showGenericErrorDialog(context: context);
  390. } finally {
  391. PhotoManager.startChangeNotify();
  392. LocalSyncService.instance.checkAndSync().ignore();
  393. }
  394. }
  395. Future<void> _saveLivePhotoOnDroid(
  396. io.File image,
  397. io.File video,
  398. File enteFile,
  399. ) async {
  400. debugPrint("Downloading LivePhoto on Droid");
  401. AssetEntity? savedAsset = await (PhotoManager.editor
  402. .saveImageWithPath(image.path, title: enteFile.title!));
  403. if (savedAsset == null) {
  404. throw Exception("Failed to save image of live photo");
  405. }
  406. IgnoredFile ignoreVideoFile = IgnoredFile(
  407. savedAsset.id,
  408. savedAsset.title ?? '',
  409. savedAsset.relativePath ?? 'remoteDownload',
  410. "remoteDownload",
  411. );
  412. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  413. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  414. file_path.extension(video.path);
  415. savedAsset = (await (PhotoManager.editor.saveVideo(
  416. video,
  417. title: videoTitle,
  418. )));
  419. if (savedAsset == null) {
  420. throw Exception("Failed to save video of live photo");
  421. }
  422. ignoreVideoFile = IgnoredFile(
  423. savedAsset.id,
  424. savedAsset.title ?? videoTitle,
  425. savedAsset.relativePath ?? 'remoteDownload',
  426. "remoteDownload",
  427. );
  428. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  429. }
  430. Future<void> _setAs(File file) async {
  431. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  432. await dialog.show();
  433. try {
  434. final io.File? fileToSave = await (getFile(file));
  435. if (fileToSave == null) {
  436. throw Exception("Fail to get file for setAs operation");
  437. }
  438. final m = MediaExtension();
  439. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  440. if (result == false) {
  441. showShortToast(context, S.of(context).somethingWentWrong);
  442. }
  443. dialog.hide();
  444. } catch (e) {
  445. dialog.hide();
  446. _logger.severe("Failed to use as", e);
  447. showGenericErrorDialog(context: context);
  448. }
  449. }
  450. }