diff --git a/lib/components/chat_settings_popup_menu.dart b/lib/components/chat_settings_popup_menu.dart index 1c3f8ee..0b37c2e 100644 --- a/lib/components/chat_settings_popup_menu.dart +++ b/lib/components/chat_settings_popup_menu.dart @@ -46,9 +46,9 @@ class _ChatSettingsPopupMenuState extends State { Widget build(BuildContext context) { notificationChangeSub ??= Matrix.of(context) .client - .onUserEvent + .onAccountData .stream - .where((u) => u.type == 'account_data' && u.eventType == 'm.push_rules') + .where((u) => u.type == 'm.push_rules') .listen( (u) => setState(() => null), ); diff --git a/lib/components/dialogs/presence_dialog.dart b/lib/components/dialogs/presence_dialog.dart index cb54773..f5bc0b5 100644 --- a/lib/components/dialogs/presence_dialog.dart +++ b/lib/components/dialogs/presence_dialog.dart @@ -27,7 +27,7 @@ class PresenceDialog extends StatelessWidget { contentPadding: EdgeInsets.zero, leading: Avatar(avatarUrl, displayname), title: Text(displayname), - subtitle: Text(presence.sender), + subtitle: Text(presence.senderId), ), content: Column( mainAxisSize: MainAxisSize.min, @@ -38,7 +38,7 @@ class PresenceDialog extends StatelessWidget { Text( presence.presence.toString().split('.').last, style: TextStyle( - color: presence.currentlyActive == true + color: presence.presence.currentlyActive == true ? Colors.green : Theme.of(context).primaryColor, ), @@ -46,12 +46,12 @@ class PresenceDialog extends StatelessWidget { ], ), actions: [ - if (presence.sender != Matrix.of(context).client.userID) + if (presence.senderId != Matrix.of(context).client.userID) FlatButton( child: Text(L10n.of(context).sendAMessage), onPressed: () async { final roomId = await User( - presence.sender, + presence.senderId, room: Room(id: '', client: Matrix.of(context).client), ).startDirectChat(); await Navigator.of(context).pushAndRemoveUntil( diff --git a/lib/components/list_items/message.dart b/lib/components/list_items/message.dart index d469c4d..6c8e3c8 100644 --- a/lib/components/list_items/message.dart +++ b/lib/components/list_items/message.dart @@ -1,5 +1,6 @@ import 'package:bubble/bubble.dart'; import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/encryption.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; import 'package:fluffychat/components/message_content.dart'; import 'package:fluffychat/components/reply_content.dart'; @@ -98,11 +99,11 @@ class Message extends StatelessWidget { ['m.in_reply_to']['event_id'], content: {'msgtype': 'm.text', 'body': '...'}, senderId: event.senderId, - typeKey: 'm.room.message', + type: 'm.room.message', room: event.room, roomId: event.roomId, status: 1, - time: DateTime.now(), + originServerTs: DateTime.now(), ); return Container( margin: EdgeInsets.symmetric(vertical: 4.0), @@ -218,7 +219,7 @@ class _MetaRow extends StatelessWidget { ), if (showDisplayname) SizedBox(width: 4), Text( - event.time.localizedTime(context), + event.originServerTs.localizedTime(context), style: TextStyle( color: color, fontSize: 11, diff --git a/lib/components/list_items/presence_list_item.dart b/lib/components/list_items/presence_list_item.dart index b7c9a23..e55452d 100644 --- a/lib/components/list_items/presence_list_item.dart +++ b/lib/components/list_items/presence_list_item.dart @@ -13,9 +13,9 @@ class PresenceListItem extends StatelessWidget { static final Map _presences = {}; Future _requestProfile(BuildContext context) async { - _presences[presence.sender] ??= - await Matrix.of(context).client.getProfileFromUserId(presence.sender); - return _presences[presence.sender]; + _presences[presence.senderId] ??= + await Matrix.of(context).client.getProfileFromUserId(presence.senderId); + return _presences[presence.senderId]; } @override @@ -25,7 +25,7 @@ class PresenceListItem extends StatelessWidget { builder: (context, snapshot) { if (!snapshot.hasData) return Container(); Uri avatarUrl; - var displayname = presence.sender.localpart; + var displayname = presence.senderId.localpart; if (snapshot.hasData) { avatarUrl = snapshot.data.avatarUrl; displayname = snapshot.data.displayname; diff --git a/lib/components/list_items/public_room_list_item.dart b/lib/components/list_items/public_room_list_item.dart index 71ff959..224c0da 100644 --- a/lib/components/list_items/public_room_list_item.dart +++ b/lib/components/list_items/public_room_list_item.dart @@ -1,4 +1,5 @@ import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/matrix_api.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; import 'package:flutter/material.dart'; @@ -6,15 +7,16 @@ import '../../l10n/l10n.dart'; import '../../utils/app_route.dart'; import '../../views/chat.dart'; import '../avatar.dart'; +import '../matrix.dart'; class PublicRoomListItem extends StatelessWidget { - final PublicRoomEntry publicRoomEntry; + final PublicRoom publicRoomEntry; const PublicRoomListItem(this.publicRoomEntry, {Key key}) : super(key: key); void joinAction(BuildContext context) async { - final success = await SimpleDialogs(context) - .tryRequestWithLoadingDialog(publicRoomEntry.join()); + final success = await SimpleDialogs(context).tryRequestWithLoadingDialog( + Matrix.of(context).client.api.joinRoom(publicRoomEntry.roomId)); if (success != false) { await Navigator.of(context).push( AppRoute.defaultRoute( diff --git a/lib/components/matrix.dart b/lib/components/matrix.dart index 6151c2b..41d4cba 100644 --- a/lib/components/matrix.dart +++ b/lib/components/matrix.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/encryption.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; import 'package:fluffychat/utils/firebase_controller.dart'; import 'package:flutter/foundation.dart'; @@ -84,7 +85,7 @@ class MatrixState extends State { } } - Map getAuthByPassword(String password, String session) => { + Map getAuthByPassword(String password, [String session]) => { 'type': 'm.login.password', 'identifier': { 'type': 'm.id.user', @@ -92,7 +93,7 @@ class MatrixState extends State { }, 'user': client.userID, 'password': password, - 'session': session, + if (session != null) 'session': session, }; StreamSubscription onRoomKeyRequestSub; @@ -102,7 +103,7 @@ class MatrixState extends State { final event = Event.fromJson( eventUpdate.content, client.getRoomById(eventUpdate.roomID)); if (DateTime.now().millisecondsSinceEpoch - - event.time.millisecondsSinceEpoch > + event.originServerTs.millisecondsSinceEpoch > 1000 * 60 * 5) { return; } @@ -227,11 +228,12 @@ class _InheritedMatrix extends InheritedWidget { @override bool updateShouldNotify(_InheritedMatrix old) { - var update = old.data.client.accessToken != data.client.accessToken || - old.data.client.userID != data.client.userID || - old.data.client.deviceID != data.client.deviceID || - old.data.client.deviceName != data.client.deviceName || - old.data.client.homeserver != data.client.homeserver; + var update = + old.data.client.api.accessToken != data.client.api.accessToken || + old.data.client.userID != data.client.userID || + old.data.client.deviceID != data.client.deviceID || + old.data.client.deviceName != data.client.deviceName || + old.data.client.api.homeserver != data.client.api.homeserver; return update; } } diff --git a/lib/components/message_content.dart b/lib/components/message_content.dart index d2f4897..cff9d08 100644 --- a/lib/components/message_content.dart +++ b/lib/components/message_content.dart @@ -90,8 +90,8 @@ class MessageContent extends StatelessWidget { break; default: return Text( - L10n.of(context).userSentUnknownEvent( - event.sender.calcDisplayname(), event.typeKey), + L10n.of(context) + .userSentUnknownEvent(event.sender.calcDisplayname(), event.type), style: TextStyle( color: textColor, decoration: event.redacted ? TextDecoration.lineThrough : null, diff --git a/lib/utils/client_presence_extension.dart b/lib/utils/client_presence_extension.dart index 41674ef..02bdb9b 100644 --- a/lib/utils/client_presence_extension.dart +++ b/lib/utils/client_presence_extension.dart @@ -3,7 +3,7 @@ import 'package:famedlysdk/famedlysdk.dart'; extension ClientPresenceExtension on Client { List get statusList { final statusList = presences.values.toList().reversed.toList(); - statusList.removeWhere((p) => p.statusMsg?.isEmpty ?? true); + statusList.removeWhere((p) => p.presence.statusMsg?.isEmpty ?? true); statusList.reversed.toList(); return statusList; } diff --git a/lib/utils/firebase_controller.dart b/lib/utils/firebase_controller.dart index 07020e6..5efe800 100644 --- a/lib/utils/firebase_controller.dart +++ b/lib/utils/firebase_controller.dart @@ -42,7 +42,7 @@ abstract class FirebaseController { ); return; } - final pushers = await client.getPushers(); + final pushers = await client.api.requestPushers(); final currentPushers = pushers.where((pusher) => pusher.pushkey == token); if (currentPushers.length == 1 && currentPushers.first.kind == 'http' && @@ -50,35 +50,35 @@ abstract class FirebaseController { currentPushers.first.appDisplayName == clientName && currentPushers.first.deviceDisplayName == client.deviceName && currentPushers.first.lang == 'en' && - currentPushers.first.data.url == GATEWAY_URL && + currentPushers.first.data.url.toString() == GATEWAY_URL && currentPushers.first.data.format == PUSHER_FORMAT) { debugPrint('[Push] Pusher already set'); } else { if (currentPushers.isNotEmpty) { for (final currentPusher in currentPushers) { - await client.setPushers( - token, - 'null', - currentPusher.appId, - currentPusher.appDisplayName, - currentPusher.deviceDisplayName, - currentPusher.lang, - currentPusher.data.url, + currentPusher.pushkey = token; + currentPusher.kind = 'null'; + await client.api.setPusher( + currentPusher, append: true, ); debugPrint('[Push] Remove legacy pusher for this device'); } } - await client.setPushers( - token, - 'http', - APP_ID, - clientName, - client.deviceName, - 'en', - GATEWAY_URL, + await client.api.setPusher( + Pusher( + token, + APP_ID, + clientName, + client.deviceName, + 'en', + PusherData( + url: Uri.parse(GATEWAY_URL), + format: PUSHER_FORMAT, + ), + kind: 'http', + ), append: false, - format: PUSHER_FORMAT, ); } @@ -224,7 +224,7 @@ abstract class FirebaseController { messages: [ Message( body, - event.time, + event.originServerTs, person, ) ], diff --git a/lib/utils/presence_extension.dart b/lib/utils/presence_extension.dart index 5087807..b367298 100644 --- a/lib/utils/presence_extension.dart +++ b/lib/utils/presence_extension.dart @@ -5,9 +5,11 @@ import 'date_time_extension.dart'; extension PresenceExtension on Presence { String getLocalizedStatusMessage(BuildContext context) { - if (statusMsg?.isNotEmpty ?? false) { - return statusMsg; + if (presence.statusMsg?.isNotEmpty ?? false) { + return presence.statusMsg; } - return L10n.of(context).lastActiveAgo(time.localizedTimeShort(context)); + return L10n.of(context).lastActiveAgo( + DateTime.fromMillisecondsSinceEpoch(presence.lastActiveAgo) + .localizedTimeShort(context)); } } diff --git a/lib/utils/room_status_extension.dart b/lib/utils/room_status_extension.dart index 4b53f94..6b5d043 100644 --- a/lib/utils/room_status_extension.dart +++ b/lib/utils/room_status_extension.dart @@ -10,11 +10,13 @@ extension RoomStatusExtension on Room { String getLocalizedStatus(BuildContext context) { if (isDirectChat) { if (directChatPresence != null) { - if (directChatPresence.currentlyActive == true) { + if (directChatPresence.presence.currentlyActive == true) { return L10n.of(context).currentlyActive; } - return L10n.of(context) - .lastActiveAgo(directChatPresence.time.localizedTimeShort(context)); + return L10n.of(context).lastActiveAgo( + DateTime.fromMillisecondsSinceEpoch( + directChatPresence.presence.lastActiveAgo) + .localizedTimeShort(context)); } return L10n.of(context).lastSeenLongTimeAgo; } diff --git a/lib/utils/url_launcher.dart b/lib/utils/url_launcher.dart index 224d767..b7b4928 100644 --- a/lib/utils/url_launcher.dart +++ b/lib/utils/url_launcher.dart @@ -23,7 +23,7 @@ class UrlLauncher { final identifier = url.replaceAll('https://matrix.to/#/', ''); if (identifier.substring(0, 1) == '#') { final response = await SimpleDialogs(context).tryRequestWithLoadingDialog( - matrix.client.joinRoomById( + matrix.client.api.joinRoom( Uri.encodeComponent(identifier), ), ); diff --git a/lib/views/app_info.dart b/lib/views/app_info.dart index 579c9ef..b0d6031 100644 --- a/lib/views/app_info.dart +++ b/lib/views/app_info.dart @@ -33,7 +33,7 @@ class AppInfo extends StatelessWidget { ), ListTile( title: Text('Homeserver:'), - subtitle: Text(client.homeserver), + subtitle: Text(client.api.homeserver.toString()), ), ListTile( title: Text('Device name:'), diff --git a/lib/views/auth_web_view.dart b/lib/views/auth_web_view.dart index 56132c8..ad51573 100644 --- a/lib/views/auth_web_view.dart +++ b/lib/views/auth_web_view.dart @@ -14,9 +14,8 @@ class AuthWebView extends StatelessWidget { @override Widget build(BuildContext context) { - final url = - '/_matrix/client/r0/auth/$authType/fallback/web?session=$session' + - Matrix.of(context).client.homeserver; + final url = Matrix.of(context).client.api.homeserver.toString() + + '/_matrix/client/r0/auth/$authType/fallback/web?session=$session'; if (kIsWeb) launch(url); return Scaffold( appBar: AppBar( diff --git a/lib/views/chat.dart b/lib/views/chat.dart index 7f842eb..fa4d097 100644 --- a/lib/views/chat.dart +++ b/lib/views/chat.dart @@ -372,7 +372,7 @@ class _ChatState extends State<_Chat> { .client .onPresence .stream - .where((p) => p.sender == room.directChatMatrixID), + .where((p) => p.senderId == room.directChatMatrixID), builder: (context, snapshot) { return ListTile( leading: Avatar(room.avatar, room.displayname), @@ -557,7 +557,8 @@ class _ChatState extends State<_Chat> { ); } selectedEvents.sort( - (a, b) => a.time.compareTo(b.time), + (a, b) => a.originServerTs + .compareTo(b.originServerTs), ); } }, diff --git a/lib/views/chat_details.dart b/lib/views/chat_details.dart index b02a995..71e6d50 100644 --- a/lib/views/chat_details.dart +++ b/lib/views/chat_details.dart @@ -1,4 +1,5 @@ import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/matrix_api.dart'; import 'package:fluffychat/components/adaptive_page_layout.dart'; import 'package:fluffychat/components/chat_settings_popup_menu.dart'; import 'package:fluffychat/components/content_banner.dart'; @@ -61,28 +62,22 @@ class _ChatDetailsState extends State { var newAliases = List.from(aliases); newAliases.add(canonicalAlias); final response = await SimpleDialogs(context).tryRequestWithLoadingDialog( - widget.room.client.jsonRequest( - type: HTTPType.GET, - action: '/client/r0/directory/room/$canonicalAlias', - ), + widget.room.client.api.requestRoomAliasInformations(canonicalAlias), ); if (response == false) { final success = await SimpleDialogs(context).tryRequestWithLoadingDialog( - widget.room.client.jsonRequest( - type: HTTPType.PUT, - action: '/client/r0/directory/room/$canonicalAlias', - data: {'room_id': widget.room.id}), + widget.room.client.api + .createRoomAlias(canonicalAlias, widget.room.id), ); if (success == false) return; } } await SimpleDialogs(context).tryRequestWithLoadingDialog( - widget.room.client.jsonRequest( - type: HTTPType.PUT, - action: - '/client/r0/rooms/${widget.room.id}/state/m.room.canonical_alias', - data: {'alias': '#$s:$domain'}), + widget.room.client.api + .sendState(widget.room.id, 'm.room.canonical_alias', { + 'alias': '#$s:$domain', + }), ); } diff --git a/lib/views/chat_list.dart b/lib/views/chat_list.dart index 4914ae8..b8617ad 100644 --- a/lib/views/chat_list.dart +++ b/lib/views/chat_list.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/matrix_api.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; import 'package:fluffychat/components/list_items/presence_list_item.dart'; import 'package:fluffychat/components/list_items/public_room_list_item.dart'; @@ -93,7 +94,7 @@ class _ChatListState extends State { setState(() => loadingPublicRooms = true); final newPublicRoomsResponse = await SimpleDialogs(context).tryRequestWithErrorToast( - Matrix.of(context).client.requestPublicRooms( + Matrix.of(context).client.api.searchPublicRooms( limit: 30, includeAllNetworks: true, genericSearchTerm: searchController.text, @@ -107,13 +108,12 @@ class _ChatListState extends State { if (searchController.text.isNotEmpty && searchController.text.isValidMatrixId && searchController.text.sigil == '#') { - publicRoomsResponse.publicRooms.add( - PublicRoomEntry( - aliases: [searchController.text], - name: searchController.text, - roomId: searchController.text, - client: Matrix.of(context).client, - ), + publicRoomsResponse.chunk.add( + PublicRoom.fromJson({ + 'aliases': [searchController.text], + 'name': searchController.text, + 'room_id': searchController.text, + }), ); } } @@ -199,15 +199,9 @@ class _ChatListState extends State { ); if (status?.isEmpty ?? true) return; await SimpleDialogs(context).tryRequestWithLoadingDialog( - Matrix.of(context).client.jsonRequest( - type: HTTPType.PUT, - action: - '/client/r0/presence/${Matrix.of(context).client.userID}/status', - data: { - 'presence': 'online', - 'status_msg': status, - }, - ), + Matrix.of(context).client.api.sendPresence( + Matrix.of(context).client.userID, PresenceType.online, + statusMsg: status), ); } @@ -412,8 +406,7 @@ class _ChatListState extends State { ); } final publicRoomsCount = - (publicRoomsResponse?.publicRooms?.length ?? - 0); + (publicRoomsResponse?.chunk?.length ?? 0); final totalCount = rooms.length + publicRoomsCount; return ListView.separated( @@ -469,7 +462,7 @@ class _ChatListState extends State { rooms[i].id, ) : PublicRoomListItem(publicRoomsResponse - .publicRooms[i - rooms.length]); + .chunk[i - rooms.length]); }); } else { return Center( diff --git a/lib/views/invitation_selection.dart b/lib/views/invitation_selection.dart index ab893bf..37d4437 100644 --- a/lib/views/invitation_selection.dart +++ b/lib/views/invitation_selection.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/matrix_api.dart'; import 'package:fluffychat/components/adaptive_page_layout.dart'; import 'package:fluffychat/components/avatar.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; @@ -23,7 +24,7 @@ class _InvitationSelectionState extends State { TextEditingController controller = TextEditingController(); String currentSearchTerm; bool loading = false; - List> foundProfiles = []; + List foundProfiles = []; Timer coolDown; Future> getContacts(BuildContext context) async { @@ -84,32 +85,23 @@ class _InvitationSelectionState extends State { setState(() => loading = true); final matrix = Matrix.of(context); final response = await SimpleDialogs(context).tryRequestWithErrorToast( - matrix.client.jsonRequest( - type: HTTPType.POST, - action: '/client/r0/user_directory/search', - data: { - 'search_term': text, - 'limit': 10, - }), + matrix.client.api.searchUser(text, limit: 10), ); setState(() => loading = false); - if (response == false || - !(response is Map) || - (response['results'] == null)) return; + if (response == false || (response?.results == null)) return; setState(() { - foundProfiles = List>.from(response['results']); + foundProfiles = List.from(response.results); if ('@$text'.isValidMatrixId && - foundProfiles - .indexWhere((profile) => '@$text' == profile['user_id']) == + foundProfiles.indexWhere((profile) => '@$text' == profile.userId) == -1) { setState(() => foundProfiles = [ - {'user_id': '@$text'} + Profile.fromJson({'user_id': '@$text'}), ]); } foundProfiles.removeWhere((profile) => widget.room .getParticipants() - .indexWhere((u) => u.id == profile['user_id']) != + .indexWhere((u) => u.id == profile.userId) != -1); }); } @@ -160,19 +152,15 @@ class _InvitationSelectionState extends State { itemCount: foundProfiles.length, itemBuilder: (BuildContext context, int i) => ListTile( leading: Avatar( - foundProfiles[i]['avatar_url'] == null - ? null - : Uri.parse(foundProfiles[i]['avatar_url']), - foundProfiles[i]['display_name'] ?? - foundProfiles[i]['user_id'], + foundProfiles[i].avatarUrl, + foundProfiles[i].displayname ?? foundProfiles[i].userId, ), title: Text( - foundProfiles[i]['display_name'] ?? - (foundProfiles[i]['user_id'] as String).localpart, + foundProfiles[i].displayname ?? + foundProfiles[i].userId.localpart, ), - subtitle: Text(foundProfiles[i]['user_id']), - onTap: () => - inviteAction(context, foundProfiles[i]['user_id']), + subtitle: Text(foundProfiles[i].userId), + onTap: () => inviteAction(context, foundProfiles[i].userId), ), ) : FutureBuilder>( diff --git a/lib/views/login.dart b/lib/views/login.dart index 4a3f406..1d81bb7 100644 --- a/lib/views/login.dart +++ b/lib/views/login.dart @@ -91,7 +91,7 @@ class _LoginState extends State { .getWellKnownInformationsByUserId(userId); final newDomain = wellKnownInformations.mHomeserver?.baseUrl; if ((newDomain?.isNotEmpty ?? false) && - newDomain != Matrix.of(context).client.homeserver) { + newDomain != Matrix.of(context).client.api.homeserver.toString()) { await SimpleDialogs(context).tryRequestWithErrorToast( Matrix.of(context).client.checkServer(newDomain)); setState(() => usernameError = null); @@ -110,7 +110,9 @@ class _LoginState extends State { title: Text( L10n.of(context).logInTo(Matrix.of(context) .client + .api .homeserver + .toString() .replaceFirst('https://', '')), ), ), diff --git a/lib/views/new_group.dart b/lib/views/new_group.dart index b367e39..2edb904 100644 --- a/lib/views/new_group.dart +++ b/lib/views/new_group.dart @@ -1,3 +1,4 @@ +import 'package:famedlysdk/matrix_api.dart' as api; import 'package:fluffychat/components/adaptive_page_layout.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; import 'package:fluffychat/components/matrix.dart'; @@ -32,20 +33,17 @@ class _NewGroupState extends State<_NewGroup> { void submitAction(BuildContext context) async { final matrix = Matrix.of(context); - var params = {}; - if (publicGroup) { - params['preset'] = 'public_chat'; - params['visibility'] = 'public'; - if (controller.text.isNotEmpty) { - params['room_alias_name'] = controller.text; - } - } else { - params['preset'] = 'private_chat'; - } - if (controller.text.isNotEmpty) params['name'] = controller.text; final String roomID = await SimpleDialogs(context).tryRequestWithLoadingDialog( - matrix.client.createRoom(params: params), + matrix.client.api.createRoom( + preset: publicGroup + ? api.CreateRoomPreset.public_chat + : api.CreateRoomPreset.private_chat, + visibility: publicGroup ? api.Visibility.public : null, + roomAliasName: + publicGroup && controller.text.isNotEmpty ? controller.text : null, + name: controller.text.isNotEmpty ? controller.text : null, + ), ); Navigator.of(context).pop(); if (roomID != null) { diff --git a/lib/views/new_private_chat.dart b/lib/views/new_private_chat.dart index 46d5a08..ea07d92 100644 --- a/lib/views/new_private_chat.dart +++ b/lib/views/new_private_chat.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:famedlysdk/famedlysdk.dart'; +import 'package:famedlysdk/matrix_api.dart'; import 'package:fluffychat/components/adaptive_page_layout.dart'; import 'package:fluffychat/components/avatar.dart'; import 'package:fluffychat/components/dialogs/simple_dialogs.dart'; @@ -34,14 +35,14 @@ class _NewPrivateChatState extends State<_NewPrivateChat> { final _formKey = GlobalKey(); bool loading = false; String currentSearchTerm; - List> foundProfiles = []; + List foundProfiles = []; Timer coolDown; - Map get foundProfile => foundProfiles.firstWhere( - (user) => user['user_id'] == '@$currentSearchTerm', - orElse: () => null); + Profile get foundProfile => + foundProfiles.firstWhere((user) => user.userId == '@$currentSearchTerm', + orElse: () => null); bool get correctMxId => foundProfiles - .indexWhere((user) => user['user_id'] == '@$currentSearchTerm') != + .indexWhere((user) => user.userId == '@$currentSearchTerm') != -1; void submitAction(BuildContext context) async { @@ -89,20 +90,12 @@ class _NewPrivateChatState extends State<_NewPrivateChat> { setState(() => loading = true); final matrix = Matrix.of(context); final response = await SimpleDialogs(context).tryRequestWithErrorToast( - matrix.client.jsonRequest( - type: HTTPType.POST, - action: '/client/r0/user_directory/search', - data: { - 'search_term': text, - 'limit': 10, - }), + matrix.client.api.searchUser(text, limit: 10), ); setState(() => loading = false); - if (response == false || - !(response is Map) || - (response['results']?.isEmpty ?? true)) return; + if (response == false || (response?.results?.isEmpty ?? true)) return; setState(() { - foundProfiles = List>.from(response['results']); + foundProfiles = List.from(response.results); }); } @@ -158,11 +151,8 @@ class _NewPrivateChatState extends State<_NewPrivateChat> { ? Padding( padding: const EdgeInsets.all(8.0), child: Avatar( - foundProfile['avatar_url'] == null - ? null - : Uri.parse(foundProfile['avatar_url']), - foundProfile['display_name'] ?? - foundProfile['user_id'], + foundProfile.avatarUrl, + foundProfile.displayname ?? foundProfile.userId, size: 12, ), ) @@ -184,24 +174,21 @@ class _NewPrivateChatState extends State<_NewPrivateChat> { onTap: () { setState(() { controller.text = currentSearchTerm = - foundProfile['user_id'].substring(1); + foundProfile.userId.substring(1); }); }, leading: Avatar( - foundProfile['avatar_url'] == null - ? null - : Uri.parse(foundProfile['avatar_url']), - foundProfile['display_name'] ?? foundProfile['user_id'], + foundProfile.avatarUrl, + foundProfile.displayname ?? foundProfile.userId, //size: 24, ), title: Text( - foundProfile['display_name'] ?? - (foundProfile['user_id'] as String).localpart, + foundProfile.displayname ?? foundProfile.userId.localpart, style: TextStyle(), maxLines: 1, ), subtitle: Text( - foundProfile['user_id'], + foundProfile.userId, maxLines: 1, style: TextStyle( fontSize: 12, diff --git a/lib/views/settings_devices.dart b/lib/views/settings_devices.dart index da38173..ffcaa73 100644 --- a/lib/views/settings_devices.dart +++ b/lib/views/settings_devices.dart @@ -25,36 +25,32 @@ class DevicesSettings extends StatefulWidget { } class DevicesSettingsState extends State { - List devices; + List devices; Future _loadUserDevices(BuildContext context) async { if (devices != null) return true; - devices = await Matrix.of(context).client.requestUserDevices(); + devices = await Matrix.of(context).client.api.requestDevices(); return true; } void reload() => setState(() => devices = null); - void _removeDevicesAction( - BuildContext context, List devices) async { + void _removeDevicesAction(BuildContext context, List devices) async { if (await SimpleDialogs(context).askConfirmation() == false) return; var matrix = Matrix.of(context); var deviceIds = []; for (var userDevice in devices) { deviceIds.add(userDevice.deviceId); } - final success = await SimpleDialogs(context) - .tryRequestWithLoadingDialog(matrix.client.deleteDevices(deviceIds), - onAdditionalAuth: (MatrixException exception) async { - final password = await SimpleDialogs(context).enterText( - titleText: L10n.of(context).pleaseEnterYourPassword, - labelText: L10n.of(context).pleaseEnterYourPassword, - hintText: '******', - password: true); - if (password == null) return; - await matrix.client.deleteDevices(deviceIds, - auth: matrix.getAuthByPassword(password, exception.session)); - return; - }); + final password = await SimpleDialogs(context).enterText( + titleText: L10n.of(context).pleaseEnterYourPassword, + labelText: L10n.of(context).pleaseEnterYourPassword, + hintText: '******', + password: true); + if (password == null) return; + + final success = await SimpleDialogs(context).tryRequestWithLoadingDialog( + matrix.client.api.deleteDevices(deviceIds, + auth: matrix.getAuthByPassword(password))); if (success != false) { reload(); } @@ -81,9 +77,9 @@ class DevicesSettingsState extends State { if (!snapshot.hasData || this.devices == null) { return Center(child: CircularProgressIndicator()); } - Function isOwnDevice = (UserDevice userDevice) => + Function isOwnDevice = (Device userDevice) => userDevice.deviceId == Matrix.of(context).client.deviceID; - final devices = List.from(this.devices); + final devices = List.from(this.devices); var thisDevice = devices.firstWhere(isOwnDevice, orElse: () => null); devices.removeWhere(isOwnDevice); devices.sort((a, b) => b.lastSeenTs.compareTo(a.lastSeenTs)); @@ -134,7 +130,7 @@ class DevicesSettingsState extends State { } class UserDeviceListItem extends StatelessWidget { - final UserDevice userDevice; + final Device userDevice; final Function remove; const UserDeviceListItem(this.userDevice, {this.remove, Key key}) diff --git a/lib/views/settings_emotes.dart b/lib/views/settings_emotes.dart index ff590e5..834f716 100644 --- a/lib/views/settings_emotes.dart +++ b/lib/views/settings_emotes.dart @@ -70,21 +70,16 @@ class _EmotesSettingsState extends State { content['short'][emote.emote] = emote.mxc; } debugPrint(content.toString()); - var path = ''; if (widget.room != null) { - path = '/client/r0/rooms/${widget.room.id}/state/im.ponies.room_emotes/'; + await SimpleDialogs(context).tryRequestWithLoadingDialog( + client.api.sendState(widget.room.id, 'im.ponies.room_emotes', content), + ); } else { - path = - '/client/r0/user/${client.userID}/account_data/im.ponies.user_emotes'; + await SimpleDialogs(context).tryRequestWithLoadingDialog( + client.api + .setAccountData(client.userID, 'im.ponies.user_emotes', content), + ); } - debugPrint(path); - await SimpleDialogs(context).tryRequestWithLoadingDialog( - client.jsonRequest( - type: HTTPType.PUT, - action: path, - data: content, - ), - ); } bool get readonly => widget.room == null @@ -378,11 +373,14 @@ class _EmoteImagePickerState extends State<_EmoteImagePicker> { maxWidth: 128, maxHeight: 128); if (file == null) return; + final matrixFile = + MatrixFile(bytes: await file.readAsBytes(), path: file.path); final uploadResp = await SimpleDialogs(context).tryRequestWithLoadingDialog( - Matrix.of(context).client.upload( - MatrixFile(bytes: await file.readAsBytes(), path: file.path), - ), + Matrix.of(context) + .client + .api + .upload(matrixFile.bytes, matrixFile.path), ); setState(() { widget.controller.text = uploadResp; diff --git a/lib/views/sign_up.dart b/lib/views/sign_up.dart index 54a3b4b..9be825e 100644 --- a/lib/views/sign_up.dart +++ b/lib/views/sign_up.dart @@ -49,7 +49,7 @@ class _SignUpState extends State { usernameController.text.toLowerCase().replaceAll(' ', '-'); try { - await matrix.client.usernameAvailable(preferredUsername); + await matrix.client.api.usernameAvailable(preferredUsername); } on MatrixException catch (exception) { setState(() => usernameError = exception.errorMessage); return setState(() => loading = false); @@ -73,7 +73,12 @@ class _SignUpState extends State { elevation: 0, leading: loading ? Container() : null, title: Text( - Matrix.of(context).client.homeserver.replaceFirst('https://', ''), + Matrix.of(context) + .client + .api + .homeserver + .toString() + .replaceFirst('https://', ''), ), ), body: ListView( diff --git a/pubspec.lock b/pubspec.lock index bb9d54a..550ac2b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -133,8 +133,8 @@ packages: dependency: "direct main" description: path: "." - ref: "359e03496ad72f125ae275788621ac4f42d99d01" - resolved-ref: "359e03496ad72f125ae275788621ac4f42d99d01" + ref: "857775cf37804440717ce797e0ed63fd39066904" + resolved-ref: "857775cf37804440717ce797e0ed63fd39066904" url: "https://gitlab.com/famedly/famedlysdk.git" source: git version: "0.0.1" diff --git a/pubspec.yaml b/pubspec.yaml index 79f56c8..8b4e637 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -27,7 +27,7 @@ dependencies: famedlysdk: git: url: https://gitlab.com/famedly/famedlysdk.git - ref: 359e03496ad72f125ae275788621ac4f42d99d01 + ref: 857775cf37804440717ce797e0ed63fd39066904 localstorage: ^3.0.1+4 bubble: ^1.1.9+1