manage_links_widget.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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/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. trailingWidget: Switch.adaptive(
  77. value: widget.collection!.publicURLs?.firstOrNull
  78. ?.enableCollect ??
  79. false,
  80. onChanged: (value) async {
  81. await _updateUrlSettings(
  82. context,
  83. {'enableCollect': value},
  84. );
  85. setState(() {});
  86. },
  87. ),
  88. ),
  89. const MenuSectionDescriptionWidget(
  90. content:
  91. "Allow people with the link to also add photos to the shared "
  92. "album.",
  93. ),
  94. const SizedBox(height: 24),
  95. MenuItemWidget(
  96. alignCaptionedTextToLeft: true,
  97. captionedTextWidget: CaptionedTextWidget(
  98. title: "Link expiry",
  99. subTitle: (url.hasExpiry
  100. ? (url.isExpired ? "Expired" : "Enabled")
  101. : "Never"),
  102. subTitleColor: url.isExpired ? warning500 : null,
  103. ),
  104. trailingIcon: Icons.chevron_right,
  105. menuItemColor: enteColorScheme.fillFaint,
  106. surfaceExecutionStates: false,
  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. surfaceExecutionStates: false,
  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. 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. trailingWidget: Switch.adaptive(
  180. value: widget.collection!.publicURLs?.firstOrNull
  181. ?.passwordEnabled ??
  182. false,
  183. onChanged: (enablePassword) async {
  184. if (enablePassword) {
  185. final inputResult =
  186. await _displayLinkPasswordInput(context);
  187. if (inputResult != null &&
  188. inputResult == 'ok' &&
  189. _textFieldController.text.trim().isNotEmpty) {
  190. final propToUpdate = await _getEncryptedPassword(
  191. _textFieldController.text,
  192. );
  193. await _updateUrlSettings(context, propToUpdate);
  194. }
  195. } else {
  196. await _updateUrlSettings(
  197. context,
  198. {'disablePassword': true},
  199. );
  200. }
  201. setState(() {});
  202. },
  203. ),
  204. ),
  205. const SizedBox(
  206. height: 24,
  207. ),
  208. MenuItemWidget(
  209. captionedTextWidget: const CaptionedTextWidget(
  210. title: "Remove link",
  211. textColor: warning500,
  212. makeTextBold: true,
  213. ),
  214. leadingIcon: Icons.remove_circle_outline,
  215. leadingIconColor: warning500,
  216. menuItemColor: getEnteColorScheme(context).fillFaint,
  217. surfaceExecutionStates: false,
  218. onTap: () async {
  219. final bool result = await sharingActions.disableUrl(
  220. context,
  221. widget.collection!,
  222. );
  223. if (result && mounted) {
  224. Navigator.of(context).pop();
  225. // setState(() => {});
  226. }
  227. },
  228. ),
  229. ],
  230. ),
  231. ),
  232. ],
  233. ),
  234. ),
  235. );
  236. }
  237. Future<void> showPicker() async {
  238. return showCupertinoModalPopup(
  239. context: context,
  240. builder: (context) {
  241. return Column(
  242. mainAxisAlignment: MainAxisAlignment.end,
  243. children: <Widget>[
  244. Container(
  245. decoration: BoxDecoration(
  246. color: Theme.of(context).colorScheme.cupertinoPickerTopColor,
  247. border: const Border(
  248. bottom: BorderSide(
  249. color: Color(0xff999999),
  250. width: 0.0,
  251. ),
  252. ),
  253. ),
  254. child: Row(
  255. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  256. children: <Widget>[
  257. CupertinoButton(
  258. onPressed: () {
  259. Navigator.of(context).pop('cancel');
  260. },
  261. padding: const EdgeInsets.symmetric(
  262. horizontal: 8.0,
  263. vertical: 5.0,
  264. ),
  265. child: Text(
  266. 'Cancel',
  267. style: Theme.of(context).textTheme.subtitle1,
  268. ),
  269. ),
  270. CupertinoButton(
  271. onPressed: () async {
  272. int newValidTill = -1;
  273. bool hasSelectedCustom = false;
  274. final int expireAfterInMicroseconds =
  275. _selectedExpiry.item3;
  276. // need to manually select time
  277. if (expireAfterInMicroseconds < 0) {
  278. hasSelectedCustom = true;
  279. Navigator.of(context).pop('');
  280. final timeInMicrosecondsFromEpoch =
  281. await _showDateTimePicker();
  282. if (timeInMicrosecondsFromEpoch != null) {
  283. newValidTill = timeInMicrosecondsFromEpoch;
  284. }
  285. } else if (expireAfterInMicroseconds == 0) {
  286. // no expiry
  287. newValidTill = 0;
  288. } else {
  289. newValidTill = DateTime.now().microsecondsSinceEpoch +
  290. expireAfterInMicroseconds;
  291. }
  292. if (!hasSelectedCustom) {
  293. Navigator.of(context).pop('');
  294. }
  295. if (newValidTill >= 0) {
  296. debugPrint("Setting expirty $newValidTill");
  297. await updateTime(newValidTill);
  298. }
  299. },
  300. padding: const EdgeInsets.symmetric(
  301. horizontal: 16.0,
  302. vertical: 2.0,
  303. ),
  304. child: Text(
  305. 'Confirm',
  306. style: Theme.of(context).textTheme.subtitle1,
  307. ),
  308. )
  309. ],
  310. ),
  311. ),
  312. Container(
  313. height: 220.0,
  314. color: const Color(0xfff7f7f7),
  315. child: CupertinoPicker(
  316. backgroundColor:
  317. Theme.of(context).backgroundColor.withOpacity(0.95),
  318. onSelectedItemChanged: (value) {
  319. final firstWhere = _expiryOptions
  320. .firstWhere((element) => element.item1 == value);
  321. setState(() {
  322. _selectedExpiry = firstWhere;
  323. });
  324. },
  325. magnification: 1.3,
  326. useMagnifier: true,
  327. itemExtent: 25,
  328. diameterRatio: 1,
  329. children: _expiryOptions
  330. .map(
  331. (e) => Text(
  332. e.item2,
  333. style: Theme.of(context).textTheme.subtitle1,
  334. ),
  335. )
  336. .toList(),
  337. ),
  338. )
  339. ],
  340. );
  341. },
  342. );
  343. }
  344. Future<void> updateTime(int newValidTill) async {
  345. await _updateUrlSettings(
  346. context,
  347. {'validTill': newValidTill},
  348. );
  349. if (mounted) {
  350. // reset to default value. THis is needed will we move to
  351. // new selection menu as per figma/
  352. _selectedExpiry = _expiryOptions.first;
  353. setState(() {});
  354. }
  355. }
  356. // _showDateTimePicker return null if user doesn't select date-time
  357. Future<int?> _showDateTimePicker() async {
  358. final dateResult = await DatePicker.showDatePicker(
  359. context,
  360. minTime: DateTime.now(),
  361. currentTime: DateTime.now(),
  362. locale: LocaleType.en,
  363. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  364. );
  365. if (dateResult == null) {
  366. return null;
  367. }
  368. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  369. context,
  370. showTitleActions: true,
  371. currentTime: dateResult,
  372. locale: LocaleType.en,
  373. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  374. );
  375. if (dateWithTimeResult == null) {
  376. return null;
  377. } else {
  378. return dateWithTimeResult.microsecondsSinceEpoch;
  379. }
  380. }
  381. final TextEditingController _textFieldController = TextEditingController();
  382. Future<String?> _displayLinkPasswordInput(BuildContext context) async {
  383. _textFieldController.clear();
  384. return showDialog<String>(
  385. context: context,
  386. builder: (context) {
  387. bool passwordVisible = false;
  388. return StatefulBuilder(
  389. builder: (context, setState) {
  390. return AlertDialog(
  391. title: const Text('Enter password'),
  392. content: TextFormField(
  393. autofillHints: const [AutofillHints.newPassword],
  394. decoration: InputDecoration(
  395. hintText: "Password",
  396. contentPadding: const EdgeInsets.all(12),
  397. suffixIcon: IconButton(
  398. icon: Icon(
  399. passwordVisible ? Icons.visibility : Icons.visibility_off,
  400. color: Colors.white.withOpacity(0.5),
  401. size: 20,
  402. ),
  403. onPressed: () {
  404. passwordVisible = !passwordVisible;
  405. setState(() {});
  406. },
  407. ),
  408. ),
  409. obscureText: !passwordVisible,
  410. controller: _textFieldController,
  411. autofocus: true,
  412. autocorrect: false,
  413. keyboardType: TextInputType.visiblePassword,
  414. onChanged: (_) {
  415. setState(() {});
  416. },
  417. ),
  418. actions: <Widget>[
  419. TextButton(
  420. child: Text(
  421. 'Cancel',
  422. style: Theme.of(context).textTheme.subtitle2,
  423. ),
  424. onPressed: () {
  425. Navigator.pop(context, 'cancel');
  426. },
  427. ),
  428. TextButton(
  429. child:
  430. Text('Ok', style: Theme.of(context).textTheme.subtitle2),
  431. onPressed: () {
  432. if (_textFieldController.text.trim().isEmpty) {
  433. return;
  434. }
  435. Navigator.pop(context, 'ok');
  436. },
  437. ),
  438. ],
  439. );
  440. },
  441. );
  442. },
  443. );
  444. }
  445. Future<Map<String, dynamic>> _getEncryptedPassword(String pass) async {
  446. assert(
  447. Sodium.cryptoPwhashAlgArgon2id13 == Sodium.cryptoPwhashAlgDefault,
  448. "mismatch in expected default pw hashing algo",
  449. );
  450. final int memLimit = Sodium.cryptoPwhashMemlimitInteractive;
  451. final int opsLimit = Sodium.cryptoPwhashOpslimitInteractive;
  452. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  453. final result = await CryptoUtil.deriveKey(
  454. utf8.encode(pass) as Uint8List,
  455. kekSalt,
  456. memLimit,
  457. opsLimit,
  458. );
  459. return {
  460. 'passHash': Sodium.bin2base64(result),
  461. 'nonce': Sodium.bin2base64(kekSalt),
  462. 'memLimit': memLimit,
  463. 'opsLimit': opsLimit,
  464. };
  465. }
  466. Future<void> _updateUrlSettings(
  467. BuildContext context,
  468. Map<String, dynamic> prop,
  469. ) async {
  470. final dialog = createProgressDialog(context, "Please wait...");
  471. await dialog.show();
  472. try {
  473. await CollectionsService.instance
  474. .updateShareUrl(widget.collection!, prop);
  475. await dialog.hide();
  476. showShortToast(context, "Album updated");
  477. } catch (e) {
  478. await dialog.hide();
  479. await showGenericErrorDialog(context: context);
  480. }
  481. }
  482. Future<void> _showDeviceLimitPicker() async {
  483. final List<Text> options = [];
  484. for (int i = 50; i > 0; i--) {
  485. options.add(
  486. Text(i.toString(), style: Theme.of(context).textTheme.subtitle1),
  487. );
  488. }
  489. return showCupertinoModalPopup(
  490. context: context,
  491. builder: (context) {
  492. return Column(
  493. mainAxisAlignment: MainAxisAlignment.end,
  494. children: <Widget>[
  495. Container(
  496. decoration: BoxDecoration(
  497. color: Theme.of(context).colorScheme.cupertinoPickerTopColor,
  498. border: const Border(
  499. bottom: BorderSide(
  500. color: Color(0xff999999),
  501. width: 0.0,
  502. ),
  503. ),
  504. ),
  505. child: Row(
  506. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  507. children: <Widget>[
  508. CupertinoButton(
  509. onPressed: () {
  510. Navigator.of(context).pop('cancel');
  511. },
  512. padding: const EdgeInsets.symmetric(
  513. horizontal: 8.0,
  514. vertical: 5.0,
  515. ),
  516. child: Text(
  517. 'Cancel',
  518. style: Theme.of(context).textTheme.subtitle1,
  519. ),
  520. ),
  521. CupertinoButton(
  522. onPressed: () async {
  523. await _updateUrlSettings(context, {
  524. 'deviceLimit': int.tryParse(
  525. options[_selectedDeviceLimitIndex].data!,
  526. ),
  527. });
  528. setState(() {});
  529. Navigator.of(context).pop('');
  530. },
  531. padding: const EdgeInsets.symmetric(
  532. horizontal: 16.0,
  533. vertical: 2.0,
  534. ),
  535. child: Text(
  536. 'Confirm',
  537. style: Theme.of(context).textTheme.subtitle1,
  538. ),
  539. )
  540. ],
  541. ),
  542. ),
  543. Container(
  544. height: 220.0,
  545. color: const Color(0xfff7f7f7),
  546. child: CupertinoPicker(
  547. backgroundColor:
  548. Theme.of(context).backgroundColor.withOpacity(0.95),
  549. onSelectedItemChanged: (value) {
  550. _selectedDeviceLimitIndex = value;
  551. },
  552. magnification: 1.3,
  553. useMagnifier: true,
  554. itemExtent: 25,
  555. diameterRatio: 1,
  556. children: options,
  557. ),
  558. )
  559. ],
  560. );
  561. },
  562. );
  563. }
  564. }