file_app_bar.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import 'dart:io';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:logging/logging.dart';
  5. import 'package:media_extension/media_extension.dart';
  6. import 'package:path/path.dart' as file_path;
  7. import 'package:photo_manager/photo_manager.dart';
  8. import 'package:photos/core/event_bus.dart';
  9. import 'package:photos/db/files_db.dart';
  10. import 'package:photos/events/local_photos_updated_event.dart';
  11. import "package:photos/generated/l10n.dart";
  12. import "package:photos/l10n/l10n.dart";
  13. import "package:photos/models/file/extensions/file_props.dart";
  14. import 'package:photos/models/file/file.dart';
  15. import 'package:photos/models/file/file_type.dart';
  16. import 'package:photos/models/file/trash_file.dart';
  17. import 'package:photos/models/ignored_file.dart';
  18. import "package:photos/models/metadata/common_keys.dart";
  19. import 'package:photos/models/selected_files.dart';
  20. import "package:photos/service_locator.dart";
  21. import 'package:photos/services/collections_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/collections/collection_action_sheet.dart';
  26. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  27. import "package:photos/ui/viewer/file_details/favorite_widget.dart";
  28. import "package:photos/ui/viewer/file_details/upload_icon_widget.dart";
  29. import 'package:photos/utils/dialog_util.dart';
  30. import 'package:photos/utils/file_util.dart';
  31. import "package:photos/utils/magic_util.dart";
  32. import 'package:photos/utils/toast_util.dart';
  33. class FileAppBar extends StatefulWidget {
  34. final EnteFile file;
  35. final Function(EnteFile) onFileRemoved;
  36. final double height;
  37. final bool shouldShowActions;
  38. final ValueNotifier<bool> enableFullScreenNotifier;
  39. const FileAppBar(
  40. this.file,
  41. this.onFileRemoved,
  42. this.height,
  43. this.shouldShowActions, {
  44. required this.enableFullScreenNotifier,
  45. Key? key,
  46. }) : super(key: key);
  47. @override
  48. FileAppBarState createState() => FileAppBarState();
  49. }
  50. class FileAppBarState extends State<FileAppBar> {
  51. final _logger = Logger("FadingAppBar");
  52. final List<Widget> _actions = [];
  53. @override
  54. void didUpdateWidget(FileAppBar oldWidget) {
  55. super.didUpdateWidget(oldWidget);
  56. if (oldWidget.file.generatedID != widget.file.generatedID) {
  57. _getActions();
  58. }
  59. }
  60. @override
  61. Widget build(BuildContext context) {
  62. _logger.fine("building app bar ${widget.file.generatedID?.toString()}");
  63. //When the widget is initialized, the actions are not available.
  64. //Cannot call _getActions() in initState.
  65. if (_actions.isEmpty) {
  66. _getActions();
  67. }
  68. final isTrashedFile = widget.file is TrashFile;
  69. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  70. return CustomAppBar(
  71. ValueListenableBuilder(
  72. valueListenable: widget.enableFullScreenNotifier,
  73. builder: (context, bool isFullScreen, child) {
  74. return IgnorePointer(
  75. ignoring: isFullScreen,
  76. child: AnimatedOpacity(
  77. opacity: isFullScreen ? 0 : 1,
  78. duration: const Duration(milliseconds: 150),
  79. child: child,
  80. ),
  81. );
  82. },
  83. child: Container(
  84. decoration: BoxDecoration(
  85. gradient: LinearGradient(
  86. begin: Alignment.topCenter,
  87. end: Alignment.bottomCenter,
  88. colors: [
  89. Colors.black.withOpacity(0.72),
  90. Colors.black.withOpacity(0.6),
  91. Colors.transparent,
  92. ],
  93. stops: const [0, 0.2, 1],
  94. ),
  95. ),
  96. child: AppBar(
  97. iconTheme: const IconThemeData(
  98. color: Colors.white,
  99. ), //same for both themes
  100. actions: shouldShowActions ? _actions : [],
  101. elevation: 0,
  102. backgroundColor: const Color(0x00000000),
  103. ),
  104. ),
  105. ),
  106. Size.fromHeight(Platform.isAndroid ? 84 : 96),
  107. );
  108. }
  109. List<Widget> _getActions() {
  110. _actions.clear();
  111. final bool isOwnedByUser = widget.file.isOwner;
  112. final bool isFileUploaded = widget.file.isUploaded;
  113. bool isFileHidden = false;
  114. if (isOwnedByUser && isFileUploaded) {
  115. isFileHidden = CollectionsService.instance
  116. .getCollectionByID(widget.file.collectionID!)
  117. ?.isHidden() ??
  118. false;
  119. }
  120. if (widget.file.isLiveOrMotionPhoto) {
  121. _actions.add(
  122. IconButton(
  123. icon: const Icon(Icons.album_outlined),
  124. onPressed: () {
  125. showShortToast(
  126. context,
  127. S.of(context).pressAndHoldToPlayVideoDetailed,
  128. );
  129. },
  130. ),
  131. );
  132. }
  133. // only show fav option for files owned by the user
  134. if ((isOwnedByUser || flagService.internalUser) &&
  135. !isFileHidden &&
  136. isFileUploaded) {
  137. _actions.add(FavoriteWidget(widget.file));
  138. }
  139. if (!isFileUploaded) {
  140. _actions.add(
  141. UploadIconWidget(
  142. file: widget.file,
  143. key: ValueKey(widget.file.tag),
  144. ),
  145. );
  146. }
  147. final List<PopupMenuItem> items = [];
  148. if (widget.file.isRemoteFile) {
  149. items.add(
  150. PopupMenuItem(
  151. value: 1,
  152. child: Row(
  153. children: [
  154. Icon(
  155. Platform.isAndroid
  156. ? Icons.download
  157. : CupertinoIcons.cloud_download,
  158. color: Theme.of(context).iconTheme.color,
  159. ),
  160. const Padding(
  161. padding: EdgeInsets.all(8),
  162. ),
  163. Text(S.of(context).download),
  164. ],
  165. ),
  166. ),
  167. );
  168. }
  169. // options for files owned by the user
  170. if (isOwnedByUser && !isFileHidden && isFileUploaded) {
  171. final bool isArchived =
  172. widget.file.magicMetadata.visibility == archiveVisibility;
  173. items.add(
  174. PopupMenuItem(
  175. value: 2,
  176. child: Row(
  177. children: [
  178. Icon(
  179. isArchived ? Icons.unarchive : Icons.archive_outlined,
  180. color: Theme.of(context).iconTheme.color,
  181. ),
  182. const Padding(
  183. padding: EdgeInsets.all(8),
  184. ),
  185. Text(
  186. isArchived ? S.of(context).unarchive : S.of(context).archive,
  187. ),
  188. ],
  189. ),
  190. ),
  191. );
  192. }
  193. if ((widget.file.fileType == FileType.image ||
  194. widget.file.fileType == FileType.livePhoto) &&
  195. Platform.isAndroid) {
  196. items.add(
  197. PopupMenuItem(
  198. value: 3,
  199. child: Row(
  200. children: [
  201. Icon(
  202. Icons.wallpaper_outlined,
  203. color: Theme.of(context).iconTheme.color,
  204. ),
  205. const Padding(
  206. padding: EdgeInsets.all(8),
  207. ),
  208. Text(S.of(context).setAs),
  209. ],
  210. ),
  211. ),
  212. );
  213. }
  214. if (isOwnedByUser && widget.file.isUploaded) {
  215. if (!isFileHidden) {
  216. items.add(
  217. PopupMenuItem(
  218. value: 4,
  219. child: Row(
  220. children: [
  221. Icon(
  222. Icons.visibility_off,
  223. color: Theme.of(context).iconTheme.color,
  224. ),
  225. const Padding(
  226. padding: EdgeInsets.all(8),
  227. ),
  228. Text(S.of(context).hide),
  229. ],
  230. ),
  231. ),
  232. );
  233. } else {
  234. items.add(
  235. PopupMenuItem(
  236. value: 5,
  237. child: Row(
  238. children: [
  239. Icon(
  240. Icons.visibility,
  241. color: Theme.of(context).iconTheme.color,
  242. ),
  243. const Padding(
  244. padding: EdgeInsets.all(8),
  245. ),
  246. Text(S.of(context).unhide),
  247. ],
  248. ),
  249. ),
  250. );
  251. }
  252. }
  253. if (items.isNotEmpty) {
  254. _actions.add(
  255. PopupMenuButton(
  256. itemBuilder: (context) {
  257. return items;
  258. },
  259. onSelected: (dynamic value) async {
  260. if (value == 1) {
  261. await _download(widget.file);
  262. } else if (value == 2) {
  263. await _toggleFileArchiveStatus(widget.file);
  264. } else if (value == 3) {
  265. await _setAs(widget.file);
  266. } else if (value == 4) {
  267. await _handleHideRequest(context);
  268. } else if (value == 5) {
  269. await _handleUnHideRequest(context);
  270. }
  271. },
  272. ),
  273. );
  274. }
  275. return _actions;
  276. }
  277. Future<void> _handleHideRequest(BuildContext context) async {
  278. try {
  279. final hideResult =
  280. await CollectionsService.instance.hideFiles(context, [widget.file]);
  281. if (hideResult) {
  282. widget.onFileRemoved(widget.file);
  283. }
  284. } catch (e, s) {
  285. _logger.severe("failed to update file visibility", e, s);
  286. await showGenericErrorDialog(context: context, error: e);
  287. }
  288. }
  289. Future<void> _handleUnHideRequest(BuildContext context) async {
  290. final selectedFiles = SelectedFiles();
  291. selectedFiles.files.add(widget.file);
  292. showCollectionActionSheet(
  293. context,
  294. selectedFiles: selectedFiles,
  295. actionType: CollectionActionType.unHide,
  296. );
  297. }
  298. Future<void> _toggleFileArchiveStatus(EnteFile file) async {
  299. final bool isArchived =
  300. widget.file.magicMetadata.visibility == archiveVisibility;
  301. await changeVisibility(
  302. context,
  303. [widget.file],
  304. isArchived ? visibleVisibility : archiveVisibility,
  305. );
  306. if (mounted) {
  307. setState(() {});
  308. }
  309. }
  310. Future<void> _download(EnteFile file) async {
  311. final dialog = createProgressDialog(
  312. context,
  313. context.l10n.downloading,
  314. isDismissible: true,
  315. );
  316. await dialog.show();
  317. try {
  318. final FileType type = file.fileType;
  319. final bool downloadLivePhotoOnDroid =
  320. type == FileType.livePhoto && Platform.isAndroid;
  321. AssetEntity? savedAsset;
  322. final File? fileToSave = await getFile(file);
  323. //Disabling notifications for assets changing to insert the file into
  324. //files db before triggering a sync.
  325. await PhotoManager.stopChangeNotify();
  326. if (type == FileType.image) {
  327. savedAsset = await PhotoManager.editor
  328. .saveImageWithPath(fileToSave!.path, title: file.title!);
  329. } else if (type == FileType.video) {
  330. savedAsset = await PhotoManager.editor
  331. .saveVideo(fileToSave!, title: file.title!);
  332. } else if (type == FileType.livePhoto) {
  333. final File? liveVideoFile =
  334. await getFileFromServer(file, liveVideo: true);
  335. if (liveVideoFile == null) {
  336. throw AssertionError("Live video can not be null");
  337. }
  338. if (downloadLivePhotoOnDroid) {
  339. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  340. } else {
  341. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  342. imageFile: fileToSave!,
  343. videoFile: liveVideoFile,
  344. title: file.title!,
  345. );
  346. }
  347. }
  348. if (savedAsset != null) {
  349. file.localID = savedAsset.id;
  350. await FilesDB.instance.insert(file);
  351. Bus.instance.fire(
  352. LocalPhotosUpdatedEvent(
  353. [file],
  354. source: "download",
  355. ),
  356. );
  357. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  358. _logger.severe('Failed to save assert of type $type');
  359. }
  360. showToast(context, S.of(context).fileSavedToGallery);
  361. await dialog.hide();
  362. } catch (e) {
  363. _logger.warning("Failed to save file", e);
  364. await dialog.hide();
  365. await showGenericErrorDialog(context: context, error: e);
  366. } finally {
  367. await PhotoManager.startChangeNotify();
  368. LocalSyncService.instance.checkAndSync().ignore();
  369. }
  370. }
  371. Future<void> _saveLivePhotoOnDroid(
  372. File image,
  373. File video,
  374. EnteFile enteFile,
  375. ) async {
  376. debugPrint("Downloading LivePhoto on Droid");
  377. AssetEntity? savedAsset = await (PhotoManager.editor
  378. .saveImageWithPath(image.path, title: enteFile.title!));
  379. if (savedAsset == null) {
  380. throw Exception("Failed to save image of live photo");
  381. }
  382. IgnoredFile ignoreVideoFile = IgnoredFile(
  383. savedAsset.id,
  384. savedAsset.title ?? '',
  385. savedAsset.relativePath ?? 'remoteDownload',
  386. "remoteDownload",
  387. );
  388. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  389. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  390. file_path.extension(video.path);
  391. savedAsset = (await (PhotoManager.editor.saveVideo(
  392. video,
  393. title: videoTitle,
  394. )));
  395. if (savedAsset == null) {
  396. throw Exception("Failed to save video of live photo");
  397. }
  398. ignoreVideoFile = IgnoredFile(
  399. savedAsset.id,
  400. savedAsset.title ?? videoTitle,
  401. savedAsset.relativePath ?? 'remoteDownload',
  402. "remoteDownload",
  403. );
  404. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  405. }
  406. Future<void> _setAs(EnteFile file) async {
  407. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  408. await dialog.show();
  409. try {
  410. final File? fileToSave = await (getFile(file));
  411. if (fileToSave == null) {
  412. throw Exception("Fail to get file for setAs operation");
  413. }
  414. final m = MediaExtension();
  415. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  416. if (result == false) {
  417. showShortToast(context, S.of(context).somethingWentWrong);
  418. }
  419. await dialog.hide();
  420. } catch (e) {
  421. await dialog.hide();
  422. _logger.severe("Failed to use as", e);
  423. await showGenericErrorDialog(context: context, error: e);
  424. }
  425. }
  426. }