manage_links_widget.dart 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. debugPrint("Setting expirty $newValidTill");
  320. await updateTime(newValidTill);
  321. }
  322. },
  323. padding: const EdgeInsets.symmetric(
  324. horizontal: 16.0,
  325. vertical: 2.0,
  326. ),
  327. child: Text(
  328. 'Confirm',
  329. style: Theme.of(context).textTheme.subtitle1,
  330. ),
  331. )
  332. ],
  333. ),
  334. ),
  335. Container(
  336. height: 220.0,
  337. color: const Color(0xfff7f7f7),
  338. child: CupertinoPicker(
  339. backgroundColor:
  340. Theme.of(context).backgroundColor.withOpacity(0.95),
  341. onSelectedItemChanged: (value) {
  342. final firstWhere = _expiryOptions
  343. .firstWhere((element) => element.item1 == value);
  344. setState(() {
  345. _selectedExpiry = firstWhere;
  346. });
  347. },
  348. magnification: 1.3,
  349. useMagnifier: true,
  350. itemExtent: 25,
  351. diameterRatio: 1,
  352. children: _expiryOptions
  353. .map(
  354. (e) => Text(e.item2,
  355. style: Theme.of(context).textTheme.subtitle1),
  356. )
  357. .toList(),
  358. ),
  359. )
  360. ],
  361. );
  362. },
  363. );
  364. }
  365. Future<void> updateTime(int newValidTill) async {
  366. await _updateUrlSettings(
  367. context,
  368. {'validTill': newValidTill},
  369. );
  370. if (mounted) {
  371. // reset to default value. THis is needed will we move to
  372. // new selection menu as per figma/
  373. _selectedExpiry = _expiryOptions.first;
  374. setState(() {});
  375. }
  376. }
  377. // _showDateTimePicker return null if user doesn't select date-time
  378. Future<int?> _showDateTimePicker() async {
  379. final dateResult = await DatePicker.showDatePicker(
  380. context,
  381. minTime: DateTime.now(),
  382. currentTime: DateTime.now(),
  383. locale: LocaleType.en,
  384. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  385. );
  386. if (dateResult == null) {
  387. return null;
  388. }
  389. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  390. context,
  391. showTitleActions: true,
  392. currentTime: dateResult,
  393. locale: LocaleType.en,
  394. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  395. );
  396. if (dateWithTimeResult == null) {
  397. return null;
  398. } else {
  399. return dateWithTimeResult.microsecondsSinceEpoch;
  400. }
  401. }
  402. final TextEditingController _textFieldController = TextEditingController();
  403. Future<String?> _displayLinkPasswordInput(BuildContext context) async {
  404. _textFieldController.clear();
  405. return showDialog<String>(
  406. context: context,
  407. builder: (context) {
  408. bool passwordVisible = false;
  409. return StatefulBuilder(
  410. builder: (context, setState) {
  411. return AlertDialog(
  412. title: const Text('Enter password'),
  413. content: TextFormField(
  414. autofillHints: const [AutofillHints.newPassword],
  415. decoration: InputDecoration(
  416. hintText: "Password",
  417. contentPadding: const EdgeInsets.all(12),
  418. suffixIcon: IconButton(
  419. icon: Icon(
  420. passwordVisible ? Icons.visibility : Icons.visibility_off,
  421. color: Colors.white.withOpacity(0.5),
  422. size: 20,
  423. ),
  424. onPressed: () {
  425. passwordVisible = !passwordVisible;
  426. setState(() {});
  427. },
  428. ),
  429. ),
  430. obscureText: !passwordVisible,
  431. controller: _textFieldController,
  432. autofocus: true,
  433. autocorrect: false,
  434. keyboardType: TextInputType.visiblePassword,
  435. onChanged: (_) {
  436. setState(() {});
  437. },
  438. ),
  439. actions: <Widget>[
  440. TextButton(
  441. child: Text(
  442. 'Cancel',
  443. style: Theme.of(context).textTheme.subtitle2,
  444. ),
  445. onPressed: () {
  446. Navigator.pop(context, 'cancel');
  447. },
  448. ),
  449. TextButton(
  450. child:
  451. Text('Ok', style: Theme.of(context).textTheme.subtitle2),
  452. onPressed: () {
  453. if (_textFieldController.text.trim().isEmpty) {
  454. return;
  455. }
  456. Navigator.pop(context, 'ok');
  457. },
  458. ),
  459. ],
  460. );
  461. },
  462. );
  463. },
  464. );
  465. }
  466. Future<Map<String, dynamic>> _getEncryptedPassword(String pass) async {
  467. assert(
  468. Sodium.cryptoPwhashAlgArgon2id13 == Sodium.cryptoPwhashAlgDefault,
  469. "mismatch in expected default pw hashing algo",
  470. );
  471. final int memLimit = Sodium.cryptoPwhashMemlimitInteractive;
  472. final int opsLimit = Sodium.cryptoPwhashOpslimitInteractive;
  473. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  474. final result = await CryptoUtil.deriveKey(
  475. utf8.encode(pass) as Uint8List,
  476. kekSalt,
  477. memLimit,
  478. opsLimit,
  479. );
  480. return {
  481. 'passHash': Sodium.bin2base64(result),
  482. 'nonce': Sodium.bin2base64(kekSalt),
  483. 'memLimit': memLimit,
  484. 'opsLimit': opsLimit,
  485. };
  486. }
  487. Future<void> _updateUrlSettings(
  488. BuildContext context,
  489. Map<String, dynamic> prop,
  490. ) async {
  491. final dialog = createProgressDialog(context, "Please wait...");
  492. await dialog.show();
  493. try {
  494. await CollectionsService.instance
  495. .updateShareUrl(widget.collection!, prop);
  496. await dialog.hide();
  497. showShortToast(context, "Album updated");
  498. } catch (e) {
  499. await dialog.hide();
  500. await showGenericErrorDialog(context: context);
  501. }
  502. }
  503. Future<void> _showDeviceLimitPicker() async {
  504. final List<Text> options = [];
  505. for (int i = 50; i > 0; i--) {
  506. options.add(
  507. Text(i.toString(), style: Theme.of(context).textTheme.subtitle1),
  508. );
  509. }
  510. return showCupertinoModalPopup(
  511. context: context,
  512. builder: (context) {
  513. return Column(
  514. mainAxisAlignment: MainAxisAlignment.end,
  515. children: <Widget>[
  516. Container(
  517. decoration: BoxDecoration(
  518. color: Theme.of(context).colorScheme.cupertinoPickerTopColor,
  519. border: const Border(
  520. bottom: BorderSide(
  521. color: Color(0xff999999),
  522. width: 0.0,
  523. ),
  524. ),
  525. ),
  526. child: Row(
  527. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  528. children: <Widget>[
  529. CupertinoButton(
  530. onPressed: () {
  531. Navigator.of(context).pop('cancel');
  532. },
  533. padding: const EdgeInsets.symmetric(
  534. horizontal: 8.0,
  535. vertical: 5.0,
  536. ),
  537. child: Text(
  538. 'Cancel',
  539. style: Theme.of(context).textTheme.subtitle1,
  540. ),
  541. ),
  542. CupertinoButton(
  543. onPressed: () async {
  544. await _updateUrlSettings(context, {
  545. 'deviceLimit': int.tryParse(
  546. options[_selectedDeviceLimitIndex].data!,
  547. ),
  548. });
  549. setState(() {});
  550. Navigator.of(context).pop('');
  551. },
  552. padding: const EdgeInsets.symmetric(
  553. horizontal: 16.0,
  554. vertical: 2.0,
  555. ),
  556. child: Text(
  557. 'Confirm',
  558. style: Theme.of(context).textTheme.subtitle1,
  559. ),
  560. )
  561. ],
  562. ),
  563. ),
  564. Container(
  565. height: 220.0,
  566. color: const Color(0xfff7f7f7),
  567. child: CupertinoPicker(
  568. backgroundColor:
  569. Theme.of(context).backgroundColor.withOpacity(0.95),
  570. onSelectedItemChanged: (value) {
  571. _selectedDeviceLimitIndex = value;
  572. },
  573. magnification: 1.3,
  574. useMagnifier: true,
  575. itemExtent: 25,
  576. diameterRatio: 1,
  577. children: options,
  578. ),
  579. )
  580. ],
  581. );
  582. },
  583. );
  584. }
  585. }