fading_app_bar.dart 16 KB

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