create_collection_page.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import 'package:flutter/material.dart';
  2. import 'package:logging/logging.dart';
  3. import 'package:page_transition/page_transition.dart';
  4. import 'package:photos/core/configuration.dart';
  5. import 'package:photos/db/files_db.dart';
  6. import 'package:photos/models/collection.dart';
  7. import 'package:photos/models/collection_items.dart';
  8. import 'package:photos/models/file.dart';
  9. import 'package:photos/models/selected_files.dart';
  10. import 'package:photos/services/collections_service.dart';
  11. import 'package:photos/services/remote_sync_service.dart';
  12. import 'package:photos/ui/collection_page.dart';
  13. import 'package:photos/ui/loading_widget.dart';
  14. import 'package:photos/ui/thumbnail_widget.dart';
  15. import 'package:photos/utils/dialog_util.dart';
  16. import 'package:photos/utils/share_util.dart';
  17. import 'package:photos/utils/toast_util.dart';
  18. import 'package:receive_sharing_intent/receive_sharing_intent.dart';
  19. enum CollectionActionType { addFiles, moveFiles, restoreFiles }
  20. String _actionName(CollectionActionType type, bool plural) {
  21. final titleSuffix = (plural ? "s" : "");
  22. String text = "";
  23. switch (type) {
  24. case CollectionActionType.addFiles:
  25. text = "add file";
  26. break;
  27. case CollectionActionType.moveFiles:
  28. text = "move file";
  29. break;
  30. case CollectionActionType.restoreFiles:
  31. text = "restore file";
  32. break;
  33. }
  34. return text + titleSuffix;
  35. }
  36. class CreateCollectionPage extends StatefulWidget {
  37. final SelectedFiles selectedFiles;
  38. final List<SharedMediaFile> sharedFiles;
  39. final CollectionActionType actionType;
  40. const CreateCollectionPage(this.selectedFiles, this.sharedFiles,
  41. {Key key, this.actionType = CollectionActionType.addFiles})
  42. : super(key: key);
  43. @override
  44. _CreateCollectionPageState createState() => _CreateCollectionPageState();
  45. }
  46. class _CreateCollectionPageState extends State<CreateCollectionPage> {
  47. final _logger = Logger("CreateCollectionPage");
  48. String _albumName;
  49. @override
  50. Widget build(BuildContext context) {
  51. final filesCount = widget.sharedFiles != null
  52. ? widget.sharedFiles.length
  53. : widget.selectedFiles.files.length;
  54. return Scaffold(
  55. appBar: AppBar(
  56. title: Text(_actionName(widget.actionType, filesCount > 1)),
  57. ),
  58. body: _getBody(context),
  59. );
  60. }
  61. Widget _getBody(BuildContext context) {
  62. return SingleChildScrollView(
  63. child: Column(
  64. mainAxisSize: MainAxisSize.min,
  65. children: [
  66. Row(
  67. children: [
  68. Expanded(
  69. child: Padding(
  70. padding: const EdgeInsets.only(
  71. top: 30, bottom: 12, left: 40, right: 40),
  72. child: OutlinedButton.icon(
  73. style: ButtonStyle(
  74. padding: MaterialStateProperty.all<EdgeInsets>(
  75. EdgeInsets.all(20),
  76. ),
  77. ),
  78. icon: Icon(
  79. Icons.create_new_folder_outlined,
  80. color: Theme.of(context).buttonColor,
  81. ),
  82. label: Text(
  83. "to a new album",
  84. style: Theme.of(context).textTheme.bodyText1,
  85. ),
  86. onPressed: () {
  87. _showNameAlbumDialog();
  88. },
  89. ),
  90. ),
  91. ),
  92. ],
  93. ),
  94. Padding(
  95. padding: const EdgeInsets.fromLTRB(40, 24, 40, 20),
  96. child: Align(
  97. alignment: Alignment.centerLeft,
  98. child: Text(
  99. "to an existing album",
  100. style: TextStyle(
  101. fontWeight: FontWeight.bold,
  102. color: Theme.of(context).primaryColorLight.withOpacity(0.8),
  103. ),
  104. ),
  105. ),
  106. ),
  107. Padding(
  108. padding: const EdgeInsets.fromLTRB(20, 4, 20, 0),
  109. child: _getExistingCollectionsWidget(),
  110. ),
  111. ],
  112. ),
  113. );
  114. }
  115. Widget _getExistingCollectionsWidget() {
  116. return FutureBuilder<List<CollectionWithThumbnail>>(
  117. future: _getCollectionsWithThumbnail(),
  118. builder: (context, snapshot) {
  119. if (snapshot.hasError) {
  120. return Text(snapshot.error.toString());
  121. } else if (snapshot.hasData) {
  122. return ListView.builder(
  123. itemBuilder: (context, index) {
  124. return _buildCollectionItem(snapshot.data[index]);
  125. },
  126. itemCount: snapshot.data.length,
  127. shrinkWrap: true,
  128. physics: NeverScrollableScrollPhysics(),
  129. );
  130. } else {
  131. return loadWidget;
  132. }
  133. },
  134. );
  135. }
  136. Widget _buildCollectionItem(CollectionWithThumbnail item) {
  137. return Container(
  138. padding: EdgeInsets.only(left: 24, bottom: 16),
  139. child: GestureDetector(
  140. behavior: HitTestBehavior.translucent,
  141. child: Row(
  142. children: <Widget>[
  143. ClipRRect(
  144. borderRadius: BorderRadius.circular(2.0),
  145. child: SizedBox(
  146. child: ThumbnailWidget(item.thumbnail),
  147. height: 64,
  148. width: 64,
  149. key: Key("collection_item:" + item.thumbnail.tag()),
  150. ),
  151. ),
  152. Padding(padding: EdgeInsets.all(8)),
  153. Expanded(
  154. child: Text(
  155. item.collection.name,
  156. style: TextStyle(
  157. fontSize: 16,
  158. ),
  159. ),
  160. ),
  161. ],
  162. ),
  163. onTap: () async {
  164. if (await _runCollectionAction(item.collection.id)) {
  165. showToast(widget.actionType == CollectionActionType.addFiles
  166. ? "added successfully to " + item.collection.name
  167. : "moved successfully to " + item.collection.name);
  168. _navigateToCollection(item.collection);
  169. }
  170. },
  171. ),
  172. );
  173. }
  174. Future<List<CollectionWithThumbnail>> _getCollectionsWithThumbnail() async {
  175. final List<CollectionWithThumbnail> collectionsWithThumbnail = [];
  176. final latestCollectionFiles =
  177. await CollectionsService.instance.getLatestCollectionFiles();
  178. for (final file in latestCollectionFiles) {
  179. final c =
  180. CollectionsService.instance.getCollectionByID(file.collectionID);
  181. if (c.owner.id == Configuration.instance.getUserID()) {
  182. collectionsWithThumbnail.add(CollectionWithThumbnail(c, file));
  183. }
  184. }
  185. collectionsWithThumbnail.sort((first, second) {
  186. return second.collection.updationTime
  187. .compareTo(first.collection.updationTime);
  188. });
  189. return collectionsWithThumbnail;
  190. }
  191. void _showNameAlbumDialog() async {
  192. AlertDialog alert = AlertDialog(
  193. title: Text("album title"),
  194. content: TextFormField(
  195. decoration: InputDecoration(
  196. hintText: "Christmas 2020 / Dinner at Alice's",
  197. contentPadding: EdgeInsets.all(8),
  198. ),
  199. onChanged: (value) {
  200. setState(() {
  201. _albumName = value;
  202. });
  203. },
  204. autofocus: true,
  205. keyboardType: TextInputType.text,
  206. textCapitalization: TextCapitalization.words,
  207. ),
  208. actions: [
  209. TextButton(
  210. child: Text(
  211. "ok",
  212. style: TextStyle(
  213. color: Theme.of(context).buttonColor,
  214. ),
  215. ),
  216. onPressed: () async {
  217. Navigator.of(context, rootNavigator: true).pop('dialog');
  218. final collection = await _createAlbum(_albumName);
  219. if (collection != null) {
  220. if (await _runCollectionAction(collection.id)) {
  221. if (widget.actionType == CollectionActionType.restoreFiles) {
  222. showToast('restored files to album ' + _albumName);
  223. } else {
  224. showToast("album '" + _albumName + "' created.");
  225. }
  226. _navigateToCollection(collection);
  227. }
  228. }
  229. },
  230. ),
  231. ],
  232. );
  233. showDialog(
  234. context: context,
  235. builder: (BuildContext context) {
  236. return alert;
  237. },
  238. );
  239. }
  240. void _navigateToCollection(Collection collection) {
  241. Navigator.pop(context);
  242. Navigator.push(
  243. context,
  244. PageTransition(
  245. type: PageTransitionType.bottomToTop,
  246. child: CollectionPage(
  247. CollectionWithThumbnail(collection, null),
  248. )));
  249. }
  250. Future<bool> _runCollectionAction(int collectionID) async {
  251. switch (widget.actionType) {
  252. case CollectionActionType.addFiles:
  253. return _addToCollection(collectionID);
  254. case CollectionActionType.moveFiles:
  255. return _moveFilesToCollection(collectionID);
  256. case CollectionActionType.restoreFiles:
  257. return _restoreFilesToCollection(collectionID);
  258. }
  259. throw AssertionError("unexpected actionType ${widget.actionType}");
  260. }
  261. Future<bool> _moveFilesToCollection(int toCollectionID) async {
  262. final dialog = createProgressDialog(context, "moving files to album...");
  263. await dialog.show();
  264. try {
  265. int fromCollectionID = widget.selectedFiles.files?.first?.collectionID;
  266. await CollectionsService.instance.move(toCollectionID, fromCollectionID,
  267. widget.selectedFiles.files?.toList());
  268. RemoteSyncService.instance.sync(silently: true);
  269. widget.selectedFiles?.clearAll();
  270. await dialog.hide();
  271. return true;
  272. } on AssertionError catch (e, s) {
  273. await dialog.hide();
  274. showErrorDialog(context, "oops", e.message);
  275. return false;
  276. } catch (e, s) {
  277. _logger.severe("Could not move to album", e, s);
  278. await dialog.hide();
  279. showGenericErrorDialog(context);
  280. return false;
  281. }
  282. }
  283. Future<bool> _restoreFilesToCollection(int toCollectionID) async {
  284. final dialog = createProgressDialog(context, "restoring files...");
  285. await dialog.show();
  286. try {
  287. await CollectionsService.instance
  288. .restore(toCollectionID, widget.selectedFiles.files?.toList());
  289. RemoteSyncService.instance.sync(silently: true);
  290. widget.selectedFiles?.clearAll();
  291. await dialog.hide();
  292. return true;
  293. } on AssertionError catch (e, s) {
  294. await dialog.hide();
  295. showErrorDialog(context, "oops", e.message);
  296. return false;
  297. } catch (e, s) {
  298. _logger.severe("Could not move to album", e, s);
  299. await dialog.hide();
  300. showGenericErrorDialog(context);
  301. return false;
  302. }
  303. }
  304. Future<bool> _addToCollection(int collectionID) async {
  305. final dialog = createProgressDialog(context, "uploading files to album...");
  306. await dialog.show();
  307. try {
  308. final List<File> files = [];
  309. final List<File> filesPendingUpload = [];
  310. if (widget.sharedFiles != null) {
  311. filesPendingUpload.addAll(await convertIncomingSharedMediaToFile(
  312. widget.sharedFiles, collectionID));
  313. } else {
  314. final List<File> filesPendingUpload = [];
  315. for (final file in widget.selectedFiles.files) {
  316. final currentFile = await FilesDB.instance.getFile(file.generatedID);
  317. if (currentFile.uploadedFileID == null) {
  318. currentFile.collectionID = collectionID;
  319. filesPendingUpload.add(currentFile);
  320. } else {
  321. files.add(currentFile);
  322. }
  323. }
  324. await FilesDB.instance.insertMultiple(filesPendingUpload);
  325. await CollectionsService.instance.addToCollection(collectionID, files);
  326. }
  327. RemoteSyncService.instance.sync(silently: true);
  328. await dialog.hide();
  329. widget.selectedFiles?.clearAll();
  330. return true;
  331. } catch (e, s) {
  332. _logger.severe("Could not add to album", e, s);
  333. await dialog.hide();
  334. showGenericErrorDialog(context);
  335. }
  336. return false;
  337. }
  338. Future<Collection> _createAlbum(String albumName) async {
  339. Collection collection;
  340. final dialog = createProgressDialog(context, "creating album...");
  341. await dialog.show();
  342. try {
  343. collection = await CollectionsService.instance.createAlbum(albumName);
  344. } catch (e, s) {
  345. _logger.severe(e, s);
  346. await dialog.hide();
  347. showGenericErrorDialog(context);
  348. } finally {
  349. await dialog.hide();
  350. }
  351. return collection;
  352. }
  353. }