lemmur-app-android/lib/pages/manage_account.dart

567 lines
19 KiB
Dart
Raw Normal View History

2021-01-06 00:51:19 +01:00
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
2021-01-06 18:45:56 +01:00
import 'package:image_picker/image_picker.dart';
2021-01-24 20:01:55 +01:00
import 'package:lemmy_api_client/pictrs.dart';
import 'package:lemmy_api_client/v2.dart';
2021-01-06 00:51:19 +01:00
2021-01-06 18:45:56 +01:00
import '../hooks/delayed_loading.dart';
import '../hooks/image_picker.dart';
import '../hooks/ref.dart';
2021-01-06 00:51:19 +01:00
import '../hooks/stores.dart';
2021-01-06 18:45:56 +01:00
import '../util/pictrs.dart';
2021-01-26 23:51:02 +01:00
import '../widgets/bottom_safe.dart';
2021-01-06 00:51:19 +01:00
2021-01-06 18:45:56 +01:00
/// Page for managing things like username, email, avatar etc
/// This page will assume the manage account is logged in and
/// its token is in AccountsStore
class ManageAccountPage extends HookWidget {
2021-01-06 00:51:19 +01:00
final String instanceHost;
final String username;
2021-01-06 18:45:56 +01:00
const ManageAccountPage(
{@required this.instanceHost, @required this.username})
2021-01-06 00:51:19 +01:00
: assert(instanceHost != null),
assert(username != null);
@override
Widget build(BuildContext context) {
final accountStore = useAccountsStore();
final theme = Theme.of(context);
2021-01-06 18:45:56 +01:00
final userFuture = useMemoized(() async {
2021-01-24 20:01:55 +01:00
final site = await LemmyApiV2(instanceHost).run(
GetSite(auth: accountStore.tokenFor(instanceHost, username).raw));
2021-01-06 00:51:19 +01:00
2021-01-06 18:45:56 +01:00
return site.myUser;
2021-01-06 00:51:19 +01:00
});
return Scaffold(
appBar: AppBar(
backgroundColor: theme.scaffoldBackgroundColor,
brightness: theme.brightness,
shadowColor: Colors.transparent,
iconTheme: theme.iconTheme,
title:
2021-01-06 19:11:01 +01:00
Text('@$instanceHost@$username', style: theme.textTheme.headline6),
2021-01-06 00:51:19 +01:00
centerTitle: true,
),
2021-01-24 20:01:55 +01:00
body: FutureBuilder<UserSafeSettings>(
2021-01-06 18:45:56 +01:00
future: userFuture,
builder: (_, userSnap) {
if (userSnap.hasError) {
return Center(child: Text('Error: ${userSnap.error?.toString()}'));
2021-01-06 00:51:19 +01:00
}
2021-01-06 18:45:56 +01:00
if (!userSnap.hasData) {
2021-01-06 00:51:19 +01:00
return const Center(child: CircularProgressIndicator());
}
2021-01-06 18:45:56 +01:00
return _ManageAccount(user: userSnap.data);
},
),
);
}
}
class _ManageAccount extends HookWidget {
const _ManageAccount({Key key, @required this.user})
: assert(user != null),
super(key: key);
2021-01-24 20:01:55 +01:00
final UserSafeSettings user;
2021-01-06 18:45:56 +01:00
@override
Widget build(BuildContext context) {
2021-01-06 19:11:01 +01:00
final accountsStore = useAccountsStore();
2021-01-06 18:45:56 +01:00
final theme = Theme.of(context);
2021-01-06 19:11:01 +01:00
final saveDelayedLoading = useDelayedLoading();
final deleteDelayedLoading = useDelayedLoading();
2021-01-06 18:45:56 +01:00
final displayNameController =
useTextEditingController(text: user.preferredUsername);
final bioController = useTextEditingController(text: user.bio);
final emailController = useTextEditingController(text: user.email);
2021-01-17 17:21:46 +01:00
final matrixUserController =
useTextEditingController(text: user.matrixUserId);
2021-01-06 18:45:56 +01:00
final avatar = useRef(user.avatar);
final banner = useRef(user.banner);
2021-01-17 17:21:46 +01:00
final showAvatars = useState(user.showAvatars);
final showNsfw = useState(user.showNsfw);
final sendNotificationsToEmail = useState(user.sendNotificationsToEmail);
final defaultListingType = useState(user.defaultListingType);
final defaultSortType = useState(user.defaultSortType);
final newPasswordController = useTextEditingController();
final newPasswordVerifyController = useTextEditingController();
final oldPasswordController = useTextEditingController();
2021-01-06 18:45:56 +01:00
2021-01-08 09:47:59 +01:00
final informAcceptedAvatarRef = useRef<VoidCallback>(null);
final informAcceptedBannerRef = useRef<VoidCallback>(null);
2021-01-06 19:11:01 +01:00
final deleteAccountPasswordController = useTextEditingController();
2021-01-17 17:35:47 +01:00
final token = accountsStore.tokenFor(user.instanceHost, user.name);
2021-01-06 18:45:56 +01:00
handleSubmit() async {
2021-01-06 19:11:01 +01:00
saveDelayedLoading.start();
2021-01-06 18:45:56 +01:00
try {
2021-01-24 20:01:55 +01:00
await LemmyApiV2(user.instanceHost).run(SaveUserSettings(
showNsfw: showNsfw.value,
theme: user.theme,
defaultSortType: defaultSortType.value,
defaultListingType: defaultListingType.value,
lang: user.lang,
showAvatars: showAvatars.value,
sendNotificationsToEmail: sendNotificationsToEmail.value,
auth: token.raw,
avatar: avatar.current,
banner: banner.current,
newPassword: newPasswordController.text.isEmpty
? null
: newPasswordController.text,
newPasswordVerify: newPasswordVerifyController.text.isEmpty
? null
: newPasswordVerifyController.text,
oldPassword: oldPasswordController.text.isEmpty
? null
: oldPasswordController.text,
matrixUserId: matrixUserController.text.isEmpty
? null
: matrixUserController.text,
preferredUsername: displayNameController.text.isEmpty
? null
: displayNameController.text,
bio: bioController.text.isEmpty ? null : bioController.text,
email: emailController.text.isEmpty ? null : emailController.text,
));
2021-01-08 09:47:59 +01:00
informAcceptedAvatarRef.current();
informAcceptedBannerRef.current();
2021-01-06 19:11:01 +01:00
Scaffold.of(context).showSnackBar(const SnackBar(
content: Text('User settings saved'),
));
2021-01-06 18:45:56 +01:00
} on Exception catch (err) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(err.toString()),
));
2021-01-17 17:21:46 +01:00
} finally {
saveDelayedLoading.cancel();
2021-01-06 18:45:56 +01:00
}
2021-01-06 19:11:01 +01:00
}
deleteAccountDialog() async {
final confirmDelete = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Remove account?'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'''Are you sure you want to remove @${user.instanceHost}@${user.name}? '''
'''WARNING: this removes your account COMPLETELY, not from lemmur only''',
),
TextField(
controller: deleteAccountPasswordController,
obscureText: true,
decoration: const InputDecoration(hintText: 'Password'),
)
],
),
actions: [
FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('no'),
),
FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('yes'),
),
],
),
) ??
false;
if (confirmDelete) {
deleteDelayedLoading.start();
try {
2021-01-24 20:01:55 +01:00
await LemmyApiV2(user.instanceHost).run(DeleteAccount(
password: deleteAccountPasswordController.text,
auth: token.raw,
));
2021-01-06 19:11:01 +01:00
accountsStore.removeAccount(user.instanceHost, user.name);
Navigator.of(context).pop();
} on Exception catch (err) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(err.toString()),
));
}
deleteDelayedLoading.cancel();
} else {
deleteAccountPasswordController.clear();
}
2021-01-06 18:45:56 +01:00
}
return ListView(
2021-01-17 18:57:57 +01:00
padding: const EdgeInsets.symmetric(horizontal: 15),
2021-01-06 18:45:56 +01:00
children: [
_ImagePicker(
user: user,
name: 'Avatar',
initialUrl: avatar.current,
onChange: (value) => avatar.current = value,
2021-01-08 09:47:59 +01:00
informAcceptedRef: informAcceptedAvatarRef,
2021-01-06 18:45:56 +01:00
),
const SizedBox(height: 8),
_ImagePicker(
user: user,
name: 'Banner',
initialUrl: banner.current,
onChange: (value) => banner.current = value,
2021-01-08 09:47:59 +01:00
informAcceptedRef: informAcceptedBannerRef,
2021-01-06 18:45:56 +01:00
),
const SizedBox(height: 8),
Text('Display Name', style: theme.textTheme.headline6),
TextField(
controller: displayNameController,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Text('Bio', style: theme.textTheme.headline6),
TextField(
controller: bioController,
minLines: 4,
maxLines: 10,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Text('Email', style: theme.textTheme.headline6),
TextField(
controller: emailController,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
2021-01-17 17:21:46 +01:00
Text('Matrix User', style: theme.textTheme.headline6),
TextField(
controller: matrixUserController,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Text('New password', style: theme.textTheme.headline6),
TextField(
controller: newPasswordController,
obscureText: true,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Text('Verify password', style: theme.textTheme.headline6),
TextField(
controller: newPasswordVerifyController,
obscureText: true,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Text('Old password', style: theme.textTheme.headline6),
TextField(
controller: oldPasswordController,
obscureText: true,
decoration: InputDecoration(
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('Sort type'),
Text(
'This has currently no effect on lemmur',
style: TextStyle(fontSize: 10),
)
],
),
DropdownButton<PostListingType>(
items: [
for (final postListingType in [
PostListingType.all,
PostListingType.local,
PostListingType.subscribed,
])
DropdownMenuItem(
value: postListingType,
child: Text(postListingType.value),
)
],
onChanged: (value) => defaultListingType.value = value,
value: defaultListingType.value,
isDense: true,
),
],
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('Type'),
Text(
'This has currently no effect on lemmur',
style: TextStyle(fontSize: 10),
)
],
),
DropdownButton<SortType>(
items: [
for (final defaultSortType in SortType.values)
DropdownMenuItem(
value: defaultSortType,
child: Text(defaultSortType.value),
)
],
onChanged: (value) => defaultSortType.value = value,
value: defaultSortType.value,
isDense: true,
),
],
),
const SizedBox(height: 8),
CheckboxListTile(
value: showAvatars.value,
onChanged: (checked) => showAvatars.value = checked,
title: const Text('Show avatars'),
subtitle: const Text('This has currently no effect on lemmur'),
dense: true,
),
const SizedBox(height: 8),
CheckboxListTile(
value: showNsfw.value,
onChanged: (checked) => showNsfw.value = checked,
title: const Text('Show NSFW content'),
subtitle: const Text('This has currently no effect on lemmur'),
dense: true,
),
const SizedBox(height: 8),
CheckboxListTile(
value: sendNotificationsToEmail.value,
onChanged: (checked) => sendNotificationsToEmail.value = checked,
title: const Text('Send notifications to Email'),
dense: true,
),
const SizedBox(height: 8),
2021-01-06 18:45:56 +01:00
ElevatedButton(
2021-01-06 19:11:01 +01:00
onPressed: saveDelayedLoading.loading ? null : handleSubmit,
2021-01-06 18:45:56 +01:00
style: ElevatedButton.styleFrom(
visualDensity: VisualDensity.comfortable,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
2021-01-06 19:11:01 +01:00
child: saveDelayedLoading.loading
2021-01-06 18:45:56 +01:00
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(),
)
: const Text('save'),
),
const SizedBox(height: 8),
ElevatedButton(
2021-01-06 19:11:01 +01:00
onPressed: deleteAccountDialog,
2021-01-06 18:45:56 +01:00
style: ElevatedButton.styleFrom(
primary: Colors.red,
visualDensity: VisualDensity.comfortable,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: const Text('DELETE ACCOUNT'),
),
2021-01-26 23:16:47 +01:00
const BottomSafe(),
2021-01-06 18:45:56 +01:00
],
);
}
}
/// Picker and cleanuper for local images uploaded to pictrs
class _ImagePicker extends HookWidget {
final String name;
final String initialUrl;
2021-01-24 20:01:55 +01:00
final UserSafeSettings user;
2021-01-06 18:45:56 +01:00
final ValueChanged<String> onChange;
/// _ImagePicker will set the ref to a callback that can inform _ImagePicker
/// that the current picture is accepted
2021-01-08 09:47:59 +01:00
/// and should no longer allow for deletion of it
final Ref<VoidCallback> informAcceptedRef;
2021-01-06 18:45:56 +01:00
const _ImagePicker({
Key key,
@required this.initialUrl,
@required this.name,
@required this.user,
@required this.onChange,
@required this.informAcceptedRef,
2021-01-06 18:45:56 +01:00
}) : assert(name != null),
assert(user != null),
super(key: key);
@override
Widget build(BuildContext context) {
// this is in case the passed initialUrl is changed,
// basically saves the very first initialUrl
final initialUrl = useRef(this.initialUrl);
2021-01-06 18:45:56 +01:00
final theme = Theme.of(context);
final url = useState(initialUrl.current);
2021-01-06 18:45:56 +01:00
final pictrsDeleteToken = useState<PictrsUploadFile>(null);
final imagePicker = useImagePicker();
final accountsStore = useAccountsStore();
final delayedLoading = useDelayedLoading();
2021-01-06 18:45:56 +01:00
uploadImage() async {
try {
final pic = await imagePicker.getImage(source: ImageSource.gallery);
// pic is null when the picker was cancelled
if (pic != null) {
delayedLoading.start();
2021-01-24 20:01:55 +01:00
final upload = await PictrsApi(user.instanceHost).upload(
filePath: pic.path,
auth: accountsStore.tokenFor(user.instanceHost, user.name).raw,
);
2021-01-06 18:45:56 +01:00
pictrsDeleteToken.value = upload.files[0];
url.value =
pathToPictrs(user.instanceHost, pictrsDeleteToken.value.file);
onChange?.call(url.value);
}
} on Exception catch (_) {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('Failed to upload image')));
}
delayedLoading.cancel();
2021-01-06 18:45:56 +01:00
}
removePicture({bool updateState = true}) {
2021-01-24 20:01:55 +01:00
PictrsApi(user.instanceHost)
2021-01-06 18:45:56 +01:00
.delete(pictrsDeleteToken.value)
.catchError((_) {});
if (updateState) {
pictrsDeleteToken.value = null;
url.value = initialUrl.current;
onChange?.call(url.value);
2021-01-06 18:45:56 +01:00
}
}
useEffect(() {
informAcceptedRef.current = () {
pictrsDeleteToken.value = null;
initialUrl.current = url.value;
};
return () {
2021-01-06 18:45:56 +01:00
// remove picture from pictrs when exiting
if (pictrsDeleteToken.value != null) {
removePicture(updateState: false);
}
};
}, []);
2021-01-06 18:45:56 +01:00
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(name, style: theme.textTheme.headline6),
if (pictrsDeleteToken.value == null)
2021-01-06 00:51:19 +01:00
ElevatedButton(
onPressed: delayedLoading.loading ? null : uploadImage,
2021-01-06 00:51:19 +01:00
style: ElevatedButton.styleFrom(
visualDensity: VisualDensity.comfortable,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: delayedLoading.loading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator())
: Row(
children: const [Text('upload'), Icon(Icons.publish)],
),
2021-01-06 18:45:56 +01:00
)
else
IconButton(
icon: const Icon(Icons.close),
onPressed: removePicture,
)
],
),
if (url.value != null)
CachedNetworkImage(
imageUrl: url.value,
errorWidget: (_, __, ___) => const Icon(Icons.error),
),
],
2021-01-06 00:51:19 +01:00
);
}
}