[LLC] Refactor attachment_file_uploader usage in client and channel

Signed-off-by: Sahil Kumar <[email protected]>
This commit is contained in:
Sahil Kumar
2021-02-17 20:14:01 +05:30
parent 517c7e489d
commit b29f673e91
5 changed files with 144 additions and 71 deletions
+13 -8
View File
@@ -245,15 +245,20 @@ class Channel {
} }
final isImage = it.type == 'image'; final isImage = it.type == 'image';
final uploader = _client.attachmentUploader;
final cancelToken = CancelToken(); final cancelToken = CancelToken();
Future<String> future; Future<String> future;
if (isImage) { if (isImage) {
future = uploader.uploadImage(it.file, id, type, future = sendImage(
onSendProgress: onSendProgress, cancelToken: cancelToken); it.file,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
).then((it) => it.file);
} else { } else {
future = uploader.uploadFile(it.file, id, type, future = sendFile(
onSendProgress: onSendProgress, cancelToken: cancelToken); it.file,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
).then((it) => it.file);
} }
_cancelableAttachmentUploadRequest[it.id] = cancelToken; _cancelableAttachmentUploadRequest[it.id] = cancelToken;
return future.then((url) { return future.then((url) {
@@ -446,7 +451,7 @@ class Channel {
/// Send a file to this channel /// Send a file to this channel
Future<SendFileResponse> sendFile( Future<SendFileResponse> sendFile(
MultipartFile file, { AttachmentFile file, {
ProgressCallback onSendProgress, ProgressCallback onSendProgress,
CancelToken cancelToken, CancelToken cancelToken,
}) { }) {
@@ -461,12 +466,12 @@ class Channel {
/// Send an image to this channel /// Send an image to this channel
Future<SendImageResponse> sendImage( Future<SendImageResponse> sendImage(
MultipartFile image, { AttachmentFile file, {
ProgressCallback onSendProgress, ProgressCallback onSendProgress,
CancelToken cancelToken, CancelToken cancelToken,
}) { }) {
return _client.sendImage( return _client.sendImage(
image, file,
id, id,
type, type,
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
@@ -1,17 +1,18 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:stream_chat/src/api/responses.dart';
import 'package:stream_chat/src/models/attachment_file.dart'; import 'package:stream_chat/src/models/attachment_file.dart';
import '../client.dart'; import 'client.dart';
import '../extensions/string_extension.dart'; import 'extensions/string_extension.dart';
/// Class responsible for uploading images and files from a given channel /// Class responsible for uploading images and files to a given channel
abstract class AttachmentUploader { abstract class AttachmentFileUploader {
/// Uploads a image [file] to the given channel. /// Uploads a [image] to the given channel.
/// Returns image [file] URL once sent successfully. /// Returns [SendImageResponse] once sent successfully.
/// ///
/// Optionally, access upload progress using [onSendProgress] /// Optionally, access upload progress using [onSendProgress]
/// and cancel the request using [cancelToken] /// and cancel the request using [cancelToken]
Future<String> uploadImage( Future<SendImageResponse> sendImage(
AttachmentFile file, AttachmentFile image,
String channelId, String channelId,
String channelType, { String channelType, {
ProgressCallback onSendProgress, ProgressCallback onSendProgress,
@@ -19,11 +20,11 @@ abstract class AttachmentUploader {
}); });
/// Uploads a [file] to the given channel. /// Uploads a [file] to the given channel.
/// Returns [file] URL once sent successfully. /// Returns [SendFileResponse] once sent successfully.
/// ///
/// Optionally, access upload progress using [onSendProgress] /// Optionally, access upload progress using [onSendProgress]
/// and cancel the request using [cancelToken] /// and cancel the request using [cancelToken]
Future<String> uploadFile( Future<SendFileResponse> sendFile(
AttachmentFile file, AttachmentFile file,
String channelId, String channelId,
String channelType, { String channelType, {
@@ -32,15 +33,15 @@ abstract class AttachmentUploader {
}); });
} }
/// Stream's default implementation of [AttachmentUploader] /// Stream's default implementation of [AttachmentFileUploader]
class StreamAttachmentUploader implements AttachmentUploader { class StreamAttachmentUploader implements AttachmentFileUploader {
final StreamChatClient _client; final StreamChatClient _client;
/// Creates a new [StreamAttachmentUploader] instance. /// Creates a new [StreamAttachmentUploader] instance.
const StreamAttachmentUploader(this._client); const StreamAttachmentUploader(this._client);
@override @override
Future<String> uploadImage( Future<SendImageResponse> sendImage(
AttachmentFile file, AttachmentFile file,
String channelId, String channelId,
String channelType, { String channelType, {
@@ -49,22 +50,23 @@ class StreamAttachmentUploader implements AttachmentUploader {
}) async { }) async {
final filename = file.path?.split('/')?.last; final filename = file.path?.split('/')?.last;
final mimeType = filename.mimeType; final mimeType = filename.mimeType;
final res = await _client.sendImage( final response = await _client.post(
await MultipartFile.fromFile( '/channels/$channelType/$channelId/image',
file.path, data: FormData.fromMap({
filename: filename, 'file': await MultipartFile.fromFile(
contentType: mimeType, file.path,
), filename: filename,
channelId, contentType: mimeType,
channelType, ),
}),
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
); );
return res.file; return _client.decode(response.data, SendImageResponse.fromJson);
} }
@override @override
Future<String> uploadFile( Future<SendFileResponse> sendFile(
AttachmentFile file, AttachmentFile file,
String channelId, String channelId,
String channelType, { String channelType, {
@@ -73,17 +75,18 @@ class StreamAttachmentUploader implements AttachmentUploader {
}) async { }) async {
final filename = file.path?.split('/')?.last; final filename = file.path?.split('/')?.last;
final mimeType = filename.mimeType; final mimeType = filename.mimeType;
final res = await _client.sendFile( final response = await _client.post(
await MultipartFile.fromFile( '/channels/$channelType/$channelId/file',
file.path, data: FormData.fromMap({
filename: filename, 'file': await MultipartFile.fromFile(
contentType: mimeType, file.path,
), filename: filename,
channelId, contentType: mimeType,
channelType, ),
}),
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
); );
return res.file; return _client.decode(response.data, SendFileResponse.fromJson);
} }
} }
+15 -14
View File
@@ -8,11 +8,12 @@ import 'package:pedantic/pedantic.dart' show unawaited;
import 'package:rxdart/rxdart.dart'; import 'package:rxdart/rxdart.dart';
import 'package:stream_chat/src/api/retry_policy.dart'; import 'package:stream_chat/src/api/retry_policy.dart';
import 'package:stream_chat/src/event_type.dart'; import 'package:stream_chat/src/event_type.dart';
import 'package:stream_chat/src/models/attachment_file.dart';
import 'package:stream_chat/src/models/own_user.dart'; import 'package:stream_chat/src/models/own_user.dart';
import 'package:stream_chat/version.dart'; import 'package:stream_chat/version.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import 'api/attachment_uploader.dart'; import 'attachment_file_uploader.dart';
import 'api/channel.dart'; import 'api/channel.dart';
import 'api/connection_status.dart'; import 'api/connection_status.dart';
import 'api/requests.dart'; import 'api/requests.dart';
@@ -102,7 +103,7 @@ class StreamChatClient {
ChatPersistenceClient chatPersistenceClient; ChatPersistenceClient chatPersistenceClient;
/// Attachment uploader /// Attachment uploader
AttachmentUploader attachmentUploader; AttachmentFileUploader attachmentUploader;
/// Whether the chat persistence is available or not /// Whether the chat persistence is available or not
bool get persistenceEnabled => chatPersistenceClient != null; bool get persistenceEnabled => chatPersistenceClient != null;
@@ -1043,36 +1044,36 @@ class StreamChatClient {
/// Send a [file] to the [channelId] of type [channelType] /// Send a [file] to the [channelId] of type [channelType]
Future<SendFileResponse> sendFile( Future<SendFileResponse> sendFile(
MultipartFile file, AttachmentFile file,
String channelId, String channelId,
String channelType, { String channelType, {
ProgressCallback onSendProgress, ProgressCallback onSendProgress,
CancelToken cancelToken, CancelToken cancelToken,
}) async { }) {
final response = await post( return attachmentUploader.sendFile(
'/channels/$channelType/$channelId/file', file,
data: FormData.fromMap({'file': file}), channelId,
channelType,
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
); );
return decode(response.data, SendFileResponse.fromJson);
} }
/// Send a [image] to the [channelId] of type [channelType] /// Send a [image] to the [channelId] of type [channelType]
Future<SendImageResponse> sendImage( Future<SendImageResponse> sendImage(
MultipartFile image, AttachmentFile image,
String channelId, String channelId,
String channelType, { String channelType, {
ProgressCallback onSendProgress, ProgressCallback onSendProgress,
CancelToken cancelToken, CancelToken cancelToken,
}) async { }) {
final response = await post( return attachmentUploader.sendImage(
'/channels/$channelType/$channelId/image', image,
data: FormData.fromMap({'file': image}), channelId,
channelType,
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
); );
return decode(response.data, SendImageResponse.fromJson);
} }
/// Add a device for Push Notifications. /// Add a device for Push Notifications.
+1 -1
View File
@@ -10,7 +10,7 @@ export './src/api/connection_status.dart';
export './src/api/requests.dart'; export './src/api/requests.dart';
export './src/api/requests.dart'; export './src/api/requests.dart';
export './src/api/responses.dart'; export './src/api/responses.dart';
export './src/api/attachment_uploader.dart' show AttachmentUploader; export './src/attachment_file_uploader.dart' show AttachmentFileUploader;
export './src/client.dart'; export './src/client.dart';
export './src/event_type.dart'; export './src/event_type.dart';
export './src/models/action.dart'; export './src/models/action.dart';
@@ -10,8 +10,12 @@ import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/src/models/own_user.dart'; import 'package:stream_chat/src/models/own_user.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:stream_chat/stream_chat.dart';
class MockDio extends Mock implements DioForNative {} class MockDio extends Mock implements DioForNative {}
class MockAttachmentUploader extends Mock implements AttachmentFileUploader {}
class MockHttpClientAdapter extends Mock implements HttpClientAdapter {} class MockHttpClientAdapter extends Mock implements HttpClientAdapter {}
void main() { void main() {
@@ -44,6 +48,61 @@ void main() {
mockDio.post<String>('/channels/messaging/testid/message', data: { mockDio.post<String>('/channels/messaging/testid/message', data: {
'message': message.toJson(), 'message': message.toJson(),
})).called(1); })).called(1);
// final imageFile = MultipartFile.fromString('value');
//
// channelClient
// .sendImage(imageFile)
// .then((response) {
// final imageUrl = response.file;
// final attachment = Attachment(
// type = "image",
// imageUrl = imageUrl,
// )
// val message = Message(
// attachments = mutableListOf(attachment),
// )
// channelClient
// .sendMessage(message)
// .enqueue {
// /* ... */
// }
// })
// .catchError(onError);
//final channelClient = client.channel("messaging", id:'general');
//
// // Upload an image without detailed progress
// channelClient.sendImage(imageFile).enqueue { result->
// if (result.isSuccess) {
// // Successful upload, you can now attach this image
// // to an message that you then send to a channel
// val imageUrl = result.data()
// val attachment = Attachment(
// type = "image",
// imageUrl = imageUrl,
// )
// val message = Message(
// attachments = mutableListOf(attachment),
// )
// channelClient.sendMessage(message).enqueue { /* ... */ }
// }
// }
//
// // Upload a file, monitoring for progress with a ProgressCallback
// channelClient.sendFile(anyOtherFile, object : ProgressCallback {
// override fun onSuccess(file: String) {
// val fileUrl = file
// }
//
// override fun onError(error: ChatError) {
// // Handle error
// }
//
// override fun onProgress(progress: Long) {
// // You can render the uploading progress here
// }
// }).enqueue() // No callback passed to enqueue, as we'll get notified above anyway
}); });
test('markRead', () async { test('markRead', () async {
@@ -170,6 +229,11 @@ void main() {
test('sendFile', () async { test('sendFile', () async {
final mockDio = MockDio(); final mockDio = MockDio();
final mockUploader = MockAttachmentUploader();
final file = AttachmentFile(path: 'filePath/fileName.pdf');
final channelId = 'testId';
final channelType = 'messaging';
when(mockDio.options).thenReturn(BaseOptions()); when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors()); when(mockDio.interceptors).thenReturn(Interceptors());
@@ -178,23 +242,25 @@ void main() {
'api-key', 'api-key',
httpClient: mockDio, httpClient: mockDio,
tokenProvider: (_) async => '', tokenProvider: (_) async => '',
attachmentUploader: mockUploader,
); );
final channelClient = client.channel('messaging', id: 'testid'); final channelClient = client.channel(channelType, id: channelId);
final file = MultipartFile.fromString('file');
when(mockDio.post<String>('/channels/messaging/testid/file', when(mockUploader.sendFile(file, channelId, channelType))
data: argThat(isA<FormData>(), named: 'data'))) .thenAnswer((_) async => SendFileResponse());
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await channelClient.sendFile(file); await channelClient.sendFile(file);
verify(mockDio.post<String>('/channels/messaging/testid/file', verify(mockUploader.sendFile(file, channelId, channelType)).called(1);
data: argThat(isA<FormData>(), named: 'data')))
.called(1);
}); });
test('sendImage', () async { test('sendImage', () async {
final mockDio = MockDio(); final mockDio = MockDio();
final mockUploader = MockAttachmentUploader();
final image = AttachmentFile(path: 'imagePath/imageName.jpeg');
final channelId = 'testId';
final channelType = 'messaging';
when(mockDio.options).thenReturn(BaseOptions()); when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors()); when(mockDio.interceptors).thenReturn(Interceptors());
@@ -203,18 +269,16 @@ void main() {
'api-key', 'api-key',
httpClient: mockDio, httpClient: mockDio,
tokenProvider: (_) async => '', tokenProvider: (_) async => '',
attachmentUploader: mockUploader,
); );
final channelClient = client.channel('messaging', id: 'testid'); final channelClient = client.channel(channelType, id: channelId);
final file = MultipartFile.fromString('file');
when(mockDio.post<String>('/channels/messaging/testid/image', when(mockUploader.sendImage(image, channelId, channelType))
data: argThat(isA<FormData>(), named: 'data'))) .thenAnswer((_) async => SendImageResponse());
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await channelClient.sendImage(file); await channelClient.sendImage(image);
verify(mockDio.post<String>('/channels/messaging/testid/image', verify(mockUploader.sendImage(image, channelId, channelType))
data: argThat(isA<FormData>(), named: 'data')))
.called(1); .called(1);
}); });