file_app_bar.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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/models/file/file.dart';
  13. import 'package:photos/models/file/file_type.dart';
  14. import 'package:photos/models/file/trash_file.dart';
  15. import 'package:photos/models/ignored_file.dart';
  16. import "package:photos/models/metadata/common_keys.dart";
  17. import 'package:photos/models/selected_files.dart';
  18. import 'package:photos/services/collections_service.dart';
  19. import 'package:photos/services/hidden_service.dart';
  20. import 'package:photos/services/ignored_files_service.dart';
  21. import 'package:photos/services/local_sync_service.dart';
  22. import 'package:photos/ui/collections/collection_action_sheet.dart';
  23. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  24. import "package:photos/ui/viewer/file_details/favorite_widget.dart";
  25. import "package:photos/ui/viewer/file_details/upload_icon_widget.dart";
  26. import 'package:photos/utils/dialog_util.dart';
  27. import 'package:photos/utils/file_util.dart';
  28. import "package:photos/utils/magic_util.dart";
  29. import 'package:photos/utils/toast_util.dart';
  30. class FileAppBar extends StatefulWidget {
  31. final EnteFile file;
  32. final Function(EnteFile) onFileRemoved;
  33. final double height;
  34. final bool shouldShowActions;
  35. final int? userID;
  36. final ValueNotifier<bool> enableFullScreenNotifier;
  37. const FileAppBar(
  38. this.file,
  39. this.onFileRemoved,
  40. this.userID,
  41. this.height,
  42. this.shouldShowActions, {
  43. required this.enableFullScreenNotifier,
  44. Key? key,
  45. }) : super(key: key);
  46. @override
  47. FileAppBarState createState() => FileAppBarState();
  48. }
  49. class FileAppBarState extends State<FileAppBar> {
  50. final _logger = Logger("FadingAppBar");
  51. @override
  52. Widget build(BuildContext context) {
  53. return CustomAppBar(
  54. ValueListenableBuilder(
  55. valueListenable: widget.enableFullScreenNotifier,
  56. builder: (context, bool isFullScreen, _) {
  57. return IgnorePointer(
  58. ignoring: isFullScreen,
  59. child: AnimatedOpacity(
  60. opacity: isFullScreen ? 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. },
  80. ),
  81. Size.fromHeight(Platform.isAndroid ? 80 : 96),
  82. );
  83. }
  84. AppBar _buildAppBar() {
  85. debugPrint("building app bar");
  86. final List<Widget> actions = [];
  87. final isTrashedFile = widget.file is TrashFile;
  88. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  89. final bool isOwnedByUser =
  90. widget.file.ownerID == null || widget.file.ownerID == widget.userID;
  91. final bool isFileUploaded = widget.file.isUploaded;
  92. bool isFileHidden = false;
  93. if (isOwnedByUser && isFileUploaded) {
  94. isFileHidden = CollectionsService.instance
  95. .getCollectionByID(widget.file.collectionID!)
  96. ?.isHidden() ??
  97. false;
  98. }
  99. // only show fav option for files owned by the user
  100. if (isOwnedByUser && !isFileHidden && isFileUploaded) {
  101. actions.add(FavoriteWidget(widget.file));
  102. }
  103. if (!isFileUploaded) {
  104. actions.add(
  105. UploadIconWidget(
  106. file: widget.file,
  107. key: ValueKey(widget.file.tag),
  108. ),
  109. );
  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. Text(S.of(context).download),
  131. ],
  132. ),
  133. ),
  134. );
  135. }
  136. // options for files owned by the user
  137. if (isOwnedByUser && !isFileHidden) {
  138. final bool isArchived =
  139. widget.file.magicMetadata.visibility == archiveVisibility;
  140. items.add(
  141. PopupMenuItem(
  142. value: 2,
  143. child: Row(
  144. children: [
  145. Icon(
  146. isArchived ? Icons.unarchive : Icons.archive_outlined,
  147. color: Theme.of(context).iconTheme.color,
  148. ),
  149. const Padding(
  150. padding: EdgeInsets.all(8),
  151. ),
  152. Text(
  153. isArchived
  154. ? S.of(context).unarchive
  155. : S.of(context).archive,
  156. ),
  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. Future<void> _toggleFileArchiveStatus(EnteFile file) async {
  269. final bool isArchived =
  270. widget.file.magicMetadata.visibility == archiveVisibility;
  271. await changeVisibility(
  272. context,
  273. [widget.file],
  274. isArchived ? visibleVisibility : archiveVisibility,
  275. );
  276. if (mounted) {
  277. setState(() {});
  278. }
  279. }
  280. Future<void> _download(EnteFile file) async {
  281. final dialog = createProgressDialog(context, "Downloading...");
  282. await dialog.show();
  283. try {
  284. final FileType type = file.fileType;
  285. final bool downloadLivePhotoOnDroid =
  286. type == FileType.livePhoto && Platform.isAndroid;
  287. AssetEntity? savedAsset;
  288. final File? fileToSave = await getFile(file);
  289. //Disabling notifications for assets changing to insert the file into
  290. //files db before triggering a sync.
  291. PhotoManager.stopChangeNotify();
  292. if (type == FileType.image) {
  293. savedAsset = await PhotoManager.editor
  294. .saveImageWithPath(fileToSave!.path, title: file.title!);
  295. } else if (type == FileType.video) {
  296. savedAsset = await PhotoManager.editor
  297. .saveVideo(fileToSave!, title: file.title!);
  298. } else if (type == FileType.livePhoto) {
  299. final File? liveVideoFile =
  300. await getFileFromServer(file, liveVideo: true);
  301. if (liveVideoFile == null) {
  302. throw AssertionError("Live video can not be null");
  303. }
  304. if (downloadLivePhotoOnDroid) {
  305. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  306. } else {
  307. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  308. imageFile: fileToSave!,
  309. videoFile: liveVideoFile,
  310. title: file.title!,
  311. );
  312. }
  313. }
  314. if (savedAsset != null) {
  315. file.localID = savedAsset.id;
  316. await FilesDB.instance.insert(file);
  317. Bus.instance.fire(
  318. LocalPhotosUpdatedEvent(
  319. [file],
  320. source: "download",
  321. ),
  322. );
  323. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  324. _logger.severe('Failed to save assert of type $type');
  325. }
  326. showToast(context, S.of(context).fileSavedToGallery);
  327. await dialog.hide();
  328. } catch (e) {
  329. _logger.warning("Failed to save file", e);
  330. await dialog.hide();
  331. showGenericErrorDialog(context: context);
  332. } finally {
  333. PhotoManager.startChangeNotify();
  334. LocalSyncService.instance.checkAndSync().ignore();
  335. }
  336. }
  337. Future<void> _saveLivePhotoOnDroid(
  338. File image,
  339. File video,
  340. EnteFile enteFile,
  341. ) async {
  342. debugPrint("Downloading LivePhoto on Droid");
  343. AssetEntity? savedAsset = await (PhotoManager.editor
  344. .saveImageWithPath(image.path, title: enteFile.title!));
  345. if (savedAsset == null) {
  346. throw Exception("Failed to save image of live photo");
  347. }
  348. IgnoredFile ignoreVideoFile = IgnoredFile(
  349. savedAsset.id,
  350. savedAsset.title ?? '',
  351. savedAsset.relativePath ?? 'remoteDownload',
  352. "remoteDownload",
  353. );
  354. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  355. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  356. file_path.extension(video.path);
  357. savedAsset = (await (PhotoManager.editor.saveVideo(
  358. video,
  359. title: videoTitle,
  360. )));
  361. if (savedAsset == null) {
  362. throw Exception("Failed to save video of live photo");
  363. }
  364. ignoreVideoFile = IgnoredFile(
  365. savedAsset.id,
  366. savedAsset.title ?? videoTitle,
  367. savedAsset.relativePath ?? 'remoteDownload',
  368. "remoteDownload",
  369. );
  370. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  371. }
  372. Future<void> _setAs(EnteFile file) async {
  373. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  374. await dialog.show();
  375. try {
  376. final File? fileToSave = await (getFile(file));
  377. if (fileToSave == null) {
  378. throw Exception("Fail to get file for setAs operation");
  379. }
  380. final m = MediaExtension();
  381. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  382. if (result == false) {
  383. showShortToast(context, S.of(context).somethingWentWrong);
  384. }
  385. dialog.hide();
  386. } catch (e) {
  387. dialog.hide();
  388. _logger.severe("Failed to use as", e);
  389. showGenericErrorDialog(context: context);
  390. }
  391. }
  392. }