manage_links_widget.dart 23 KB

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