manage_links_widget.dart 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import 'dart:convert';
  2. import 'dart:typed_data';
  3. import 'package:collection/collection.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
  7. import 'package:flutter_sodium/flutter_sodium.dart';
  8. import 'package:photos/ente_theme_data.dart';
  9. import 'package:photos/models/collection.dart';
  10. import 'package:photos/services/collections_service.dart';
  11. import 'package:photos/theme/colors.dart';
  12. import 'package:photos/theme/ente_theme.dart';
  13. import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';
  14. import 'package:photos/ui/common/dialogs.dart';
  15. import 'package:photos/ui/components/captioned_text_widget.dart';
  16. import 'package:photos/ui/components/divider_widget.dart';
  17. import 'package:photos/ui/components/menu_item_widget.dart';
  18. import 'package:photos/ui/components/menu_section_description_widget.dart';
  19. import 'package:photos/utils/crypto_util.dart';
  20. import 'package:photos/utils/date_time_util.dart';
  21. import 'package:photos/utils/dialog_util.dart';
  22. import 'package:photos/utils/toast_util.dart';
  23. import 'package:tuple/tuple.dart';
  24. class ManageSharedLinkWidget extends StatefulWidget {
  25. final Collection? collection;
  26. const ManageSharedLinkWidget({Key? key, this.collection}) : super(key: key);
  27. @override
  28. State<ManageSharedLinkWidget> createState() => _ManageSharedLinkWidgetState();
  29. }
  30. class _ManageSharedLinkWidgetState extends State<ManageSharedLinkWidget> {
  31. // index, title, milliseconds in future post which link should expire (when >0)
  32. final List<Tuple3<int, String, int>> _expiryOptions = [
  33. const Tuple3(0, "Never", 0),
  34. Tuple3(1, "After 1 hour", const Duration(hours: 1).inMicroseconds),
  35. Tuple3(2, "After 1 day", const Duration(days: 1).inMicroseconds),
  36. Tuple3(3, "After 1 week", const Duration(days: 7).inMicroseconds),
  37. // todo: make this time calculation perfect
  38. Tuple3(4, "After 1 month", const Duration(days: 30).inMicroseconds),
  39. Tuple3(5, "After 1 year", const Duration(days: 365).inMicroseconds),
  40. const Tuple3(6, "Custom", -1),
  41. ];
  42. late Tuple3<int, String, int> _selectedExpiry;
  43. int _selectedDeviceLimitIndex = 0;
  44. final CollectionActions sharingActions =
  45. CollectionActions(CollectionsService.instance);
  46. @override
  47. void initState() {
  48. _selectedExpiry = _expiryOptions.first;
  49. super.initState();
  50. }
  51. @override
  52. Widget build(BuildContext context) {
  53. final enteColorScheme = getEnteColorScheme(context);
  54. final PublicURL url = widget.collection!.publicURLs!.firstOrNull!;
  55. return Scaffold(
  56. backgroundColor: Theme.of(context).backgroundColor,
  57. appBar: AppBar(
  58. elevation: 0,
  59. title: const Text(
  60. "Manage link",
  61. ),
  62. ),
  63. body: SingleChildScrollView(
  64. child: ListBody(
  65. children: <Widget>[
  66. Padding(
  67. padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
  68. child: Column(
  69. crossAxisAlignment: CrossAxisAlignment.start,
  70. children: [
  71. MenuItemWidget(
  72. captionedTextWidget: const CaptionedTextWidget(
  73. title: "Allow adding photos",
  74. ),
  75. alignCaptionedTextToLeft: true,
  76. menuItemColor: getEnteColorScheme(context).fillFaint,
  77. pressedColor: getEnteColorScheme(context).fillFaint,
  78. trailingWidget: Switch.adaptive(
  79. value: widget.collection!.publicURLs?.firstOrNull
  80. ?.enableCollect ??
  81. false,
  82. onChanged: (value) async {
  83. await _updateUrlSettings(
  84. context,
  85. {'enableCollect': value},
  86. );
  87. setState(() {});
  88. },
  89. ),
  90. ),
  91. const MenuSectionDescriptionWidget(
  92. content:
  93. "Allow people with the link to also add photos to the shared "
  94. "album.",
  95. ),
  96. const SizedBox(height: 24),
  97. MenuItemWidget(
  98. alignCaptionedTextToLeft: true,
  99. captionedTextWidget: CaptionedTextWidget(
  100. title: "Link expiry",
  101. subTitle: (url.hasExpiry
  102. ? (url.isExpired ? "Expired" : "Enabled")
  103. : "Never"),
  104. subTitleColor: url.isExpired ? warning500 : null,
  105. ),
  106. trailingIcon: Icons.chevron_right,
  107. menuItemColor: enteColorScheme.fillFaint,
  108. onTap: () async {
  109. await showPicker();
  110. },
  111. ),
  112. url.hasExpiry
  113. ? MenuSectionDescriptionWidget(
  114. content: url.isExpired
  115. ? "This link has expired. Please select a new expiry time or disable link expiry."
  116. : 'Link will expire on '
  117. '${getFormattedTime(DateTime.fromMicrosecondsSinceEpoch(url.validTill))}',
  118. )
  119. : const SizedBox.shrink(),
  120. const Padding(padding: EdgeInsets.only(top: 24)),
  121. MenuItemWidget(
  122. captionedTextWidget: CaptionedTextWidget(
  123. title: "Device limit",
  124. subTitle: widget
  125. .collection!.publicURLs!.first!.deviceLimit
  126. .toString(),
  127. ),
  128. trailingIcon: Icons.chevron_right,
  129. menuItemColor: enteColorScheme.fillFaint,
  130. alignCaptionedTextToLeft: true,
  131. isBottomBorderRadiusRemoved: true,
  132. onTap: () async {
  133. await _showDeviceLimitPicker();
  134. },
  135. ),
  136. DividerWidget(
  137. dividerType: DividerType.menuNoIcon,
  138. bgColor: getEnteColorScheme(context).fillFaint,
  139. ),
  140. MenuItemWidget(
  141. captionedTextWidget: const CaptionedTextWidget(
  142. title: "Allow downloads",
  143. ),
  144. alignCaptionedTextToLeft: true,
  145. isBottomBorderRadiusRemoved: true,
  146. isTopBorderRadiusRemoved: true,
  147. menuItemColor: getEnteColorScheme(context).fillFaint,
  148. pressedColor: getEnteColorScheme(context).fillFaint,
  149. trailingWidget: Switch.adaptive(
  150. value: widget.collection!.publicURLs?.firstOrNull
  151. ?.enableDownload ??
  152. true,
  153. onChanged: (value) async {
  154. if (!value) {
  155. final choice = await showChoiceDialog(
  156. context,
  157. 'Disable downloads',
  158. 'Are you sure that you want to disable the download button for files?',
  159. firstAction: 'No',
  160. secondAction: 'Yes',
  161. firstActionColor:
  162. Theme.of(context).colorScheme.greenText,
  163. secondActionColor: Theme.of(context)
  164. .colorScheme
  165. .inverseBackgroundColor,
  166. );
  167. if (choice != DialogUserChoice.secondChoice) {
  168. return;
  169. }
  170. }
  171. await _updateUrlSettings(
  172. context,
  173. {'enableDownload': value},
  174. );
  175. if (!value) {
  176. showErrorDialog(
  177. context,
  178. "Please note",
  179. "Viewers can still take screenshots or save a copy of your photos using external tools",
  180. );
  181. }
  182. setState(() {});
  183. },
  184. ),
  185. ),
  186. DividerWidget(
  187. dividerType: DividerType.menuNoIcon,
  188. bgColor: getEnteColorScheme(context).fillFaint,
  189. ),
  190. MenuItemWidget(
  191. captionedTextWidget: const CaptionedTextWidget(
  192. title: "Password lock",
  193. ),
  194. alignCaptionedTextToLeft: true,
  195. isTopBorderRadiusRemoved: true,
  196. menuItemColor: getEnteColorScheme(context).fillFaint,
  197. pressedColor: getEnteColorScheme(context).fillFaint,
  198. trailingWidget: Switch.adaptive(
  199. value: widget.collection!.publicURLs?.firstOrNull
  200. ?.passwordEnabled ??
  201. false,
  202. onChanged: (enablePassword) async {
  203. if (enablePassword) {
  204. final inputResult =
  205. await _displayLinkPasswordInput(context);
  206. if (inputResult != null &&
  207. inputResult == 'ok' &&
  208. _textFieldController.text.trim().isNotEmpty) {
  209. final propToUpdate = await _getEncryptedPassword(
  210. _textFieldController.text,
  211. );
  212. await _updateUrlSettings(context, propToUpdate);
  213. }
  214. } else {
  215. await _updateUrlSettings(
  216. context,
  217. {'disablePassword': true},
  218. );
  219. }
  220. setState(() {});
  221. },
  222. ),
  223. ),
  224. const SizedBox(
  225. height: 24,
  226. ),
  227. MenuItemWidget(
  228. captionedTextWidget: const CaptionedTextWidget(
  229. title: "Remove link",
  230. textColor: warning500,
  231. makeTextBold: true,
  232. ),
  233. leadingIcon: Icons.remove_circle_outline,
  234. leadingIconColor: warning500,
  235. menuItemColor: getEnteColorScheme(context).fillFaint,
  236. pressedColor: getEnteColorScheme(context).fillFaint,
  237. onTap: () async {
  238. final bool result = await sharingActions.publicLinkToggle(
  239. context,
  240. widget.collection!,
  241. false,
  242. );
  243. if (result && mounted) {
  244. Navigator.of(context).pop();
  245. // setState(() => {});
  246. }
  247. },
  248. ),
  249. ],
  250. ),
  251. ),
  252. ],
  253. ),
  254. ),
  255. );
  256. }
  257. Future<void> showPicker() async {
  258. Widget getOptionText(String text) {
  259. return Text(text, style: Theme.of(context).textTheme.subtitle1);
  260. }
  261. return showCupertinoModalPopup(
  262. context: context,
  263. builder: (context) {
  264. return Column(
  265. mainAxisAlignment: MainAxisAlignment.end,
  266. children: <Widget>[
  267. Container(
  268. decoration: BoxDecoration(
  269. color: Theme.of(context).colorScheme.cupertinoPickerTopColor,
  270. border: const Border(
  271. bottom: BorderSide(
  272. color: Color(0xff999999),
  273. width: 0.0,
  274. ),
  275. ),
  276. ),
  277. child: Row(
  278. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  279. children: <Widget>[
  280. CupertinoButton(
  281. onPressed: () {
  282. Navigator.of(context).pop('cancel');
  283. },
  284. padding: const EdgeInsets.symmetric(
  285. horizontal: 8.0,
  286. vertical: 5.0,
  287. ),
  288. child: Text(
  289. 'Cancel',
  290. style: Theme.of(context).textTheme.subtitle1,
  291. ),
  292. ),
  293. CupertinoButton(
  294. onPressed: () async {
  295. int newValidTill = -1;
  296. bool hasSelectedCustom = false;
  297. final int expireAfterInMicroseconds =
  298. _selectedExpiry.item3;
  299. // need to manually select time
  300. if (expireAfterInMicroseconds < 0) {
  301. hasSelectedCustom = true;
  302. Navigator.of(context).pop('');
  303. final timeInMicrosecondsFromEpoch =
  304. await _showDateTimePicker();
  305. if (timeInMicrosecondsFromEpoch != null) {
  306. newValidTill = timeInMicrosecondsFromEpoch;
  307. }
  308. } else if (expireAfterInMicroseconds == 0) {
  309. // no expiry
  310. newValidTill = 0;
  311. } else {
  312. newValidTill = DateTime.now().microsecondsSinceEpoch +
  313. expireAfterInMicroseconds;
  314. }
  315. if (!hasSelectedCustom) {
  316. Navigator.of(context).pop('');
  317. }
  318. if (newValidTill >= 0) {
  319. await updateTime(newValidTill);
  320. }
  321. },
  322. padding: const EdgeInsets.symmetric(
  323. horizontal: 16.0,
  324. vertical: 2.0,
  325. ),
  326. child: Text(
  327. 'Confirm',
  328. style: Theme.of(context).textTheme.subtitle1,
  329. ),
  330. )
  331. ],
  332. ),
  333. ),
  334. Container(
  335. height: 220.0,
  336. color: const Color(0xfff7f7f7),
  337. child: CupertinoPicker(
  338. backgroundColor:
  339. Theme.of(context).backgroundColor.withOpacity(0.95),
  340. onSelectedItemChanged: (value) {
  341. final firstWhere = _expiryOptions
  342. .firstWhere((element) => element.item1 == value);
  343. setState(() {
  344. _selectedExpiry = firstWhere;
  345. });
  346. },
  347. magnification: 1.3,
  348. useMagnifier: true,
  349. itemExtent: 25,
  350. diameterRatio: 1,
  351. children:
  352. _expiryOptions.map((e) => getOptionText(e.item2)).toList(),
  353. ),
  354. )
  355. ],
  356. );
  357. },
  358. );
  359. }
  360. Future<void> updateTime(int newValidTill) async {
  361. await _updateUrlSettings(
  362. context,
  363. {'validTill': newValidTill},
  364. );
  365. if(mounted) {
  366. setState(() {});
  367. }
  368. }
  369. // _showDateTimePicker return null if user doesn't select date-time
  370. Future<int?> _showDateTimePicker() async {
  371. final dateResult = await DatePicker.showDatePicker(
  372. context,
  373. minTime: DateTime.now(),
  374. currentTime: DateTime.now(),
  375. locale: LocaleType.en,
  376. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  377. );
  378. if (dateResult == null) {
  379. return null;
  380. }
  381. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  382. context,
  383. showTitleActions: true,
  384. currentTime: dateResult,
  385. locale: LocaleType.en,
  386. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  387. );
  388. if (dateWithTimeResult == null) {
  389. return null;
  390. } else {
  391. return dateWithTimeResult.microsecondsSinceEpoch;
  392. }
  393. }
  394. final TextEditingController _textFieldController = TextEditingController();
  395. Future<String?> _displayLinkPasswordInput(BuildContext context) async {
  396. _textFieldController.clear();
  397. return showDialog<String>(
  398. context: context,
  399. builder: (context) {
  400. bool passwordVisible = false;
  401. return StatefulBuilder(
  402. builder: (context, setState) {
  403. return AlertDialog(
  404. title: const Text('Enter password'),
  405. content: TextFormField(
  406. autofillHints: const [AutofillHints.newPassword],
  407. decoration: InputDecoration(
  408. hintText: "Password",
  409. contentPadding: const EdgeInsets.all(12),
  410. suffixIcon: IconButton(
  411. icon: Icon(
  412. passwordVisible ? Icons.visibility : Icons.visibility_off,
  413. color: Colors.white.withOpacity(0.5),
  414. size: 20,
  415. ),
  416. onPressed: () {
  417. passwordVisible = !passwordVisible;
  418. setState(() {});
  419. },
  420. ),
  421. ),
  422. obscureText: !passwordVisible,
  423. controller: _textFieldController,
  424. autofocus: true,
  425. autocorrect: false,
  426. keyboardType: TextInputType.visiblePassword,
  427. onChanged: (_) {
  428. setState(() {});
  429. },
  430. ),
  431. actions: <Widget>[
  432. TextButton(
  433. child: Text(
  434. 'Cancel',
  435. style: Theme.of(context).textTheme.subtitle2,
  436. ),
  437. onPressed: () {
  438. Navigator.pop(context, 'cancel');
  439. },
  440. ),
  441. TextButton(
  442. child:
  443. Text('Ok', style: Theme.of(context).textTheme.subtitle2),
  444. onPressed: () {
  445. if (_textFieldController.text.trim().isEmpty) {
  446. return;
  447. }
  448. Navigator.pop(context, 'ok');
  449. },
  450. ),
  451. ],
  452. );
  453. },
  454. );
  455. },
  456. );
  457. }
  458. Future<Map<String, dynamic>> _getEncryptedPassword(String pass) async {
  459. assert(
  460. Sodium.cryptoPwhashAlgArgon2id13 == Sodium.cryptoPwhashAlgDefault,
  461. "mismatch in expected default pw hashing algo",
  462. );
  463. final int memLimit = Sodium.cryptoPwhashMemlimitInteractive;
  464. final int opsLimit = Sodium.cryptoPwhashOpslimitInteractive;
  465. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  466. final result = await CryptoUtil.deriveKey(
  467. utf8.encode(pass) as Uint8List,
  468. kekSalt,
  469. memLimit,
  470. opsLimit,
  471. );
  472. return {
  473. 'passHash': Sodium.bin2base64(result),
  474. 'nonce': Sodium.bin2base64(kekSalt),
  475. 'memLimit': memLimit,
  476. 'opsLimit': opsLimit,
  477. };
  478. }
  479. Future<void> _updateUrlSettings(
  480. BuildContext context,
  481. Map<String, dynamic> prop,
  482. ) async {
  483. final dialog = createProgressDialog(context, "Please wait...");
  484. await dialog.show();
  485. try {
  486. await CollectionsService.instance
  487. .updateShareUrl(widget.collection!, prop);
  488. await dialog.hide();
  489. showShortToast(context, "Album updated");
  490. } catch (e) {
  491. await dialog.hide();
  492. await showGenericErrorDialog(context: context);
  493. }
  494. }
  495. Future<void> _showDeviceLimitPicker() async {
  496. final List<Text> options = [];
  497. for (int i = 50; i > 0; i--) {
  498. options.add(
  499. Text(i.toString(), style: Theme.of(context).textTheme.subtitle1),
  500. );
  501. }
  502. return showCupertinoModalPopup(
  503. context: context,
  504. builder: (context) {
  505. return Column(
  506. mainAxisAlignment: MainAxisAlignment.end,
  507. children: <Widget>[
  508. Container(
  509. decoration: BoxDecoration(
  510. color: Theme.of(context).colorScheme.cupertinoPickerTopColor,
  511. border: const Border(
  512. bottom: BorderSide(
  513. color: Color(0xff999999),
  514. width: 0.0,
  515. ),
  516. ),
  517. ),
  518. child: Row(
  519. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  520. children: <Widget>[
  521. CupertinoButton(
  522. onPressed: () {
  523. Navigator.of(context).pop('cancel');
  524. },
  525. padding: const EdgeInsets.symmetric(
  526. horizontal: 8.0,
  527. vertical: 5.0,
  528. ),
  529. child: Text(
  530. 'Cancel',
  531. style: Theme.of(context).textTheme.subtitle1,
  532. ),
  533. ),
  534. CupertinoButton(
  535. onPressed: () async {
  536. await _updateUrlSettings(context, {
  537. 'deviceLimit': int.tryParse(
  538. options[_selectedDeviceLimitIndex].data!,
  539. ),
  540. });
  541. setState(() {});
  542. Navigator.of(context).pop('');
  543. },
  544. padding: const EdgeInsets.symmetric(
  545. horizontal: 16.0,
  546. vertical: 2.0,
  547. ),
  548. child: Text(
  549. 'Confirm',
  550. style: Theme.of(context).textTheme.subtitle1,
  551. ),
  552. )
  553. ],
  554. ),
  555. ),
  556. Container(
  557. height: 220.0,
  558. color: const Color(0xfff7f7f7),
  559. child: CupertinoPicker(
  560. backgroundColor:
  561. Theme.of(context).backgroundColor.withOpacity(0.95),
  562. onSelectedItemChanged: (value) {
  563. _selectedDeviceLimitIndex = value;
  564. },
  565. magnification: 1.3,
  566. useMagnifier: true,
  567. itemExtent: 25,
  568. diameterRatio: 1,
  569. children: options,
  570. ),
  571. )
  572. ],
  573. );
  574. },
  575. );
  576. }
  577. }