add PMP support

Fixes #175
This commit is contained in:
Henry Hiles 2026-11-26 15:31:38 -05:00
commit 3b7a4c0cd4
Signed by: Henry-Hiles
SSH key fingerprint: SHA256:VKQUdS31Q90KvX7EkKMHMBpUspcmItAh86a+v7PGiIs
11 changed files with 469 additions and 1 deletions

View file

@ -5,6 +5,8 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:flutter/foundation.dart"; import "package:flutter/foundation.dart";
import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client.dart";
import "package:nexus/controllers/rooms.dart";
import "package:nexus/models/per_message_profiles.dart";
import "package:nexus/models/account_data.dart"; import "package:nexus/models/account_data.dart";
import "package:nexus/models/push_rules.dart"; import "package:nexus/models/push_rules.dart";
import "package:nexus/models/requests/update_push_rule.dart"; import "package:nexus/models/requests/update_push_rule.dart";
@ -73,6 +75,40 @@ class AccountDataController extends Notifier<AccountData> {
(data) => data.ignoredUserList.contains(userId) == ignored, (data) => data.ignoredUserList.contains(userId) == ignored,
); );
Future<void> setPerMessageProfiles(PerMessageProfiles profiles) =>
_sendAndWait(
() => ref
.read(ClientController.provider.notifier)
.setAccountData(
.new(type: AccountData.perMessageProfilesKey, content: profiles),
),
(data) => data.perMessageProfiles == profiles,
);
Future<void> setRoomProfile(String roomId, String profileId) async {
const type = AccountData.perMessageProfilesKey;
final current = ref
.read(RoomsController.provider)[roomId]
?.accountData[type];
await ref
.read(ClientController.provider.notifier)
.setAccountData(
.new(
type: type,
roomId: roomId,
content: {...?current, "default_profile_id": profileId},
),
);
await ref
.read(RoomsController.provider.notifier)
.awaitRooms(
(rooms) =>
rooms[roomId]?.accountData[type]?["default_profile_id"] ==
profileId,
);
}
/// Saves [rule] of [kind], creating it if it's new, or otherwise changing only /// Saves [rule] of [kind], creating it if it's new, or otherwise changing only
/// its actions and whether it's enabled. /// its actions and whether it's enabled.
Future<void> savePushRule(PushRuleKind kind, PushRule rule) { Future<void> savePushRule(PushRuleKind kind, PushRule rule) {

View file

@ -0,0 +1,56 @@
import "package:collection/collection.dart";
import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:flutter/foundation.dart";
import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:nexus/controllers/account_data.dart";
import "package:nexus/controllers/rooms.dart";
import "package:nexus/models/account_data.dart";
import "package:nexus/models/per_message_profiles.dart";
typedef RoomPersonas = ({
IList<StoredProfile> profiles,
StoredProfile? current,
});
class PersonasController(final String roomId) extends Notifier<RoomPersonas> {
@override
RoomPersonas build() {
final global = ref.watch(
AccountDataController.provider.select((data) => data.perMessageProfiles),
);
final roomJson = ref.watch(
RoomsController.provider.select(
(rooms) =>
rooms[roomId]?.accountData[AccountData.perMessageProfilesKey],
),
);
PerMessageProfiles? room;
if (roomJson != null) {
try {
room = .fromJson(roomJson);
} catch (error) {
debugPrint("Ignoring invalid room per-message profiles: $error");
}
}
final roomIds = room?.profiles.map((profile) => profile.id).toISet();
final profiles = (room?.profiles ?? const IList<StoredProfile>.empty())
.addAll(
global.profiles.where(
(profile) => !(roomIds?.contains(profile.id) ?? false),
),
);
final currentId = room?.defaultProfileId ?? global.defaultProfileId;
return (
profiles: profiles,
current: currentId == null || currentId.isEmpty
? null
: profiles.firstWhereOrNull((profile) => profile.id == currentId),
);
}
static final provider = NotifierProvider.autoDispose
.family<PersonasController, RoomPersonas, String>(PersonasController.new);
}

View file

@ -189,6 +189,7 @@ class RoomsController extends Notifier<IMap<String, Room>> {
? incoming.timeline ? incoming.timeline
: existing.timeline.addAll(incoming.timeline), : existing.timeline.addAll(incoming.timeline),
receipts: mergeReceipts(existing.receipts, incoming.receipts), receipts: mergeReceipts(existing.receipts, incoming.receipts),
accountData: existing.accountData.addAll(incoming.accountData),
) ?? ) ??
incoming.copyWith( incoming.copyWith(
receipts: mergeReceipts(const .empty(), incoming.receipts), receipts: mergeReceipts(const .empty(), incoming.receipts),

View file

@ -43,6 +43,7 @@ import "package:nexus/widgets/settings/block_user_field.dart";
import "package:nexus/widgets/settings/dialog_list_tile.dart"; import "package:nexus/widgets/settings/dialog_list_tile.dart";
import "package:nexus/widgets/settings/enable_image_packs_sheet.dart"; import "package:nexus/widgets/settings/enable_image_packs_sheet.dart";
import "package:nexus/widgets/settings/keyword_field.dart"; import "package:nexus/widgets/settings/keyword_field.dart";
import "package:nexus/widgets/settings/persona_sheet.dart";
import "package:nexus/widgets/users/user_bottom_sheet.dart"; import "package:nexus/widgets/users/user_bottom_sheet.dart";
import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; import "package:nexus/widgets/encryption/reset_encryption_sheet.dart";
@ -51,6 +52,9 @@ class SettingsSectionsController
@override @override
Future<IMap<String, IList<SettingsCategory>>> build() async { Future<IMap<String, IList<SettingsCategory>>> build() async {
final settings = await ref.watch(SettingsController.provider.future); final settings = await ref.watch(SettingsController.provider.future);
final personas = ref.watch(
AccountDataController.provider.select((data) => data.perMessageProfiles),
);
// Not awaited, so a slow homeserver doesn't hold up the rest of settings // Not awaited, so a slow homeserver doesn't hold up the rest of settings
final accountManagement = ref final accountManagement = ref
.watch(AccountManagementController.provider) .watch(AccountManagementController.provider)
@ -443,6 +447,99 @@ class SettingsSectionsController
), ),
]), ]),
), ),
.new(
title: "Personas",
icon: Icons.groups,
settings: .new([
.new(
title: "Enable Personas",
description: "Send messages as other names and avatars, chosen per room from the composer.",
icon: Icons.groups,
builder: (title, description, icon) => SwitchListTile(
title: Text(title),
subtitle: Text(description),
secondary: Icon(icon),
value: settings.personas,
onChanged: (value) => ref
.read(SettingsController.provider.notifier)
.set(settings.copyWith(personas: value))
.onError(showError),
),
),
if (settings.personas) ...[
if (personas.profiles.isNotEmpty)
.new(
title: "Default Persona",
description: "Who you send as in rooms you haven't chosen a persona for.",
icon: Icons.person_pin,
builder: (title, description, icon) =>
DialogListTile<String>(
icon: Icon(icon),
title: title,
subtitle: Text(description),
value: personas.defaultProfileId ?? "",
options: [
"",
...personas.profiles.map((profile) => profile.id),
],
getName: (id) => switch (personas.byId(id)) {
final profile? => profile.displayName ?? id,
null => "Yourself",
},
onChanged: (id) => accountData
.setPerMessageProfiles(
personas.copyWith(
defaultProfileId: id.isEmpty ? null : id,
),
)
.onError(showError),
),
),
header(
"Personas",
"The names and avatars you can send messages as.",
Icons.groups,
),
...personas.profiles.map(
(persona) => Setting(
title: persona.displayName ?? persona.id,
description: "A persona.",
icon: Icons.person,
builder: (title, _, _) => Builder(
builder: (context) => ListTile(
leading: AvatarOrHash(persona.avatarUrl, title),
title: Text(title),
subtitle: switch (persona.triggers.firstOrNull) {
final trigger? => Text(
"Trigger: ${trigger.prefix}text${trigger.suffix}",
),
null => null,
},
trailing: Icon(Icons.chevron_right),
onTap: () => context.showAdaptiveSheet(
(_) => PersonaSheet(persona: persona),
),
),
),
),
),
.new(
title: "Add Persona",
description: "Create a name and avatar to send messages as.",
icon: Icons.add,
builder: (title, _, icon) => Builder(
builder: (context) => ListTile(
leading: Icon(icon),
title: Text(title),
onTap: () => context.showAdaptiveSheet(
(_) => const PersonaSheet(),
),
),
),
),
],
]),
),
.new( .new(
title: "Image Packs", title: "Image Packs",
icon: Icons.emoji_emotions, icon: Icons.emoji_emotions,

View file

@ -1,5 +1,6 @@
import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:freezed_annotation/freezed_annotation.dart"; import "package:freezed_annotation/freezed_annotation.dart";
import "package:nexus/models/per_message_profiles.dart";
import "package:nexus/models/push_rules.dart"; import "package:nexus/models/push_rules.dart";
part "account_data.freezed.dart"; part "account_data.freezed.dart";
@ -27,6 +28,8 @@ class const AccountData({
final PushRules pushRules = const .new(), final PushRules pushRules = const .new(),
@JsonKey(name: AccountData.ignoredUserListKey) @JsonKey(name: AccountData.ignoredUserListKey)
final IgnoredUserList ignoredUserList = const .new(), final IgnoredUserList ignoredUserList = const .new(),
@JsonKey(name: AccountData.perMessageProfilesKey)
final PerMessageProfiles perMessageProfiles = const .new(),
}) with _$AccountData { }) with _$AccountData {
static const invitePermissionConfigKey = "m.invite_permission_config"; static const invitePermissionConfigKey = "m.invite_permission_config";
static const directKey = "m.direct"; static const directKey = "m.direct";
@ -35,6 +38,7 @@ class const AccountData({
static const legacyImagePackRoomsKey = "im.ponies.emote_rooms"; static const legacyImagePackRoomsKey = "im.ponies.emote_rooms";
static const pushRulesKey = "m.push_rules"; static const pushRulesKey = "m.push_rules";
static const ignoredUserListKey = "m.ignored_user_list"; static const ignoredUserListKey = "m.ignored_user_list";
static const perMessageProfilesKey = "fi.mau.msc4461.per_message_profiles.v3";
ImagePackRooms get enabledImagePacks => ImagePackRooms get enabledImagePacks =>
imagePackRooms ?? legacyImagePackRooms ?? const .new(); imagePackRooms ?? legacyImagePackRooms ?? const .new();

View file

@ -0,0 +1,48 @@
import "package:collection/collection.dart";
import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:freezed_annotation/freezed_annotation.dart";
part "per_message_profiles.freezed.dart";
part "per_message_profiles.g.dart";
@Freezed(toJson: false, fromJson: false)
@JsonSerializable(includeIfNull: false)
class const PerMessageProfiles({
final String? defaultProfileId,
final IList<StoredProfile> profiles = const .empty(),
}) with _$PerMessageProfiles {
StoredProfile? byId(String? id) =>
profiles.firstWhereOrNull((profile) => profile.id == id);
Map<String, Object?> toJson() => _$PerMessageProfilesToJson(this);
factory PerMessageProfiles.fromJson(Map<String, Object?> json) =>
_$PerMessageProfilesFromJson(json);
}
@Freezed(toJson: false, fromJson: false)
@JsonSerializable(includeIfNull: false)
class const StoredProfile({
required final String id,
@JsonKey(name: "displayname") final String? displayName,
final Uri? avatarUrl,
final IList<ProfileTrigger> triggers = const .empty(),
}) with _$StoredProfile {
Map<String, Object?> toJson() => _$StoredProfileToJson(this);
factory StoredProfile.fromJson(Map<String, Object?> json) =>
_$StoredProfileFromJson(json);
}
@Freezed(toJson: false, fromJson: false)
@JsonSerializable(includeIfNull: false)
class const ProfileTrigger({
final String prefix = "",
final String suffix = "",
final bool keepTrigger = false,
}) with _$ProfileTrigger {
Map<String, Object?> toJson() => _$ProfileTriggerToJson(this);
factory ProfileTrigger.fromJson(Map<String, Object?> json) =>
_$ProfileTriggerFromJson(json);
}

View file

@ -45,10 +45,12 @@ class const Room({
final IMap<String, IMap<String, int>> state = const .empty(), final IMap<String, IMap<String, int>> state = const .empty(),
final IMap<String, IList<ReadReceipt>> receipts = const .empty(), final IMap<String, IList<ReadReceipt>> receipts = const .empty(),
@JsonKey(fromJson: Room.accountDataJsonToIMap)
final IMap<String, Map<String, dynamic>> accountData = const .empty(),
final bool dismissNotifications = false, final bool dismissNotifications = false,
final bool hasMore = true, final bool hasMore = true,
// IMap<String, AccountData> accountData,
// IList<Notification> notifications, // IList<Notification> notifications,
}) with _$Room { }) with _$Room {
static IMap<int, int?> timelineTupleJsonToIMap(List<dynamic> json) => static IMap<int, int?> timelineTupleJsonToIMap(List<dynamic> json) =>
@ -61,6 +63,15 @@ class const Room({
), ),
); );
static IMap<String, Map<String, dynamic>> accountDataJsonToIMap(
Map<String, dynamic> json,
) => .fromEntries(
json.entries.map(
(entry) =>
.new(entry.key, Map<String, dynamic>.from(entry.value["content"])),
),
);
static IMap<int, Event> eventsJsonToIMap(List<dynamic> json) => static IMap<int, Event> eventsJsonToIMap(List<dynamic> json) =>
IMap.fromEntries( IMap.fromEntries(
json.map((eventJson) { json.map((eventJson) {

View file

@ -23,6 +23,7 @@ class const Settings({
final RoomOrder roomOrder = .unreadFirst, final RoomOrder roomOrder = .unreadFirst,
final NameColor nameColor = .powerLevel, final NameColor nameColor = .powerLevel,
final ShowAndSend typingIndicators = .showAndSend, final ShowAndSend typingIndicators = .showAndSend,
final bool personas = false,
/// When not sending, read receipts are still sent privately, so that the /// When not sending, read receipts are still sent privately, so that the
/// user's other devices know what has been read. /// user's other devices know what has been read.

View file

@ -3,6 +3,7 @@ import "dart:io";
import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:collection/collection.dart"; import "package:collection/collection.dart";
import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart";
import "package:nexus/widgets/composer/persona_button.dart";
import "package:nexus/controllers/bot_argument_suggestions.dart"; import "package:nexus/controllers/bot_argument_suggestions.dart";
import "package:nexus/controllers/bot_command_draft.dart"; import "package:nexus/controllers/bot_command_draft.dart";
import "package:nexus/controllers/bot_commands.dart"; import "package:nexus/controllers/bot_commands.dart";
@ -565,6 +566,7 @@ class const Composer(
), ),
) )
? [ ? [
PersonaButton(roomId),
IconButton( IconButton(
onPressed: hasReplacement onPressed: hasReplacement
? null ? null

View file

@ -0,0 +1,74 @@
import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:material_adaptive_sheets/material_adaptive_sheets.dart";
import "package:material_ui/material_ui.dart";
import "package:nexus/controllers/account_data.dart";
import "package:nexus/controllers/personas.dart";
import "package:nexus/controllers/settings.dart";
import "package:nexus/main.dart";
import "package:nexus/widgets/avatars/avatar_or_hash.dart";
/// Chooses the persona messages are sent as in [roomId], if personas are on.
class const PersonaButton(final String roomId, {super.key})
extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final enabled = ref.watch(
SettingsController.provider.select(
(settings) => settings.value?.personas ?? false,
),
);
final (:profiles, :current) = ref.watch(
PersonasController.provider(roomId),
);
if (!enabled || profiles.isEmpty) return const SizedBox.shrink();
Future<void> choose(String profileId) => ref
.read(AccountDataController.provider.notifier)
.setRoomProfile(roomId, profileId)
.onError(showError);
PopupMenuItem<void> item({
required String id,
required Widget leading,
required String title,
}) {
final selected = (current?.id ?? "") == id;
return PopupMenuItem(
onTap: () => choose(id),
child: ListTile(
selected: selected,
leading: leading,
title: Text(title),
trailing: selected ? Icon(Icons.check) : null,
),
);
}
return AdaptiveMenuButton<void>(
tooltip: switch (current) {
final current? => "Sending as ${current.displayName ?? current.id}",
null => "Choose persona",
},
icon: switch (current) {
final current? => AvatarOrHash(
current.avatarUrl,
current.displayName ?? current.id,
),
null => Icon(Icons.person),
},
itemBuilder: (_) => [
item(id: "", leading: Icon(Icons.person), title: "Yourself"),
...profiles.map(
(profile) => item(
id: profile.id,
leading: AvatarOrHash(
profile.avatarUrl,
profile.displayName ?? profile.id,
),
title: profile.displayName ?? profile.id,
),
),
],
);
}
}

View file

@ -0,0 +1,138 @@
import "package:flutter_hooks/flutter_hooks.dart";
import "package:hooks_riverpod/hooks_riverpod.dart";
import "package:material_adaptive_sheets/material_adaptive_sheets.dart";
import "package:material_ui/material_ui.dart";
import "package:nexus/controllers/account_data.dart";
import "package:nexus/helpers/hooks/saving.dart";
import "package:nexus/main.dart";
import "package:nexus/models/per_message_profiles.dart";
import "package:nexus/widgets/avatars/avatar_or_hash.dart";
import "package:nexus/widgets/avatars/editable_avatar.dart";
class const PersonaSheet({final StoredProfile? persona, super.key})
extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final saving = Saving.use();
final trigger = persona?.triggers.firstOrNull;
final nameController = useTextEditingController(text: persona?.displayName);
final prefixController = useTextEditingController(text: trigger?.prefix);
final suffixController = useTextEditingController(text: trigger?.suffix);
final avatar = useState(persona?.avatarUrl);
final name = useValueListenable(nameController).text.trim();
final accountData = ref.read(AccountDataController.provider.notifier);
PerMessageProfiles current() =>
ref.read(AccountDataController.provider).perMessageProfiles;
Future<void> update(PerMessageProfiles profiles) async {
await saving.run(() => accountData.setPerMessageProfiles(profiles));
if (context.mounted) Navigator.of(context).pop();
}
Future<void> save() {
final prefix = prefixController.text;
final suffix = suffixController.text;
final edited = StoredProfile(
id:
persona?.id ??
DateTime.now().microsecondsSinceEpoch.toRadixString(36),
displayName: name,
avatarUrl: avatar.value,
triggers: .new([
if (prefix.isNotEmpty || suffix.isNotEmpty)
(trigger ?? const .new()).copyWith(prefix: prefix, suffix: suffix),
...?persona?.triggers.skip(1),
]),
);
final profiles = current();
return update(
profiles.copyWith(
profiles: persona == null
? profiles.profiles.add(edited)
: profiles.profiles.replaceFirstWhere(
(profile) => profile.id == persona!.id,
(_) => edited,
),
),
).onError(showError);
}
Future<void> delete() {
final profiles = current();
return update(
profiles.copyWith(
profiles: profiles.profiles.removeWhere(
(profile) => profile.id == persona!.id,
),
defaultProfileId: profiles.defaultProfileId == persona!.id
? null
: profiles.defaultProfileId,
),
).onError(showError);
}
return SheetLayout(
title: Text(persona == null ? "Add Persona" : "Edit Persona"),
actions: [
if (persona != null)
TextButton(
onPressed: saving.active ? null : delete,
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: Text("Delete"),
),
TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")),
TextButton(
onPressed: name.isEmpty || saving.active ? null : save,
child: Text("Save"),
),
],
children: [
Center(
child: EditableAvatar(
dimension: 120,
hasAvatar: avatar.value != null,
onChanged: (url) async => avatar.value = url,
child: AvatarOrHash(
avatar.value,
name.isEmpty ? "Persona" : name,
dimension: 120,
),
),
),
TextField(
controller: nameController,
autofocus: persona == null,
textCapitalization: .words,
decoration: const .new(labelText: "Display name"),
),
Text(
"Optionally, messages that start with the prefix *and* end with the suffix are sent as this persona, without them. Leave one empty to only need the other. Both are case-sensitive.",
),
Row(
spacing: 8,
children: [
Expanded(
child: TextField(
controller: prefixController,
decoration: const .new(
labelText: "Prefix",
hintText: "e.g. k:",
),
),
),
Expanded(
child: TextField(
controller: suffixController,
decoration: const .new(labelText: "Suffix"),
),
),
],
),
],
);
}
}