manage_links_widget.dart 22 KB

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