fading_app_bar.dart 14 KB

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