Make stream_chat_persistence a add on dependency instead of shipping it with the llc

Signed-off-by: Sahil Kumar <[email protected]>
This commit is contained in:
Sahil Kumar
2021-01-27 12:52:37 +05:30
parent f48b7c8882
commit 1521558304
16 changed files with 126 additions and 187 deletions
+10 -8
View File
@@ -419,7 +419,7 @@ class Channel {
}
}
await _client.chatPersistence?.deleteMessageById(messageId);
await _client.chatPersistenceClient?.deleteMessageById(messageId);
}
return res;
@@ -487,7 +487,7 @@ class Channel {
PaginationParams options, {
bool preferOffline = false,
}) async {
final cachedReplies = await _client.chatPersistence?.getReplies(
final cachedReplies = await _client.chatPersistenceClient?.getReplies(
parentId,
lessThan: options?.lessThan,
);
@@ -603,7 +603,8 @@ class Channel {
}
if (preferOffline && cid != null) {
final updatedState = await _client.chatPersistence?.getChannelStateByCid(
final updatedState =
await _client.chatPersistenceClient?.getChannelStateByCid(
cid,
messagePagination: messagesPagination,
);
@@ -730,7 +731,7 @@ class Channel {
if (clearHistory == true) {
state.truncate();
await _client.chatPersistence?.deleteMessageByCid(_cid);
await _client.chatPersistenceClient?.deleteMessageByCid(_cid);
}
return _client.decode(response.data, EmptyResponse.fromJson);
@@ -869,7 +870,7 @@ class ChannelClientState {
_computeInitialUnread();
_channel._client.chatPersistence
_channel._client.chatPersistenceClient
?.getChannelThreads(_channel.cid)
?.then((threads) {
_threads = threads;
@@ -947,7 +948,8 @@ class ChannelClientState {
.on(EventType.channelTruncated, EventType.notificationChannelTruncated)
.listen((event) async {
final channel = event.channel;
await _channel._client.chatPersistence?.deleteMessageByCid(channel.cid);
await _channel._client.chatPersistenceClient
?.deleteMessageByCid(channel.cid);
truncate();
}));
}
@@ -1401,7 +1403,7 @@ class ChannelClientState {
set _channelState(ChannelState v) {
_channelStateController.add(v);
_channel._client.chatPersistence?.updateChannelState(v);
_channel._client.chatPersistenceClient?.updateChannelState(v);
}
/// The channel threads related to this channel
@@ -1414,7 +1416,7 @@ class ChannelClientState {
BehaviorSubject.seeded({});
set _threads(Map<String, List<Message>> v) {
_channel._client.chatPersistence?.updateMessages(
_channel._client.chatPersistenceClient?.updateMessages(
_channel.cid,
v.values.expand((v) => v).toList(),
);
+24 -31
View File
@@ -6,7 +6,6 @@ import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:logging/logging.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_chat_persistence/stream_chat_persistence.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:stream_chat/src/api/retry_policy.dart';
import 'package:stream_chat/src/event_type.dart';
@@ -21,7 +20,7 @@ import 'api/connection_status.dart';
import 'api/requests.dart';
import 'api/responses.dart';
import 'api/websocket.dart';
import 'db/stream_chat_persistence.dart';
import 'db/chat_persistence_client.dart';
import 'exceptions.dart';
import 'models/event.dart';
import 'models/message.dart';
@@ -87,7 +86,6 @@ class Client {
this.baseURL = _defaultBaseURL,
this.logLevel = Level.WARNING,
this.logHandlerFunction,
this.persistenceEnabled = true,
Duration connectTimeout = const Duration(seconds: 6),
Duration receiveTimeout = const Duration(seconds: 6),
Dio httpClient,
@@ -111,10 +109,11 @@ class Client {
logger.info('instantiating new client');
}
StreamChatPersistence _chatPersistence;
/// Client chat persistence client
ChatPersistenceClient chatPersistenceClient;
/// If true chat data will persist on disk
final bool persistenceEnabled;
/// Whether the chat persistence is available or not
bool get persistenceEnabled => chatPersistenceClient != null;
RetryPolicy _retryPolicy;
@@ -131,9 +130,6 @@ class Client {
/// The amount of time that will pass before disconnecting the client in the background
final Duration backgroundKeepAlive;
/// Client offline database
StreamChatPersistence get chatPersistence => _chatPersistence;
/// This client state
ClientState state;
@@ -345,7 +341,7 @@ class Client {
/// Call this function to dispose the client
void dispose() async {
await _chatPersistence?.disconnect();
await chatPersistenceClient?.disconnect();
await _disconnect();
httpClient.close();
await _controller.close();
@@ -427,8 +423,8 @@ class Client {
if (!event.isLocal) {
if (_synced && event.createdAt != null) {
await _chatPersistence?.updateConnectionInfo(event);
await _chatPersistence?.updateLastSyncAt(event.createdAt);
await chatPersistenceClient?.updateConnectionInfo(event);
await chatPersistenceClient?.updateLastSyncAt(event.createdAt);
}
}
@@ -459,12 +455,8 @@ class Client {
wsConnectionStatus.value = ConnectionStatus.connecting;
if (persistenceEnabled && _chatPersistence == null) {
_chatPersistence = StreamChatPersistenceImpl(
state.user.id,
logger: _detachedLogger('💽'),
);
await _chatPersistence.connect();
if (persistenceEnabled) {
await chatPersistenceClient.connect('db_${state.user.id}');
}
_ws = WebSocket(
@@ -514,10 +506,10 @@ class Client {
_ws.connectionStatus.addListener(_connectionStatusListener);
var event = await _chatPersistence?.getConnectionInfo();
var event = await chatPersistenceClient?.getConnectionInfo();
await _ws.connect().then((e) async {
await _chatPersistence?.updateConnectionInfo(e);
await chatPersistenceClient?.updateConnectionInfo(e);
event = e;
await resync();
}).catchError((err, stacktrace) {
@@ -532,14 +524,14 @@ class Client {
/// Get the events missed while offline to sync the offline storage
Future<void> resync([List<String> cids]) async {
final lastSyncAt = await chatPersistence?.getLastSyncAt();
final lastSyncAt = await chatPersistenceClient?.getLastSyncAt();
if (lastSyncAt == null) {
_synced = true;
return;
}
cids ??= await chatPersistence?.getChannelCids();
cids ??= await chatPersistenceClient?.getChannelCids();
if (cids?.isEmpty == true) {
return;
@@ -568,7 +560,7 @@ class Client {
handleEvent(event);
});
await _chatPersistence?.updateLastSyncAt(DateTime.now());
await chatPersistenceClient?.updateLastSyncAt(DateTime.now());
_synced = true;
} catch (error) {
logger.severe('Error during resync $error');
@@ -714,7 +706,7 @@ class Client {
channels.add(channel);
} else {
final newChannel = Channel.fromState(this, channelState);
await _chatPersistence
await chatPersistenceClient
?.updateChannelState(newChannel.state.channelState);
newChannel.state?.updateChannelState(channelState);
newChannels[newChannel.cid] = newChannel;
@@ -725,7 +717,7 @@ class Client {
state.channels = newChannels;
await _chatPersistence?.updateChannelQueries(
await chatPersistenceClient?.updateChannelQueries(
filter,
res.channels.map((c) => c.channel.cid).toList(),
paginationParams?.offset == null || paginationParams.offset == 0,
@@ -760,7 +752,7 @@ class Client {
@required List<SortOption> sort,
PaginationParams paginationParams = const PaginationParams(limit: 10),
}) async {
final offlineChannels = await _chatPersistence?.getChannelStates(
final offlineChannels = await chatPersistenceClient?.getChannelStates(
filter: filter,
sort: sort,
paginationParams: paginationParams,
@@ -775,7 +767,8 @@ class Client {
return channel;
} else {
final newChannel = Channel.fromState(this, channelState);
_chatPersistence?.updateChannelState(newChannel.state.channelState);
chatPersistenceClient
?.updateChannelState(newChannel.state.channelState);
newChannels[newChannel.cid] = newChannel;
return newChannel;
}
@@ -938,8 +931,8 @@ class Client {
logger.info(
'Disconnecting flushOfflineStorage: $flushChatPersistence; clearUser: $clearUser');
await _chatPersistence?.disconnect(flush: flushChatPersistence);
_chatPersistence = null;
await chatPersistenceClient?.disconnect(flush: flushChatPersistence);
chatPersistenceClient = null;
if (clearUser == true) {
state.dispose();
@@ -1328,7 +1321,7 @@ class ClientState {
void _listenChannelHidden() {
_subscriptions.add(_client.on(EventType.channelHidden).listen((event) {
_client._chatPersistence?.deleteChannels([event.cid]);
_client.chatPersistenceClient?.deleteChannels([event.cid]);
if (channels != null) {
channels = channels..removeWhere((cid, ch) => cid == event.cid);
}
@@ -1353,7 +1346,7 @@ class ClientState {
)
.listen((Event event) async {
final eventChannel = event.channel;
await _client._chatPersistence?.deleteChannels([eventChannel.cid]);
await _client.chatPersistenceClient?.deleteChannels([eventChannel.cid]);
if (channels != null) {
channels = channels..remove(eventChannel.cid);
}
@@ -9,15 +9,12 @@ import 'package:stream_chat/src/models/read.dart';
import 'package:stream_chat/src/models/user.dart';
///
abstract class StreamChatPersistence {
/// Creates a new connection to the database
Future<void> connect({
bool connectBackground = false,
bool logStatements = false,
});
abstract class ChatPersistenceClient {
/// Creates a new connection to the client
Future<void> connect(String name);
/// Closes the database instance
/// If [flush] is true, the database data will be deleted
/// Closes the client connection
/// If [flush] is true, the data will also be deleted
Future<void> disconnect({bool flush = false});
/// Get stored replies by messageId
+14 -40
View File
@@ -1,12 +1,11 @@
import 'dart:convert';
import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:stream_chat/src/api/responses.dart';
import 'package:stream_chat/src/models/channel_model.dart';
import 'package:stream_chat/src/models/channel_state.dart';
import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat_persistence/stream_chat_persistence.dart';
import 'package:meta/meta.dart';
import 'client.dart';
import 'models/own_user.dart';
@@ -20,21 +19,13 @@ class NotificationService {
) async {
if (message != null && client.persistenceEnabled) {
if (client?.state?.channels == null) {
final sharedPreferences = await _getSharedPreferences();
final userId = sharedPreferences.getString(KEY_USER_ID);
final chatPersistence = StreamChatPersistenceImpl(
userId,
logger: Logger('💽'),
);
await chatPersistence.connect();
await chatPersistence.updateChannelState(
final chatPersistenceClient = client.chatPersistenceClient;
await chatPersistenceClient.updateChannelState(
ChannelState(
channel: channelModel,
messages: [message],
),
);
await chatPersistence.disconnect();
} else {
final channel = client.state.channels[channelModel.cid];
channel.state.updateChannelState(
@@ -56,14 +47,11 @@ class NotificationService {
/// Gets the message using the client without storing it in the offline storage
/// It returns an object containing the information about the message and the channel
static Future<GetMessageResponse> getMessage(String messageId) async {
static Future<GetMessageResponse> _getMessage(String messageId) async {
final sharedPreferences = await _getSharedPreferences();
final apiKey = sharedPreferences.getString(KEY_API_KEY);
final client = Client(
apiKey,
persistenceEnabled: false,
);
final client = Client(apiKey);
final userId = sharedPreferences.getString(KEY_USER_ID);
final token = sharedPreferences.getString(KEY_TOKEN);
@@ -74,30 +62,16 @@ class NotificationService {
return res;
}
/// Stores the message in the offline storage
static Future<void> storeMessage(GetMessageResponse messageResponse) async {
final sharedPreferences = await _getSharedPreferences();
final userId = sharedPreferences.getString(KEY_USER_ID);
final chatPersistence = StreamChatPersistenceImpl(
userId,
logger: Logger('💽'),
);
await chatPersistence.connect();
await chatPersistence.updateChannelState(ChannelState(
messages: [messageResponse.message],
channel: messageResponse.channel,
));
await chatPersistence.disconnect();
}
/// Gets the message using the client and stores it in the offline storage
/// Gets the message using the client and calls a [storeMessageHandler] callback
/// with the message if the user wants to save the message in db
///
/// It returns an object containing the information about the message and the channel
static Future<GetMessageResponse> getAndStoreMessage(String messageId) async {
final getMessageResponse = await getMessage(messageId);
await storeMessage(getMessageResponse);
static Future<GetMessageResponse> getAndStoreMessage({
@required String messageId,
@required Future<void> Function(GetMessageResponse) storeMessageHandler,
}) async {
final getMessageResponse = await _getMessage(messageId);
await storeMessageHandler(getMessageResponse);
return getMessageResponse;
}
+1 -1
View File
@@ -27,4 +27,4 @@ export './src/models/reaction.dart';
export './src/models/read.dart';
export './src/models/user.dart';
export './src/notifications.dart';
export './src/db/stream_chat_persistence.dart';
export './src/db/chat_persistence_client.dart';