fading_app_bar.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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:page_transition/page_transition.dart';
  10. import 'package:path/path.dart' as file_path;
  11. import 'package:photo_manager/photo_manager.dart';
  12. import 'package:photos/core/event_bus.dart';
  13. import 'package:photos/db/files_db.dart';
  14. import 'package:photos/events/local_photos_updated_event.dart';
  15. import 'package:photos/models/file.dart';
  16. import 'package:photos/models/file_type.dart';
  17. import 'package:photos/models/ignored_file.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/common/progress_dialog.dart';
  26. import 'package:photos/ui/create_collection_page.dart';
  27. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  28. import 'package:photos/utils/delete_file_util.dart';
  29. import 'package:photos/utils/dialog_util.dart';
  30. import 'package:photos/utils/file_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) onFileDeleted;
  35. final double height;
  36. final bool shouldShowActions;
  37. final int userID;
  38. const FadingAppBar(
  39. this.file,
  40. this.onFileDeleted,
  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. height: 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.isRemoteFile;
  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. const Text("Download"),
  133. ],
  134. ),
  135. ),
  136. );
  137. }
  138. // options for files owned by the user
  139. if (isOwnedByUser) {
  140. items.add(
  141. PopupMenuItem(
  142. value: 2,
  143. child: Row(
  144. children: [
  145. Icon(
  146. Platform.isAndroid
  147. ? Icons.delete_outline
  148. : CupertinoIcons.delete,
  149. color: Theme.of(context).iconTheme.color,
  150. ),
  151. const Padding(
  152. padding: EdgeInsets.all(8),
  153. ),
  154. const Text("Delete"),
  155. ],
  156. ),
  157. ),
  158. );
  159. }
  160. if ((widget.file.fileType == FileType.image ||
  161. widget.file.fileType == FileType.livePhoto) &&
  162. Platform.isAndroid) {
  163. items.add(
  164. PopupMenuItem(
  165. value: 3,
  166. child: Row(
  167. children: [
  168. Icon(
  169. Icons.wallpaper_outlined,
  170. color: Theme.of(context).iconTheme.color,
  171. ),
  172. const Padding(
  173. padding: EdgeInsets.all(8),
  174. ),
  175. const Text("Set as"),
  176. ],
  177. ),
  178. ),
  179. );
  180. }
  181. if (isOwnedByUser && widget.file.isUploaded) {
  182. if (!isFileHidden) {
  183. items.add(
  184. PopupMenuItem(
  185. value: 4,
  186. child: Row(
  187. children: [
  188. Icon(
  189. Icons.visibility_off,
  190. color: Theme.of(context).iconTheme.color,
  191. ),
  192. const Padding(
  193. padding: EdgeInsets.all(8),
  194. ),
  195. const Text("Hide"),
  196. ],
  197. ),
  198. ),
  199. );
  200. } else {
  201. items.add(
  202. PopupMenuItem(
  203. value: 5,
  204. child: Row(
  205. children: [
  206. Icon(
  207. Icons.visibility,
  208. color: Theme.of(context).iconTheme.color,
  209. ),
  210. const Padding(
  211. padding: EdgeInsets.all(8),
  212. ),
  213. const Text("Unhide"),
  214. ],
  215. ),
  216. ),
  217. );
  218. }
  219. }
  220. return items;
  221. },
  222. onSelected: (value) {
  223. if (value == 1) {
  224. _download(widget.file);
  225. } else if (value == 2) {
  226. _showDeleteSheet(widget.file);
  227. } else if (value == 3) {
  228. _setAs(widget.file);
  229. } else if (value == 4) {
  230. _handleHideRequest(context);
  231. } else if (value == 5) {
  232. _handleUnHideRequest(context);
  233. }
  234. },
  235. ),
  236. );
  237. return AppBar(
  238. iconTheme:
  239. const IconThemeData(color: Colors.white), //same for both themes
  240. actions: shouldShowActions ? actions : [],
  241. elevation: 0,
  242. backgroundColor: const Color(0x00000000),
  243. );
  244. }
  245. Future<void> _handleHideRequest(BuildContext context) async {
  246. try {
  247. final hideResult =
  248. await CollectionsService.instance.hideFiles(context, [widget.file]);
  249. if (hideResult) {
  250. // delay to avoid black screen
  251. await Future.delayed(const Duration(milliseconds: 300));
  252. Navigator.of(context).pop();
  253. }
  254. } catch (e, s) {
  255. _logger.severe("failed to update file visibility", e, s);
  256. await showGenericErrorDialog(context);
  257. }
  258. }
  259. Future<void> _handleUnHideRequest(BuildContext context) async {
  260. final s = SelectedFiles();
  261. s.files.add(widget.file);
  262. Navigator.push(
  263. context,
  264. PageTransition(
  265. type: PageTransitionType.bottomToTop,
  266. child: CreateCollectionPage(
  267. s,
  268. null,
  269. actionType: CollectionActionType.unHide,
  270. ),
  271. ),
  272. );
  273. }
  274. Widget _getFavoriteButton() {
  275. return FutureBuilder(
  276. future: FavoritesService.instance.isFavorite(widget.file),
  277. builder: (context, snapshot) {
  278. if (snapshot.hasData) {
  279. return _getLikeButton(widget.file, snapshot.data);
  280. } else {
  281. return _getLikeButton(widget.file, false);
  282. }
  283. },
  284. );
  285. }
  286. Widget _getLikeButton(File file, bool isLiked) {
  287. return LikeButton(
  288. isLiked: isLiked,
  289. onTap: (oldValue) async {
  290. final isLiked = !oldValue;
  291. bool hasError = false;
  292. if (isLiked) {
  293. final shouldBlockUser = file.uploadedFileID == null;
  294. ProgressDialog dialog;
  295. if (shouldBlockUser) {
  296. dialog = createProgressDialog(context, "Adding to favorites...");
  297. await dialog.show();
  298. }
  299. try {
  300. await FavoritesService.instance.addToFavorites(file);
  301. } catch (e, s) {
  302. _logger.severe(e, s);
  303. hasError = true;
  304. showToast(context, "Sorry, could not add this to favorites!");
  305. } finally {
  306. if (shouldBlockUser) {
  307. await dialog.hide();
  308. }
  309. }
  310. } else {
  311. try {
  312. await FavoritesService.instance.removeFromFavorites(file);
  313. } catch (e, s) {
  314. _logger.severe(e, s);
  315. hasError = true;
  316. showToast(context, "Sorry, could not remove this from favorites!");
  317. }
  318. }
  319. return hasError ? oldValue : isLiked;
  320. },
  321. likeBuilder: (isLiked) {
  322. return Icon(
  323. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  324. color:
  325. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  326. size: 24,
  327. );
  328. },
  329. );
  330. }
  331. void _showDeleteSheet(File file) {
  332. final List<Widget> actions = [];
  333. if (file.uploadedFileID == null || file.localID == null) {
  334. actions.add(
  335. CupertinoActionSheetAction(
  336. isDestructiveAction: true,
  337. onPressed: () async {
  338. await deleteFilesFromEverywhere(context, [file]);
  339. Navigator.of(context, rootNavigator: true).pop();
  340. widget.onFileDeleted(file);
  341. },
  342. child: const Text("Everywhere"),
  343. ),
  344. );
  345. } else {
  346. // uploaded file which is present locally too
  347. actions.add(
  348. CupertinoActionSheetAction(
  349. isDestructiveAction: true,
  350. onPressed: () async {
  351. await deleteFilesOnDeviceOnly(context, [file]);
  352. showToast(context, "File deleted from device");
  353. Navigator.of(context, rootNavigator: true).pop();
  354. // TODO: Fix behavior when inside a device folder
  355. },
  356. child: const Text("Device"),
  357. ),
  358. );
  359. actions.add(
  360. CupertinoActionSheetAction(
  361. isDestructiveAction: true,
  362. onPressed: () async {
  363. await deleteFilesFromRemoteOnly(context, [file]);
  364. showShortToast(context, "Moved to trash");
  365. Navigator.of(context, rootNavigator: true).pop();
  366. // TODO: Fix behavior when inside a collection
  367. },
  368. child: const Text("ente"),
  369. ),
  370. );
  371. actions.add(
  372. CupertinoActionSheetAction(
  373. isDestructiveAction: true,
  374. onPressed: () async {
  375. await deleteFilesFromEverywhere(context, [file]);
  376. Navigator.of(context, rootNavigator: true).pop();
  377. widget.onFileDeleted(file);
  378. },
  379. child: const Text("Everywhere"),
  380. ),
  381. );
  382. }
  383. final action = CupertinoActionSheet(
  384. title: const Text("Delete file?"),
  385. actions: actions,
  386. cancelButton: CupertinoActionSheetAction(
  387. child: const Text("Cancel"),
  388. onPressed: () {
  389. Navigator.of(context, rootNavigator: true).pop();
  390. },
  391. ),
  392. );
  393. showCupertinoModalPopup(context: context, builder: (_) => action);
  394. }
  395. Future<void> _download(File file) async {
  396. final dialog = createProgressDialog(context, "Downloading...");
  397. await dialog.show();
  398. try {
  399. final FileType type = file.fileType;
  400. final bool downloadLivePhotoOnDroid =
  401. type == FileType.livePhoto && Platform.isAndroid;
  402. AssetEntity savedAsset;
  403. final io.File fileToSave = await getFile(file);
  404. if (type == FileType.image) {
  405. savedAsset = await PhotoManager.editor
  406. .saveImageWithPath(fileToSave.path, title: file.title);
  407. } else if (type == FileType.video) {
  408. savedAsset =
  409. await PhotoManager.editor.saveVideo(fileToSave, title: file.title);
  410. } else if (type == FileType.livePhoto) {
  411. final io.File liveVideoFile =
  412. await getFileFromServer(file, liveVideo: true);
  413. if (liveVideoFile == null) {
  414. throw AssertionError("Live video can not be null");
  415. }
  416. if (downloadLivePhotoOnDroid) {
  417. await _saveLivePhotoOnDroid(fileToSave, liveVideoFile, file);
  418. } else {
  419. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  420. imageFile: fileToSave,
  421. videoFile: liveVideoFile,
  422. title: file.title,
  423. );
  424. }
  425. }
  426. if (savedAsset != null) {
  427. // immediately track assetID to avoid duplicate upload
  428. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  429. final ignoreVideoFile = IgnoredFile(
  430. savedAsset.id,
  431. savedAsset.title ?? "",
  432. savedAsset.relativePath ?? 'remoteDownload',
  433. "remoteDownload",
  434. );
  435. debugPrint("IgnoreFile for auto-upload ${ignoreVideoFile.toString()}");
  436. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  437. file.localID = savedAsset.id;
  438. await FilesDB.instance.insert(file);
  439. Bus.instance.fire(LocalPhotosUpdatedEvent([file]));
  440. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  441. _logger.severe('Failed to save assert of type $type');
  442. }
  443. showToast(context, "File saved to gallery");
  444. await dialog.hide();
  445. } catch (e) {
  446. _logger.warning("Failed to save file", e);
  447. await dialog.hide();
  448. showGenericErrorDialog(context);
  449. }
  450. }
  451. Future<void> _saveLivePhotoOnDroid(
  452. io.File image,
  453. io.File video,
  454. File enteFile,
  455. ) async {
  456. debugPrint("Downloading LivePhoto on Droid");
  457. AssetEntity savedAsset = await PhotoManager.editor
  458. .saveImageWithPath(image.path, title: enteFile.title);
  459. IgnoredFile ignoreVideoFile = IgnoredFile(
  460. savedAsset.id,
  461. savedAsset.title ?? '',
  462. savedAsset.relativePath ?? 'remoteDownload',
  463. "remoteDownload",
  464. );
  465. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  466. final videoTitle = file_path.basenameWithoutExtension(enteFile.title) +
  467. file_path.extension(video.path);
  468. savedAsset = (await PhotoManager.editor.saveVideo(
  469. video,
  470. title: videoTitle,
  471. ));
  472. ignoreVideoFile = IgnoredFile(
  473. savedAsset.id,
  474. savedAsset.title ?? videoTitle,
  475. savedAsset.relativePath ?? 'remoteDownload',
  476. "remoteDownload",
  477. );
  478. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  479. }
  480. Future<void> _setAs(File file) async {
  481. final dialog = createProgressDialog(context, "Please wait...");
  482. await dialog.show();
  483. try {
  484. final io.File fileToSave = await getFile(file);
  485. final m = MediaExtension();
  486. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  487. if (result == false) {
  488. showShortToast(context, "Something went wrong");
  489. }
  490. dialog.hide();
  491. } catch (e) {
  492. dialog.hide();
  493. _logger.severe("Failed to use as", e);
  494. showGenericErrorDialog(context);
  495. }
  496. }
  497. }