Skip to content

Commit

Permalink
Merge pull request #1608 from famedly/krille/store-presences
Browse files Browse the repository at this point in the history
feat: Store presences in  database
  • Loading branch information
nico-famedly authored Nov 16, 2023
2 parents 4990960 + 0b35427 commit 76b216c
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 16 deletions.
22 changes: 21 additions & 1 deletion lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1792,12 +1792,13 @@ class Client extends MatrixApi {
await _handleRooms(leave, direction: direction);
}
}
for (final newPresence in sync.presence ?? []) {
for (final newPresence in sync.presence ?? <Presence>[]) {
final cachedPresence = CachedPresence.fromMatrixEvent(newPresence);
presences[newPresence.senderId] = cachedPresence;
// ignore: deprecated_member_use_from_same_package
onPresence.add(newPresence);
onPresenceChanged.add(cachedPresence);
await database?.storePresence(newPresence.senderId, cachedPresence);
}
for (final newAccountData in sync.accountData ?? []) {
await database?.storeAccountData(
Expand Down Expand Up @@ -2925,6 +2926,25 @@ class Client extends MatrixApi {
return;
}

/// The newest presence of this user if there is any. Fetches it from the
/// database first and then from the server if necessary or returns offline.
Future<CachedPresence> fetchCurrentPresence(String userId) async {
final cachedPresence = presences[userId];
if (cachedPresence != null) {
return cachedPresence;
}

final dbPresence = await database?.getPresence(userId);
if (dbPresence != null) return presences[userId] = dbPresence;

try {
final newPresence = await getPresence(userId);
return CachedPresence.fromPresenceResponse(newPresence, userId);
} catch (e) {
return CachedPresence.neverSeen(userId);
}
}

bool _disposed = false;
bool _aborted = false;
Future _currentTransaction = Future.sync(() => {});
Expand Down
4 changes: 4 additions & 0 deletions lib/src/database/database_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,8 @@ abstract class DatabaseApi {
Future<String> exportDump();

Future<bool> importDump(String export);

Future<void> storePresence(String userId, CachedPresence presence);

Future<CachedPresence?> getPresence(String userId);
}
12 changes: 12 additions & 0 deletions lib/src/database/hive_collections_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,18 @@ class HiveCollectionsDatabase extends DatabaseApi {
return raw;
}

@override
Future<void> storePresence(String userId, CachedPresence presence) =>
_presencesBox.put(userId, presence.toJson());

@override
Future<CachedPresence?> getPresence(String userId) async {
final rawPresence = await _presencesBox.get(userId);
if (rawPresence == null) return null;

return CachedPresence.fromJson(copyMap(rawPresence));
}

@override
Future<String> exportDump() async {
final dataMap = {
Expand Down
12 changes: 12 additions & 0 deletions lib/src/database/hive_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,18 @@ class FamedlySdkHiveDatabase extends DatabaseApi {
return raw as String;
}

@override
Future<void> storePresence(String userId, CachedPresence presence) =>
_presencesBox.put(userId, presence.toJson());

@override
Future<CachedPresence?> getPresence(String userId) async {
final rawPresence = await _presencesBox.get(userId);
if (rawPresence == null) return null;

return CachedPresence.fromJson(copyMap(rawPresence));
}

@override
Future<String> exportDump() {
// see no need to implement this in a deprecated part
Expand Down
32 changes: 31 additions & 1 deletion lib/src/presence.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,36 @@ class CachedPresence {
bool? currentlyActive;
String userid;

factory CachedPresence.fromJson(Map<String, Object?> json) =>
CachedPresence._(
presence: PresenceType.values
.singleWhere((type) => type.name == json['presence']),
lastActiveTimestamp: json['last_active_timestamp'] != null
? DateTime.fromMillisecondsSinceEpoch(
json['last_active_timestamp'] as int)
: null,
statusMsg: json['status_msg'] as String?,
currentlyActive: json['currently_active'] as bool?,
userid: json['user_id'] as String,
);

Map<String, Object?> toJson() => {
'user_id': userid,
'presence': presence.name,
if (lastActiveTimestamp != null)
'last_active_timestamp': lastActiveTimestamp?.millisecondsSinceEpoch,
if (statusMsg != null) 'status_msg': statusMsg,
if (currentlyActive != null) 'currently_active': currentlyActive,
};

CachedPresence._({
required this.userid,
required this.presence,
this.lastActiveTimestamp,
this.statusMsg,
this.currentlyActive,
});

CachedPresence(this.presence, int? lastActiveAgo, this.statusMsg,
this.currentlyActive, this.userid) {
if (lastActiveAgo != null) {
Expand All @@ -49,7 +79,7 @@ class CachedPresence {

Presence toPresence() {
final content = <String, dynamic>{
'presence': presence.toString(),
'presence': presence.name.toString(),
};
if (currentlyActive != null) content['currently_active'] = currentlyActive!;
if (lastActiveTimestamp != null) {
Expand Down
18 changes: 4 additions & 14 deletions lib/src/user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -155,20 +155,10 @@ class User extends Event {
@Deprecated('Use fetchCurrentPresence() instead')
Future<CachedPresence> get currentPresence => fetchCurrentPresence();

/// The newest presence of this user if there is any. Fetches it from the server if necessary or returns offline.
Future<CachedPresence> fetchCurrentPresence() async {
final cachedPresence = room.client.presences[id];
if (cachedPresence != null) {
return cachedPresence;
}

try {
final newPresence = await room.client.getPresence(id);
return CachedPresence.fromPresenceResponse(newPresence, id);
} catch (e) {
return CachedPresence.neverSeen(id);
}
}
/// The newest presence of this user if there is any. Fetches it from the
/// database first and then from the server if necessary or returns offline.
Future<CachedPresence> fetchCurrentPresence() =>
room.client.fetchCurrentPresence(id);

/// Whether the client is able to ban/unban this user.
bool get canBan => room.canBan && powerLevel < room.ownPowerLevel;
Expand Down
19 changes: 19 additions & 0 deletions test/database_api_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,25 @@ void testDatabase(
'deviceId',
);
});
test('getStorePresences', () async {
const userId = '@alice:example.com';
final presence = CachedPresence(
PresenceType.online,
100,
'test message',
true,
'@alice:example.com',
);
await database.storePresence(
userId,
presence,
);
final storedPresence = await database.getPresence(userId);
expect(
presence.toJson(),
storedPresence?.toJson(),
);
});

// Clearing up from here
test('clearSSSSCache', () async {
Expand Down

0 comments on commit 76b216c

Please sign in to comment.