fading_app_bar.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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:flutter_datetime_picker/flutter_datetime_picker.dart';
  6. import 'package:like_button/like_button.dart';
  7. import 'package:logging/logging.dart';
  8. import 'package:photo_manager/photo_manager.dart';
  9. import 'package:photos/core/event_bus.dart';
  10. import 'package:photos/db/files_db.dart';
  11. import 'package:photos/events/local_photos_updated_event.dart';
  12. import 'package:photos/models/file.dart';
  13. import 'package:photos/models/file_type.dart';
  14. import 'package:photos/models/trash_file.dart';
  15. import 'package:photos/services/favorites_service.dart';
  16. import 'package:photos/services/local_sync_service.dart';
  17. import 'package:photos/ui/custom_app_bar.dart';
  18. import 'package:photos/ui/progress_dialog.dart';
  19. import 'package:photos/utils/date_time_util.dart';
  20. import 'package:photos/utils/delete_file_util.dart';
  21. import 'package:photos/utils/dialog_util.dart';
  22. import 'package:photos/utils/file_util.dart';
  23. import 'package:photos/utils/magic_util.dart';
  24. import 'package:photos/utils/toast_util.dart';
  25. class FadingAppBar extends StatefulWidget implements PreferredSizeWidget {
  26. final File file;
  27. final Function(File) onFileDeleted;
  28. final double height;
  29. final bool shouldShowActions;
  30. final int userID;
  31. FadingAppBar(
  32. this.file,
  33. this.onFileDeleted,
  34. this.userID,
  35. this.height,
  36. this.shouldShowActions, {
  37. Key key,
  38. }) : super(key: key);
  39. @override
  40. Size get preferredSize => Size.fromHeight(height);
  41. @override
  42. FadingAppBarState createState() => FadingAppBarState();
  43. }
  44. class FadingAppBarState extends State<FadingAppBar> {
  45. final _logger = Logger("FadingAppBar");
  46. bool _shouldHide = false;
  47. @override
  48. Widget build(BuildContext context) {
  49. return CustomAppBar(
  50. AnimatedOpacity(
  51. child: Container(
  52. decoration: BoxDecoration(
  53. gradient: LinearGradient(
  54. begin: Alignment.topCenter,
  55. end: Alignment.bottomCenter,
  56. colors: [
  57. Colors.black.withOpacity(0.64),
  58. Colors.black.withOpacity(0.5),
  59. Colors.transparent,
  60. ],
  61. stops: const [0, 0.2, 1],
  62. ),
  63. ),
  64. child: _buildAppBar(),
  65. ),
  66. opacity: _shouldHide ? 0 : 1,
  67. duration: Duration(milliseconds: 150),
  68. ),
  69. height: 100,
  70. );
  71. }
  72. void hide() {
  73. setState(() {
  74. _shouldHide = true;
  75. });
  76. }
  77. void show() {
  78. if (mounted) {
  79. setState(() {
  80. _shouldHide = false;
  81. });
  82. }
  83. }
  84. AppBar _buildAppBar() {
  85. final List<Widget> actions = [];
  86. final isTrashedFile = widget.file is TrashFile;
  87. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  88. // only show fav option for files owned by the user
  89. if (widget.file.ownerID == null || widget.file.ownerID == widget.userID) {
  90. actions.add(_getFavoriteButton());
  91. }
  92. actions.add(PopupMenuButton(
  93. itemBuilder: (context) {
  94. final List<PopupMenuItem> items = [];
  95. if (widget.file.isRemoteFile()) {
  96. items.add(
  97. PopupMenuItem(
  98. value: 1,
  99. child: Row(
  100. children: [
  101. Icon(Platform.isAndroid
  102. ? Icons.download
  103. : CupertinoIcons.cloud_download),
  104. Padding(
  105. padding: EdgeInsets.all(8),
  106. ),
  107. Text("download"),
  108. ],
  109. ),
  110. ),
  111. );
  112. }
  113. // options for files owned by the user
  114. if (widget.file.ownerID == null ||
  115. widget.file.ownerID == widget.userID) {
  116. if (widget.file.uploadedFileID != null) {
  117. items.add(
  118. PopupMenuItem(
  119. value: 2,
  120. child: Row(
  121. children: [
  122. Icon(Platform.isAndroid
  123. ? Icons.access_time_rounded
  124. : CupertinoIcons.time),
  125. Padding(
  126. padding: EdgeInsets.all(8),
  127. ),
  128. Text("edit time"),
  129. ],
  130. ),
  131. ),
  132. );
  133. }
  134. items.add(
  135. PopupMenuItem(
  136. value: 3,
  137. child: Row(
  138. children: [
  139. Icon(Platform.isAndroid
  140. ? Icons.delete_outline
  141. : CupertinoIcons.delete),
  142. Padding(
  143. padding: EdgeInsets.all(8),
  144. ),
  145. Text("delete"),
  146. ],
  147. ),
  148. ),
  149. );
  150. }
  151. return items;
  152. },
  153. onSelected: (value) {
  154. if (value == 1) {
  155. _download(widget.file);
  156. } else if (value == 2) {
  157. _showDateTimePicker(widget.file);
  158. } else if (value == 3) {
  159. _showDeleteSheet(widget.file);
  160. }
  161. },
  162. ));
  163. return AppBar(
  164. title: Text(
  165. getDayTitle(widget.file.creationTime),
  166. style: TextStyle(
  167. fontSize: 14,
  168. ),
  169. ),
  170. actions: shouldShowActions ? actions : [],
  171. backgroundColor: Color(0x00000000),
  172. elevation: 0,
  173. );
  174. }
  175. Widget _getFavoriteButton() {
  176. return FutureBuilder(
  177. future: FavoritesService.instance.isFavorite(widget.file),
  178. builder: (context, snapshot) {
  179. if (snapshot.hasData) {
  180. return _getLikeButton(widget.file, snapshot.data);
  181. } else {
  182. return _getLikeButton(widget.file, false);
  183. }
  184. },
  185. );
  186. }
  187. Widget _getLikeButton(File file, bool isLiked) {
  188. return LikeButton(
  189. isLiked: isLiked,
  190. onTap: (oldValue) async {
  191. final isLiked = !oldValue;
  192. bool hasError = false;
  193. if (isLiked) {
  194. final shouldBlockUser = file.uploadedFileID == null;
  195. ProgressDialog dialog;
  196. if (shouldBlockUser) {
  197. dialog = createProgressDialog(context, "adding to favorites...");
  198. await dialog.show();
  199. }
  200. try {
  201. await FavoritesService.instance.addToFavorites(file);
  202. } catch (e, s) {
  203. _logger.severe(e, s);
  204. hasError = true;
  205. showToast("sorry, could not add this to favorites!");
  206. } finally {
  207. if (shouldBlockUser) {
  208. await dialog.hide();
  209. }
  210. }
  211. } else {
  212. try {
  213. await FavoritesService.instance.removeFromFavorites(file);
  214. } catch (e, s) {
  215. _logger.severe(e, s);
  216. hasError = true;
  217. showToast("sorry, could not remove this from favorites!");
  218. }
  219. }
  220. return hasError ? oldValue : isLiked;
  221. },
  222. likeBuilder: (isLiked) {
  223. return Icon(
  224. Icons.favorite_border,
  225. color: isLiked ? Colors.pinkAccent : Colors.white,
  226. size: 24,
  227. );
  228. },
  229. );
  230. }
  231. void _showDateTimePicker(File file) async {
  232. final dateResult = await DatePicker.showDatePicker(
  233. context,
  234. minTime: DateTime(1800, 1, 1),
  235. maxTime: DateTime.now(),
  236. currentTime: DateTime.fromMicrosecondsSinceEpoch(file.creationTime),
  237. locale: LocaleType.en,
  238. theme: kDatePickerTheme,
  239. );
  240. if (dateResult == null) {
  241. return;
  242. }
  243. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  244. context,
  245. showTitleActions: true,
  246. currentTime: dateResult,
  247. locale: LocaleType.en,
  248. theme: kDatePickerTheme,
  249. );
  250. if (dateWithTimeResult != null) {
  251. if (await editTime(context, List.of([widget.file]),
  252. dateWithTimeResult.microsecondsSinceEpoch)) {
  253. widget.file.creationTime = dateWithTimeResult.microsecondsSinceEpoch;
  254. setState(() {});
  255. }
  256. }
  257. }
  258. void _showDeleteSheet(File file) {
  259. final List<Widget> actions = [];
  260. if (file.uploadedFileID == null || file.localID == null) {
  261. actions.add(CupertinoActionSheetAction(
  262. child: Text("everywhere"),
  263. isDestructiveAction: true,
  264. onPressed: () async {
  265. await deleteFilesFromEverywhere(context, [file]);
  266. widget.onFileDeleted(file);
  267. },
  268. ));
  269. } else {
  270. // uploaded file which is present locally too
  271. actions.add(CupertinoActionSheetAction(
  272. child: Text("device"),
  273. isDestructiveAction: true,
  274. onPressed: () async {
  275. await deleteFilesOnDeviceOnly(context, [file]);
  276. showToast("file deleted from device");
  277. Navigator.of(context, rootNavigator: true).pop();
  278. },
  279. ));
  280. actions.add(CupertinoActionSheetAction(
  281. child: Text("ente"),
  282. isDestructiveAction: true,
  283. onPressed: () async {
  284. await deleteFilesFromRemoteOnly(context, [file]);
  285. showShortToast("moved to trash");
  286. Navigator.of(context, rootNavigator: true).pop();
  287. },
  288. ));
  289. actions.add(CupertinoActionSheetAction(
  290. child: Text("everywhere"),
  291. isDestructiveAction: true,
  292. onPressed: () async {
  293. await deleteFilesFromEverywhere(context, [file]);
  294. widget.onFileDeleted(file);
  295. },
  296. ));
  297. }
  298. final action = CupertinoActionSheet(
  299. title: Text("delete file?"),
  300. actions: actions,
  301. cancelButton: CupertinoActionSheetAction(
  302. child: Text("cancel"),
  303. onPressed: () {
  304. Navigator.of(context, rootNavigator: true).pop();
  305. },
  306. ),
  307. );
  308. showCupertinoModalPopup(context: context, builder: (_) => action);
  309. }
  310. Future<void> _download(File file) async {
  311. final dialog = createProgressDialog(context, "downloading...");
  312. await dialog.show();
  313. FileType type = file.fileType;
  314. // save and track image for livePhoto/image and video for FileType.video
  315. io.File fileToSave = await getFile(file);
  316. final savedAsset = type == FileType.video
  317. ? (await PhotoManager.editor.saveVideo(fileToSave, title: file.title))
  318. : (await PhotoManager.editor
  319. .saveImageWithPath(fileToSave.path, title: file.title));
  320. // immediately track assetID to avoid duplicate upload
  321. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  322. file.localID = savedAsset.id;
  323. await FilesDB.instance.insert(file);
  324. if (type == FileType.livePhoto) {
  325. io.File liveVideo = await getFileFromServer(file, liveVideo: true);
  326. if (liveVideo == null) {
  327. _logger.warning("Failed to find live video" + file.tag());
  328. } else {
  329. final savedAsset = (await PhotoManager.editor.saveVideo(liveVideo));
  330. // in case of livePhoto, file.localID only points the image asset.
  331. // ignore the saved video asset for live photo from future downloads
  332. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  333. }
  334. }
  335. Bus.instance.fire(LocalPhotosUpdatedEvent([file]));
  336. await dialog.hide();
  337. if (file.fileType == FileType.livePhoto) {
  338. showToast("photo and video saved to gallery");
  339. } else {
  340. showToast("file saved to gallery");
  341. }
  342. }
  343. }
  344. const kDatePickerTheme = DatePickerTheme(
  345. backgroundColor: Colors.black,
  346. itemStyle: TextStyle(
  347. color: Colors.white,
  348. ),
  349. cancelStyle: TextStyle(
  350. color: Colors.white,
  351. ),
  352. );