Skip to content

Commit

Permalink
TW-784: cancel download when exit the video player
Browse files Browse the repository at this point in the history
  • Loading branch information
sherlockvn committed Nov 17, 2023
1 parent d40272c commit 35c1ee6
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 19 deletions.
10 changes: 10 additions & 0 deletions lib/data/network/media/cancel_exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import 'package:equatable/equatable.dart';

class CancelRequestException with EquatableMixin {
final String? reason;

CancelRequestException({this.reason = ""});

@override
List<Object?> get props => [reason];
}
15 changes: 13 additions & 2 deletions lib/data/network/media/media_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:fluffychat/data/model/media/upload_file_json.dart';
import 'package:fluffychat/data/model/media/url_preview_response.dart';
import 'package:fluffychat/data/network/dio_client.dart';
import 'package:fluffychat/data/network/homeserver_endpoint.dart';
import 'package:fluffychat/data/network/media/cancel_exception.dart';
import 'package:fluffychat/di/global/get_it_initializer.dart';
import 'package:fluffychat/di/global/network_di.dart';
import 'package:matrix/matrix.dart';
Expand Down Expand Up @@ -39,13 +40,23 @@ class MediaAPI {
Future<DownloadFileResponse> downloadFileInfo({
required Uri uriPath,
required String savePath,
CancelToken? cancelToken,
ProgressCallback? onReceiveProgress,
}) async {
final response = await _client.download(
final response = await _client
.download(
uriPath,
savePath: savePath,
onReceiveProgress: onReceiveProgress,
);
cancelToken: cancelToken,
)
.onError((error, stackTrace) {
if (error is DioException && error.type == DioExceptionType.cancel) {
throw CancelRequestException();
} else {
throw Exception(error);
}
});

return DownloadFileResponse(
savePath: savePath,
Expand Down
18 changes: 16 additions & 2 deletions lib/pages/chat/events/download_video_widget.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:dio/dio.dart';
import 'package:fluffychat/pages/chat/events/download_video_state.dart';
import 'package:fluffychat/pages/chat/events/event_video_player.dart';
import 'package:fluffychat/pages/chat/events/message_content_style.dart';
Expand Down Expand Up @@ -28,6 +29,7 @@ class _DownloadVideoWidgetState extends State<DownloadVideoWidget>
final _downloadStateNotifier = ValueNotifier(DownloadVideoState.initial);
String? path;
final downloadProgressNotifier = ValueNotifier(0.0);
final cancelToken = CancelToken();

@override
void initState() {
Expand All @@ -37,6 +39,14 @@ class _DownloadVideoWidgetState extends State<DownloadVideoWidget>
super.initState();
}

@override
void dispose() {
cancelToken.cancel();
downloadProgressNotifier.dispose();
_downloadStateNotifier.dispose();
super.dispose();
}

void _downloadAction() async {
_downloadStateNotifier.value = DownloadVideoState.loading;
try {
Expand All @@ -50,6 +60,7 @@ class _DownloadVideoWidgetState extends State<DownloadVideoWidget>
progressCallback: (count, total) {
downloadProgressNotifier.value = count / total;
},
cancelToken: cancelToken,
);
_downloadStateNotifier.value = DownloadVideoState.done;
} on MatrixConnectionException catch (e) {
Expand All @@ -64,7 +75,7 @@ class _DownloadVideoWidgetState extends State<DownloadVideoWidget>
context,
e.toLocalizedString(context),
);
Logs().w('Error while playing video', e, s);
Logs().e('Error while playing video', e, s);
}
}

Expand All @@ -79,7 +90,10 @@ class _DownloadVideoWidgetState extends State<DownloadVideoWidget>
margin: VideoViewerStyle.backButtonMargin(context),
tooltip: L10n.of(context)!.back,
icon: Icons.close,
onTap: () => Navigator.of(context).pop(),
onTap: () {
cancelToken.cancel();
Navigator.of(context).pop();
},
iconColor: Theme.of(context).colorScheme.surface,
),
Stack(
Expand Down
8 changes: 5 additions & 3 deletions lib/pages/chat/events/event_video_player.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,11 @@ class EventVideoPlayer extends StatelessWidget {
),
CenterVideoButton(
icon: Icons.play_arrow,
onTap: () {
Navigator.of(context, rootNavigator: PlatformInfos.isWeb)
.push(
onTap: () async {
await Navigator.of(
context,
rootNavigator: PlatformInfos.isWeb,
).push(
HeroPageRoute(
builder: (context) {
return InteractiveViewerGallery(
Expand Down
2 changes: 2 additions & 0 deletions lib/presentation/mixins/handle_video_download_mixin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mixin HandleVideoDownloadMixin {
required Event event,
void Function(String uriOrFilePath)? playVideoAction,
ProgressCallback? progressCallback,
CancelToken? cancelToken,
}) async {
lastSelectedVideoEventId = event.eventId;
if (PlatformInfos.isWeb) {
Expand All @@ -33,6 +34,7 @@ mixin HandleVideoDownloadMixin {
} else {
final videoFile = await event.getFileInfo(
progressCallback: progressCallback,
cancelToken: cancelToken,
);
if (lastSelectedVideoEventId == event.eventId &&
playVideoAction != null &&
Expand Down
35 changes: 23 additions & 12 deletions lib/utils/matrix_sdk_extensions/download_file_extension.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fluffychat/data/network/media/cancel_exception.dart';
import 'package:fluffychat/data/network/media/media_api.dart';
import 'package:fluffychat/di/global/get_it_initializer.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions/event_extension.dart';
Expand Down Expand Up @@ -32,6 +33,7 @@ extension DownloadFileExtension on Event {
Uri mxcUrl,
String savePath, {
ProgressCallback? progressCallback,
CancelToken? cancelToken,
bool getThumbnail = false,
}) async {
final database = room.client.database;
Expand All @@ -52,20 +54,27 @@ extension DownloadFileExtension on Event {
await attachment.delete();
}
}

final downloadResponse = await mediaApi.downloadFileInfo(
uriPath: downloadLink,
savePath: savePath,
onReceiveProgress: progressCallback,
);
if (downloadResponse.statusCode == 200) {
return FileInfo(
filename,
savePath,
content.tryGet<int>('size') ?? await File(savePath).length(),
try {
final downloadResponse = await mediaApi.downloadFileInfo(
uriPath: downloadLink,
savePath: savePath,
cancelToken: cancelToken,
onReceiveProgress: progressCallback,
);
if (downloadResponse.statusCode == 200) {
return FileInfo(
filename,
savePath,
content.tryGet<int>('size') ?? await File(savePath).length(),
);
}
throw ('getFileInfo: Download file $filename failed');
} catch (e) {
if (e is CancelRequestException) {
Logs().i("downloadOrRetrieveAttachment: user cancel the download");
}
}
throw ('getFileInfo: Download file $filename failed');
return null;
}

// Decrypt the file if it's encrypted.
Expand Down Expand Up @@ -105,6 +114,7 @@ extension DownloadFileExtension on Event {
Future<FileInfo?> getFileInfo({
getThumbnail = false,
ProgressCallback? progressCallback,
CancelToken? cancelToken,
}) async {
if (!canContainAttachment()) {
throw ("getFileInfo: This event has the type '$type' and so it can't contain an attachment.");
Expand Down Expand Up @@ -153,6 +163,7 @@ extension DownloadFileExtension on Event {
'$tempDirectory/${Uri.encodeComponent(mxcUrl.toString())}',
progressCallback: progressCallback,
getThumbnail: getThumbnail,
cancelToken: cancelToken,
);

if (isFileEncrypted && fileInfo != null && decryptedPath != null) {
Expand Down

0 comments on commit 35c1ee6

Please sign in to comment.