Skip to content

Commit

Permalink
Merge pull request #206 from syphon-org/0.1.5-block-user
Browse files Browse the repository at this point in the history
[0.1.5] block users + bugs
  • Loading branch information
ereio authored Dec 14, 2020
2 parents 462b6dd + 3209407 commit 1aa2771
Show file tree
Hide file tree
Showing 22 changed files with 345 additions and 131 deletions.
12 changes: 8 additions & 4 deletions lib/global/cache/serializer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class CacheSerializer implements StateSerializer<AppState> {
state.cryptoStore,
state.mediaStore,
state.settingsStore,
state.userStore,
];

// Queue up a cache saving will wait
Expand All @@ -66,8 +67,8 @@ class CacheSerializer implements StateSerializer<AppState> {
// Stopwatch stopwatchSerialize = new Stopwatch()..start();
try {
// HACK: unable to pass certain stores directly to an isolate
final sensitiveStorage = [AuthStore, SyncStore, CryptoStore];
if (!sensitiveStorage.contains(store.runtimeType)) {
final sensitiveStorage = [MediaStore];
if (sensitiveStorage.contains(store.runtimeType)) {
jsonEncoded = await compute(jsonEncode, store);
} else {
jsonEncoded = json.encode(store);
Expand Down Expand Up @@ -131,6 +132,7 @@ class CacheSerializer implements StateSerializer<AppState> {
AppState decode(Uint8List data) {
AuthStore authStore = AuthStore();
SyncStore syncStore = SyncStore();
UserStore userStore = UserStore();
CryptoStore cryptoStore = CryptoStore();
MediaStore mediaStore = MediaStore();
SettingsStore settingsStore = SettingsStore();
Expand Down Expand Up @@ -162,8 +164,10 @@ class CacheSerializer implements StateSerializer<AppState> {
case 'SettingsStore':
settingsStore = SettingsStore.fromJson(store);
break;
case 'RoomStore':
case 'UserStore':
userStore = UserStore.fromJson(store);
break;
case 'RoomStore':
// --- cold storage only ---
default:
break;
Expand All @@ -183,7 +187,7 @@ class CacheSerializer implements StateSerializer<AppState> {
roomStore: RoomStore().copyWith(
rooms: preloaded['rooms'] ?? {},
),
userStore: UserStore().copyWith(
userStore: userStore.copyWith(
users: preloaded['users'] ?? {},
),
eventStore: EventStore().copyWith(
Expand Down
2 changes: 2 additions & 0 deletions lib/global/cache/storage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import 'package:syphon/store/media/state.dart';
import 'package:syphon/store/rooms/state.dart';
import 'package:syphon/store/settings/state.dart';
import 'package:syphon/store/sync/state.dart';
import 'package:syphon/store/user/state.dart';

final List<Object> stores = [
AuthStore(),
SyncStore(),
UserStore(),
MediaStore(),
CryptoStore(),
SettingsStore(),
Expand Down
2 changes: 1 addition & 1 deletion lib/global/libs/matrix/errors.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class MatrixErrors {
static const String room_unknown = 'M_UNKNOWN';
static const String not_authorized = 'M_UNAUTHORIZED';
static const String room_not_found = 'M_NOT_FOUND';
static const String not_found = "M_NOT_FOUND";
static const String user_in_use = 'M_USER_IN_USE';
static const String unknown_token = 'M_UNKNOWN_TOKEN';
static const String email_in_use = 'M_THREEPID_IN_USE';
Expand Down
6 changes: 4 additions & 2 deletions lib/global/libs/matrix/events.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:syphon/global/algos.dart';

// Project imports:
import 'package:syphon/global/libs/matrix/encryption.dart';
import 'package:syphon/global/print.dart';
import 'package:syphon/store/events/model.dart';

abstract class Events {
Expand Down Expand Up @@ -50,16 +51,17 @@ abstract class Events {
String from,
String to,
int limit = 10, // default limit by matrix
bool desc = true, // Direction of events
bool desc = true, // direction of events
}) async {
String url =
'$protocol$homeserver/_matrix/client/r0/rooms/$roomId/messages';

// Params
url += '?limit=$limit';
url += from != null ? '&from=${from}' : '';
url += to != null ? '&to=${to}' : '';
url += desc ? '&dir=b' : '&dir=f';
// TODO: remove after implementing reactions
url += '&filter={"not_types":["${EventTypes.member}", "m.reaction"]}';

Map<String, String> headers = {
'Authorization': 'Bearer $accessToken',
Expand Down
2 changes: 1 addition & 1 deletion lib/global/libs/matrix/index.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ abstract class MatrixApi {
static final updateAvatarUri = Users.updateAvatarUri;

// Users
static final blockUser = Users.blockUser;
static final inviteUser = Users.inviteUser;
static final fetchUserProfile = Users.fetchUserProfile;
static final updateBlockedUsers = Users.updateBlockedUsers;

// Media
static final fetchThumbnail = Media.fetchThumbnail;
Expand Down
16 changes: 7 additions & 9 deletions lib/global/libs/matrix/user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,30 +86,28 @@ abstract class Users {
* to the user that set the account_data. The config will be synced
* to clients in the top-level account_data.
*/
static Future<dynamic> blockUser({
static Future<dynamic> updateBlockedUsers({
String protocol = 'https://',
String homeserver = 'matrix.org',
String accessToken,
String userId,
List<String> roomIds = const [],
Map<String, dynamic> blockUserList = const {"ignored_users": {}},
}) async {
String url =
'$protocol$homeserver/_matrix/client/r0/user/$userId/account_data/${EventTypes.ignoredUserList}';
'$protocol$homeserver/_matrix/client/r0/user/$userId/account_data/${AccountDataTypes.ignoredUserList}';

Map<String, String> headers = {
'Authorization': 'Bearer $accessToken',
};

final accountData = {userId: []};

if (roomIds.isNotEmpty) {
accountData[userId] = roomIds;
}
final body = {
'ignored_users': blockUserList ?? {},
};

final saveResponse = await http.put(
url,
headers: headers,
body: json.encode(accountData),
body: json.encode(body),
);

return await json.decode(
Expand Down
10 changes: 4 additions & 6 deletions lib/store/events/actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ ThunkAction<AppState> fetchMessageEvents({
"limit": limit,
});

printDebug("[fetchMessageEvents] CALLED FOR ${room.name} ${to} ${from}");
printJson(messagesJson);

// The token the pagination ends at. If dir=b this token should be used again to request even earlier events.
final String end = messagesJson['end'];

Expand All @@ -127,11 +130,6 @@ ThunkAction<AppState> fetchMessageEvents({
// The messages themselves
final List<dynamic> messages = messagesJson['chunk'] ?? [];

messages.forEach((msg) {
printDebug("[fetchMessageEvents] *** PRINT MESSAGES *** ${room.name}");
printJson(msg);
});

// reuse the logic for syncing
await store.dispatch(
syncRooms({
Expand All @@ -145,7 +143,7 @@ ThunkAction<AppState> fetchMessageEvents({
}),
);
} catch (error) {
debugPrint('[fetchMessageEvents] $error');
debugPrint('[fetchMessageEvents] error $error');
} finally {
store.dispatch(UpdateRoom(id: room.id, syncing: false));
}
Expand Down
4 changes: 2 additions & 2 deletions lib/store/events/model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ class EventTypes {
static const message = 'm.room.message';
static const encrypted = 'm.room.encrypted';
static const member = 'm.room.member';
static const reaction = 'm.reaction';

static const guestAccess = 'm.room.guest_access';
static const joinRules = 'm.room.join_rules';
static const historyVisibility = 'm.room.history_visibility';
static const powerLevels = 'm.room.power_levels';
static const encryption = 'm.room.encryption';
static const roomKey = 'm.room_key';

static const ignoredUserList = 'm.ignored_user_list';
}

class MessageTypes {
Expand All @@ -42,6 +41,7 @@ class MessageTypes {
static const AUDIO = 'm.text';
static const LOCATION = 'm.location';
static const VIDEO = 'm.video';
static const ANNOTATIONO = 'm.annotation';
}

class MediumType {
Expand Down
8 changes: 8 additions & 0 deletions lib/store/events/selectors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ List<Message> roomMessages(AppState state, String roomId) {
return state.eventStore.messages[roomId] ?? [];
}

// remove messages from blocked users
List<Message> filterMessages(List<Message> messages, List<String> blocked) {
return messages
..removeWhere(
(message) => blocked.contains(message.sender),
);
}

List<Message> latestMessages(List<Message> messages) {
final sortedList = List<Message>.from(messages ?? []);

Expand Down
2 changes: 1 addition & 1 deletion lib/store/index.dart
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ Future<Store> initStore(Database cache, Database storage) async {
storage: CacheStorage(cache: cache),
serializer: CacheSerializer(cache: cache, preloaded: data),
// TODO: can remove once cold storage is in place
throttleDuration: Duration(milliseconds: 4500),
throttleDuration: Duration(milliseconds: 4000),
shouldSave: (Store<AppState> store, dynamic action) {
// TODO: can remove once cold storage is in place
switch (action.runtimeType) {
Expand Down
4 changes: 2 additions & 2 deletions lib/store/rooms/actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ ThunkAction<AppState> removeRoom({Room room}) {
if (leaveData['errcode'] != null) {
if (leaveData['errcode'] == MatrixErrors.room_unknown) {
await store.dispatch(RemoveRoom(roomId: room.id));
} else if (leaveData['errcode'] == MatrixErrors.room_not_found) {
} else if (leaveData['errcode'] == MatrixErrors.not_found) {
await store.dispatch(RemoveRoom(roomId: room.id));
}

Expand All @@ -893,7 +893,7 @@ ThunkAction<AppState> removeRoom({Room room}) {
);

if (forgetData['errcode'] != null) {
if (leaveData['errcode'] == MatrixErrors.room_not_found) {
if (leaveData['errcode'] == MatrixErrors.not_found) {
await store.dispatch(RemoveRoom(roomId: room.id));
}
if (room.direct) {
Expand Down
15 changes: 12 additions & 3 deletions lib/store/rooms/selectors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@ List<Room> rooms(AppState state) {
return state.roomStore.roomList;
}

List<Room> sortedPrioritizedRooms(Map rooms) {
final List<Room> sortedList =
rooms != null ? List<Room>.from(rooms.values) : [];
List<Room> filterBlockedRooms(List<Room> rooms, List<String> blocked) {
final List<Room> roomList = rooms != null ? rooms : [];

return roomList
..removeWhere((room) =>
room.userIds.length == 2 &&
room.userIds.any((userId) => blocked.contains(userId)))
..toList();
}

List<Room> sortedPrioritizedRooms(List<Room> rooms) {
final sortedList = rooms != null ? rooms : [];

// sort descending
sortedList.sort((a, b) {
Expand Down
Loading

0 comments on commit 1aa2771

Please sign in to comment.