An open-source cross-platform alternative to AirDrop
feat: improve cancel handling
Tien Do Namd39a8d82fc66
diff --git a/assets/i18n/strings.i18n.json b/assets/i18n/strings.i18n.jsonindex 86380ac3..93a3f821 100644--- a/assets/i18n/strings.i18n.json+++ b/assets/i18n/strings.i18n.json@@ -5,9 +5,11 @@"advanced": "Advanced","cancel": "Cancel","close": "Close",+ "continueStr": "Continue","decline": "Decline","done": "Done","error": "Error",+ "finished": "Finished","hide": "Hide","offline": "Offline","online": "Online",@@ -74,10 +76,21 @@"titleSending": "Sending files","titleReceiving": "Receiving files","total": {- "title": "Total progress ({time})",+ "title": {+ "sending": "Total progress ({time})",+ "finishedError": "Finished with error",+ "canceledSender": "Canceled by sender",+ "canceledReceiver": "Canceled by receiver"+ },"count": "Files: {curr} / {n}","size": "Size: {curr} / {n}","speed": "Speed: {speed}/s"}+ },+ "dialogs": {+ "cancelSession": {+ "title": "Cancel file transfer",+ "content": "Do you really want to cancel the file transfer?"+ }}}diff --git a/assets/i18n/strings_de.i18n.json b/assets/i18n/strings_de.i18n.jsonindex b1d22473..f86f6e40 100644--- a/assets/i18n/strings_de.i18n.json+++ b/assets/i18n/strings_de.i18n.json@@ -5,9 +5,11 @@"advanced": "Erweitert","cancel": "Abbrechen","close": "Schließen",+ "continueStr": "Weiter","decline": "Ablehnen","done": "Fertig","error": "Fehler",+ "finished": "Abgeschlossen","hide": "Verstecken","offline": "Offline","online": "Online",@@ -74,10 +76,21 @@"titleSending": "Sende Dateien","titleReceiving": "Empfange Dateien","total": {- "title": "Gesamtfortschritt ({time})",+ "title": {+ "sending": "Gesamtfortschritt ({time})",+ "finishedError": "Abgeschlossen mit Fehler",+ "canceledSender": "Abgebrochen durch Absender",+ "canceledReceiver": "Abgebrochen durch Empfänger"+ },"count": "Dateien: {curr} / {n}","size": "Größe: {curr} / {n}","speed": "Geschwindigkeit: {speed}/s"}+ },+ "dialogs": {+ "cancelSession": {+ "title": "Dateiübertragung abbrechen",+ "content": "Möchtest du wirklich die Dateiübertragung abbrechen?"+ }}}diff --git a/lib/pages/progress_page.dart b/lib/pages/progress_page.dartindex e7d20eaa..bf4e60bb 100644--- a/lib/pages/progress_page.dart+++ b/lib/pages/progress_page.dart@@ -11,6 +11,7 @@ import 'package:localsend_app/provider/progress_provider.dart';import 'package:localsend_app/util/file_size_helper.dart';import 'package:localsend_app/util/file_speed_helper.dart';import 'package:localsend_app/widget/custom_progress_bar.dart';+import 'package:localsend_app/widget/dialogs/cancel_session_dialog.dart';import 'package:routerino/routerino.dart';class ProgressPage extends ConsumerStatefulWidget {@@ -49,6 +50,22 @@ class _ProgressPageState extends ConsumerState<ProgressPage> {});}+ Future<bool> _askCancelConfirmation(SessionStatus status) async {+ final bool result = status == SessionStatus.sending ? await context.pushBottomSheet(() => const CancelSessionDialog()) : true;+ if (result) {+ final receiveState = ref.read(serverProvider.select((s) => s?.receiveState));+ final sendState = ref.read(sendProvider);++ if (receiveState != null) {+ ref.read(serverProvider.notifier).cancelSession();+ } else if (sendState != null) {+ ref.read(sendProvider.notifier).cancelSession();+ }+ ref.read(progressProvider.notifier).reset();+ }+ return result;+ }+@overrideWidget build(BuildContext context) {final ProgressNotifier progressNotifier = ref.watch(progressProvider);@@ -76,156 +93,156 @@ class _ProgressPageState extends ConsumerState<ProgressPage> {remainingTime = null;}- return Scaffold(- body: Stack(- children: [- ListView.builder(- padding: EdgeInsets.only(- top: MediaQuery.of(context).padding.top + 20,- bottom: 150,- left: 15,- right: 30,- ),- itemCount: _files.length + 1,- itemBuilder: (context, index) {- if (index == 0) {- // title- return Text(- receiveState != null ? t.progressPage.titleReceiving : t.progressPage.titleSending,- style: Theme.of(context).textTheme.headline6,- );- }+ return WillPopScope(+ onWillPop: () => _askCancelConfirmation(status),+ child: Scaffold(+ body: Stack(+ children: [+ ListView.builder(+ padding: EdgeInsets.only(+ top: MediaQuery.of(context).padding.top + 20,+ bottom: 150,+ left: 15,+ right: 30,+ ),+ itemCount: _files.length + 1,+ itemBuilder: (context, index) {+ if (index == 0) {+ // title+ return Text(+ receiveState != null ? t.progressPage.titleReceiving : t.progressPage.titleSending,+ style: Theme.of(context).textTheme.headline6,+ );+ }- final file = _files[index - 1];- final fileStatus = receiveState?.files[file.id]?.status ?? sendState!.files[file.id]!.status;+ final file = _files[index - 1];+ final fileStatus = receiveState?.files[file.id]?.status ?? sendState!.files[file.id]!.status;- return Padding(- padding: const EdgeInsets.symmetric(vertical: 10),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Icon(file.fileType.icon, size: 46),- const SizedBox(width: 10),- Expanded(+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(file.fileType.icon, size: 46),+ const SizedBox(width: 10),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ file.fileName,+ style: const TextStyle(fontSize: 16),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ Text(' (${file.size.asReadableFileSize})', style: const TextStyle(fontSize: 16)),+ ],+ ),+ if (fileStatus == FileStatus.sending)+ Padding(+ padding: const EdgeInsets.only(top: 5),+ child: CustomProgressBar(+ progress: progressNotifier.getProgress(file.id),+ ),+ )+ else+ Text(fileStatus.label, style: TextStyle(color: fileStatus.getColor(context))),+ ],+ ),+ ),+ ],+ ),+ );+ },+ ),+ SafeArea(+ child: Align(+ alignment: Alignment.bottomCenter,+ child: Padding(+ padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),+ child: Card(+ child: Padding(+ padding: const EdgeInsets.only(left: 15, right: 15, bottom: 5, top: 10),child: Column(crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,children: [+ Text(+ status.getLabel(+ remainingTime: remainingTime ?? '-',+ ),+ style: const TextStyle(fontSize: 20),+ ),+ const SizedBox(height: 5),+ CustomProgressBar(+ progress: _totalBytes == 0 ? 0 : currBytes / _totalBytes,+ borderRadius: 5,+ color: Theme.of(context).colorScheme.tertiaryContainer,+ ),+ AnimatedCrossFade(+ crossFadeState: _advanced ? CrossFadeState.showSecond : CrossFadeState.showFirst,+ duration: const Duration(milliseconds: 200),+ alignment: Alignment.topLeft,+ firstChild: Container(),+ secondChild: Padding(+ padding: const EdgeInsets.only(top: 10, bottom: 5),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(t.progressPage.total.count(+ curr: progressNotifier.getFinishedCount(),+ n: _filesWithToken.length,+ )),+ Text(t.progressPage.total.size(+ curr: currBytes.asReadableFileSize,+ n: _totalBytes == double.maxFinite.toInt() ? '-' : _totalBytes.asReadableFileSize,+ )),+ if (speedInBytes != null)+ Text(t.progressPage.total.speed(+ speed: speedInBytes.asReadableFileSize,+ )),+ ],+ ),+ ),+ ),+ const SizedBox(height: 5),Row(+ mainAxisAlignment: MainAxisAlignment.end,children: [- Flexible(- child: Text(- file.fileName,- style: const TextStyle(fontSize: 16),- maxLines: 1,- overflow: TextOverflow.ellipsis,- ),+ TextButton.icon(+ style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),+ onPressed: () {+ setState(() => _advanced = !_advanced);+ },+ icon: const Icon(Icons.info),+ label: Text(_advanced ? t.general.hide : t.general.advanced),),- Text(' (${file.size.asReadableFileSize})', style: const TextStyle(fontSize: 16)),- ],- ),- if (fileStatus == FileStatus.sending)- Padding(- padding: const EdgeInsets.only(top: 5),- child: CustomProgressBar(- progress: progressNotifier.getProgress(file.id),+ TextButton.icon(+ style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),+ onPressed: () async {+ final result = await _askCancelConfirmation(status);+ if (result && mounted) {+ context.pushRootImmediately(() => const HomePage());+ }+ },+ icon: Icon(status == SessionStatus.sending ? Icons.close : Icons.check_circle),+ label: Text(status == SessionStatus.sending ? t.general.cancel : t.general.done),),- )- else- Text(fileStatus.label, style: TextStyle(color: fileStatus.getColor(context))),+ ],+ )],),),- ],- ),- );- },- ),- SafeArea(- child: Align(- alignment: Alignment.bottomCenter,- child: Padding(- padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),- child: Card(- child: Padding(- padding: const EdgeInsets.only(left: 15, right: 15, bottom: 5, top: 10),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- Text(- t.progressPage.total.title(- time: endTime != null ? t.general.done : (remainingTime ?? '-'),- ),- style: const TextStyle(fontSize: 20),- ),- const SizedBox(height: 5),- CustomProgressBar(- progress: _totalBytes == 0 ? 0 : currBytes / _totalBytes,- borderRadius: 5,- color: Theme.of(context).colorScheme.tertiaryContainer,- ),- AnimatedCrossFade(- crossFadeState: _advanced ? CrossFadeState.showSecond : CrossFadeState.showFirst,- duration: const Duration(milliseconds: 200),- alignment: Alignment.topLeft,- firstChild: Container(),- secondChild: Padding(- padding: const EdgeInsets.only(top: 10, bottom: 5),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(t.progressPage.total.count(- curr: progressNotifier.getFinishedCount(),- n: _filesWithToken.length,- )),- Text(t.progressPage.total.size(- curr: currBytes.asReadableFileSize,- n: _totalBytes == double.maxFinite.toInt() ? '-' : _totalBytes.asReadableFileSize,- )),- if (speedInBytes != null)- Text(t.progressPage.total.speed(- speed: speedInBytes.asReadableFileSize,- )),- ],- ),- ),- ),- const SizedBox(height: 5),- Row(- mainAxisAlignment: MainAxisAlignment.end,- children: [- TextButton.icon(- style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),- onPressed: () {- setState(() => _advanced = !_advanced);- },- icon: const Icon(Icons.info),- label: Text(_advanced ? t.general.hide : t.general.advanced),- ),- TextButton.icon(- style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),- onPressed: () {- if (receiveState != null) {- ref.read(serverProvider.notifier).closeSession();- } else if (sendState != null) {- ref.read(sendProvider.notifier).cancel();- }- ref.read(progressProvider.notifier).reset();- context.pushRootImmediately(() => const HomePage());- },- icon: const Icon(Icons.check_circle),- label: Text(t.general.done),- ),- ],- )- ],- ),),),),),- ),- ],+ ],+ ),),);}@@ -262,3 +279,25 @@ extension on FileStatus {}}}++extension on SessionStatus {+ String getLabel({required String remainingTime}) {+ switch (this) {+ case SessionStatus.sending:+ return t.progressPage.total.title.sending(+ time: remainingTime,+ );+ case SessionStatus.finished:+ return t.general.finished;+ case SessionStatus.finishedWithErrors:+ return t.progressPage.total.title.finishedError;+ case SessionStatus.canceledBySender:+ return t.progressPage.total.title.canceledSender;+ case SessionStatus.canceledByReceiver:+ return t.progressPage.total.title.canceledReceiver;+ default:+ print(this);+ return '';+ }+ }+}diff --git a/lib/pages/receive_page.dart b/lib/pages/receive_page.dartindex f78b454b..2642c07a 100644--- a/lib/pages/receive_page.dart+++ b/lib/pages/receive_page.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';import 'package:localsend_app/gen/strings.g.dart';+import 'package:localsend_app/model/server/receive_state.dart';import 'package:localsend_app/model/session_status.dart';import 'package:localsend_app/pages/progress_page.dart';import 'package:localsend_app/provider/network/server_provider.dart';@@ -11,6 +12,14 @@ import 'package:routerino/routerino.dart';class ReceivePage extends ConsumerWidget {const ReceivePage({Key? key}) : super(key: key);+ void _accept(WidgetRef ref, ReceiveState receiveState) {+ ref.read(serverProvider.notifier).acceptFileRequest(receiveState.files.values.map((f) => f.file.id).toSet());+ }++ void _decline(WidgetRef ref) {+ ref.read(serverProvider.notifier).declineFileRequest();+ }+@overrideWidget build(BuildContext context, WidgetRef ref) {final receiveState = ref.watch(serverProvider)?.receiveState;@@ -20,99 +29,108 @@ class ReceivePage extends ConsumerWidget {body: Container(),);}- return Scaffold(- body: SafeArea(- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),- child: Column(- children: [- Expanded(- child: Column(- mainAxisAlignment: MainAxisAlignment.center,- children: [- Icon(receiveState.sender.deviceType.icon, size: 64),- const SizedBox(height: 10),- Text(- receiveState.sender.alias,- style: const TextStyle(fontSize: 48),- textAlign: TextAlign.center,- ),- const SizedBox(height: 10),- Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [- DeviceBadge(- color: Theme.of(context).colorScheme.tertiaryContainer,- label: '#${receiveState.sender.ip.visualId}',- ),- if (receiveState.sender.deviceModel != null)- Padding(- padding: const EdgeInsets.only(left: 10),- child: DeviceBadge(- color: Theme.of(context).colorScheme.tertiaryContainer,- label: receiveState.sender.deviceModel!,- ),+ return WillPopScope(+ onWillPop: () async {+ _decline(ref);+ return true;+ },+ child: Scaffold(+ body: SafeArea(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),+ child: Column(+ children: [+ Expanded(+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Icon(receiveState.sender.deviceType.icon, size: 64),+ const SizedBox(height: 10),+ Text(+ receiveState.sender.alias,+ style: const TextStyle(fontSize: 48),+ textAlign: TextAlign.center,+ ),+ const SizedBox(height: 10),+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ DeviceBadge(+ color: Theme.of(context).colorScheme.tertiaryContainer,+ label: '#${receiveState.sender.ip.visualId}',),- ],+ if (receiveState.sender.deviceModel != null)+ Padding(+ padding: const EdgeInsets.only(left: 10),+ child: DeviceBadge(+ color: Theme.of(context).colorScheme.tertiaryContainer,+ label: receiveState.sender.deviceModel!,+ ),+ ),+ ],+ ),+ const SizedBox(height: 40),+ Text(+ t.receivePage.subTitle(n: receiveState.files.length),+ style: Theme.of(context).textTheme.headline6,+ textAlign: TextAlign.center,+ ),+ ],+ ),+ ),+ if (receiveState.status == SessionStatus.canceledBySender)+ ...[+ Padding(+ padding: const EdgeInsets.only(bottom: 20),+ child: Text(t.receivePage.canceled, style: const TextStyle(color: Colors.orange), textAlign: TextAlign.center),),- const SizedBox(height: 40),- Text(- t.receivePage.subTitle(n: receiveState.files.length),- style: Theme.of(context).textTheme.headline6,- textAlign: TextAlign.center,+ Center(+ child: ElevatedButton.icon(+ onPressed: () {+ ref.read(serverProvider.notifier).closeSession();+ context.pop();+ },+ icon: const Icon(Icons.check_circle),+ label: Text(t.general.close),+ ),),- ],- ),- ),- if (receiveState.status == SessionStatus.canceledBySender)- ...[- Padding(- padding: const EdgeInsets.only(bottom: 20),- child: Text(t.receivePage.canceled, style: const TextStyle(color: Colors.orange), textAlign: TextAlign.center),- ),- Center(- child: ElevatedButton.icon(+ ]+ else+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ ElevatedButton.icon(+ style: ElevatedButton.styleFrom(+ backgroundColor: Theme.of(context).buttonTheme.colorScheme!.error,+ foregroundColor: Colors.white, // wrong in dark mode, so we hard code this+ ),onPressed: () {- ref.read(serverProvider.notifier).closeSession();+ _decline(ref);context.pop();},- icon: const Icon(Icons.check_circle),- label: Text(t.general.close),+ icon: const Icon(Icons.close),+ label: Text(t.general.decline),),- ),- ]- else- Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [- ElevatedButton.icon(- style: ElevatedButton.styleFrom(- backgroundColor: Theme.of(context).buttonTheme.colorScheme!.error,- foregroundColor: Colors.white, // wrong in dark mode, so we hard code this- ),- onPressed: () {- ref.read(serverProvider.notifier).declineFileRequest();- context.pop();- },- icon: const Icon(Icons.close),- label: Text(t.general.decline),- ),- const SizedBox(width: 20),- ElevatedButton.icon(- style: ElevatedButton.styleFrom(- backgroundColor: Theme.of(context).buttonTheme.colorScheme!.primary,- foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,+ const SizedBox(width: 20),+ ElevatedButton.icon(+ style: ElevatedButton.styleFrom(+ backgroundColor: Theme.of(context).buttonTheme.colorScheme!.primary,+ foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,+ ),+ onPressed: () {+ _accept(ref, receiveState);+ context.pushAndRemoveUntilImmediately(+ removeUntil: ReceivePage,+ builder: () => const ProgressPage(),+ );+ },+ icon: const Icon(Icons.check_circle),+ label: Text(t.general.accept),),- onPressed: () {- ref.read(serverProvider.notifier).acceptFileRequest(receiveState.files.values.map((f) => f.file.id).toSet());- context.pushImmediately(() => const ProgressPage());- },- icon: const Icon(Icons.check_circle),- label: Text(t.general.accept),- ),- ],- ),- ],+ ],+ ),+ ],+ ),),),),diff --git a/lib/pages/send_page.dart b/lib/pages/send_page.dartindex 84d3641d..abc15d02 100644--- a/lib/pages/send_page.dart+++ b/lib/pages/send_page.dart@@ -34,6 +34,21 @@ class _SendPageState extends ConsumerState<SendPage> {});}+ void _cancel() {+ // the state will be lost so we store them temporarily (only for UI)+ final myDevice = ref.read(deviceInfoProvider);+ final sendState = ref.read(sendProvider);+ if (sendState == null) {+ return;+ }++ setState(() {+ _myDevice = myDevice;+ _targetDevice = sendState.target;+ });+ ref.read(sendProvider.notifier).cancelSession();+ }+@overrideWidget build(BuildContext context) {final sendState = ref.watch(sendProvider);@@ -44,62 +59,64 @@ class _SendPageState extends ConsumerState<SendPage> {}final myDevice = ref.watch(deviceInfoProvider);- return Scaffold(- body: SafeArea(- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 30),- child: Column(- children: [- Expanded(- child: Column(- children: [- Hero(- tag: 'this-device',- child: DeviceListTile(- device: myDevice,- thisDevice: !_showName,+ return WillPopScope(+ onWillPop: () async {+ _cancel();+ return true;+ },+ child: Scaffold(+ body: SafeArea(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 30),+ child: Column(+ children: [+ Expanded(+ child: Column(+ children: [+ Hero(+ tag: 'this-device',+ child: DeviceListTile(+ device: myDevice,+ thisDevice: !_showName,+ ),),- ),- const SizedBox(height: 20),- const Icon(Icons.arrow_downward),- const SizedBox(height: 20),- Hero(- tag: 'device-${(sendState?.target ?? _targetDevice)?.ip}',- child: DeviceListTile(- device: sendState?.target ?? _targetDevice!,+ const SizedBox(height: 20),+ const Icon(Icons.arrow_downward),+ const SizedBox(height: 20),+ Hero(+ tag: 'device-${(sendState?.target ?? _targetDevice)?.ip}',+ child: DeviceListTile(+ device: sendState?.target ?? _targetDevice!,+ ),),- ),- ],+ ],+ ),),- ),- if (sendState != null)- ...[- if (sendState.status == SessionStatus.waiting)- Padding(- padding: const EdgeInsets.only(bottom: 20),- child: Text(t.sendPage.waiting, textAlign: TextAlign.center),- )- else if (sendState.status == SessionStatus.declined)- Padding(- padding: const EdgeInsets.only(bottom: 20),- child: Text(t.sendPage.rejected, style: const TextStyle(color: Colors.orange), textAlign: TextAlign.center),- ),- Center(- child: ElevatedButton.icon(- onPressed: () {- setState(() {- _myDevice = myDevice;- _targetDevice = sendState.target;- });- ref.read(sendProvider.notifier).cancel();- context.pop();- },- icon: Icon(sendState.status == SessionStatus.declined ? Icons.check_circle : Icons.close),- label: Text(sendState.status == SessionStatus.declined ? t.general.close : t.general.cancel),+ if (sendState != null)+ ...[+ if (sendState.status == SessionStatus.waiting)+ Padding(+ padding: const EdgeInsets.only(bottom: 20),+ child: Text(t.sendPage.waiting, textAlign: TextAlign.center),+ )+ else if (sendState.status == SessionStatus.declined)+ Padding(+ padding: const EdgeInsets.only(bottom: 20),+ child: Text(t.sendPage.rejected, style: const TextStyle(color: Colors.orange), textAlign: TextAlign.center),+ ),+ Center(+ child: ElevatedButton.icon(+ onPressed: () {+ _cancel();+ context.pop();+ },+ icon: Icon(sendState.status == SessionStatus.declined ? Icons.check_circle : Icons.close),+ label: Text(sendState.status == SessionStatus.declined ? t.general.close : t.general.cancel),+ ),),- ),- ],- ],+ ],+ ],+ ),),),),diff --git a/lib/pages/tabs/send_tab.dart b/lib/pages/tabs/send_tab.dartindex d1bb1fcd..12ceeaf6 100644--- a/lib/pages/tabs/send_tab.dart+++ b/lib/pages/tabs/send_tab.dart@@ -138,7 +138,7 @@ class _SendTabState extends ConsumerState<SendTab> {child: DeviceListTile(device: device,onTap: () {- ref.read(sendProvider.notifier).sendRequest(+ ref.read(sendProvider.notifier).startSession(target: device,files: ref.read(selectedFilesProvider),);diff --git a/lib/provider/network/nearby_devices_provider.dart b/lib/provider/network/nearby_devices_provider.dartindex 66a0fb66..26952f24 100644--- a/lib/provider/network/nearby_devices_provider.dart+++ b/lib/provider/network/nearby_devices_provider.dart@@ -21,9 +21,11 @@ class NearbyDevicesNotifier extends StateNotifier<NearbyDevicesState> {state = state.copyWith(running: true);await _getStream(localIp, port).forEach((device) {- state = state.copyWith(- devices: [...state.devices, device],- );+ if (state.devices.every((d) => d.ip != device.ip)) {+ state = state.copyWith(+ devices: [...state.devices, device],+ );+ }});state = state.copyWith(running: false);diff --git a/lib/provider/network/send_provider.dart b/lib/provider/network/send_provider.dartindex 4177ca78..1e293c27 100644--- a/lib/provider/network/send_provider.dart+++ b/lib/provider/network/send_provider.dart@@ -32,7 +32,7 @@ class SendNotifier extends StateNotifier<SendState?> {SendNotifier(this._ref) : super(null);- Future<void> sendRequest({+ Future<void> startSession({required Device target,required List<PlatformFile> files,}) async {@@ -101,7 +101,10 @@ class SendNotifier extends StateNotifier<SendState?> {};// ignore: use_build_context_synchronously- Routerino.context.push(() => const ProgressPage());+ Routerino.context.pushAndRemoveUntilImmediately(+ removeUntil: SendPage,+ builder: () => const ProgressPage(),+ );state = requestState.copyWith(status: SessionStatus.sending,@@ -139,6 +142,8 @@ class SendNotifier extends StateNotifier<SendState?> {bool hasErrorForFile = false;try {+ final cancelToken = CancelToken();+ state = state?.copyWith(cancelToken: cancelToken);await Dio().post(ApiRoute.send.target(target, query: {'fileId': file.file.id,@@ -153,6 +158,7 @@ class SendNotifier extends StateNotifier<SendState?> {onSendProgress: (curr, total) {_ref.read(progressProvider.notifier).setProgress(file.file.id, curr / total);},+ cancelToken: cancelToken,);} on DioError catch (e) {hasErrorForFile = true;@@ -165,7 +171,12 @@ class SendNotifier extends StateNotifier<SendState?> {print(st);}- state = state?.withFileStatus(file.file.id, hasErrorForFile ? FileStatus.failed : FileStatus.finished);+ if (state == null) {+ // session already closed+ return;+ } else {+ state = state?.withFileStatus(file.file.id, hasErrorForFile ? FileStatus.failed : FileStatus.finished);+ }}state = state?.copyWith(@@ -175,12 +186,13 @@ class SendNotifier extends StateNotifier<SendState?> {print('Files sent successfully.');}- Future<void> cancel() async {+ /// Closes the send-session and sends a cancel event to the receiver.+ Future<void> cancelSession() async {final target = state?.target;if (target == null) {return;}- state?.cancelToken?.cancel();+ state?.cancelToken?.cancel(); // cancel current requeststate = null;try {await Dio().post(ApiRoute.cancel.target(target));diff --git a/lib/provider/network/server_provider.dart b/lib/provider/network/server_provider.dartindex 1466d570..50ff7942 100644--- a/lib/provider/network/server_provider.dart+++ b/lib/provider/network/server_provider.dart@@ -139,6 +139,11 @@ class ServerNotifier extends StateNotifier<ServerState?> {// Delayed response (waiting for user's decision)final result = await streamController.stream.first;if (result) {+ state = state?.copyWith(+ receiveState: state?.receiveState?.copyWith(+ status: SessionStatus.sending,+ ),+ );return Response.ok(jsonEncode({for (final file in state!.receiveState!.files.values) file.file.id: file.token,@@ -151,9 +156,9 @@ class ServerNotifier extends StateNotifier<ServerState?> {router.post(ApiRoute.send.path, (Request request) async {final receiveState = state?.receiveState;- if (receiveState == null || request.ip != receiveState.sender.ip) {+ if (receiveState == null || request.ip != receiveState.sender.ip || receiveState.status != SessionStatus.sending) {// reject because there is no session or IP does not match session- print('No session or wrong IP');+ print('No session or wrong IP. Current status: ${receiveState?.status}');return Response.badRequest();}@@ -197,9 +202,13 @@ class ServerNotifier extends StateNotifier<ServerState?> {}},);+ if (state?.receiveState == null || state!.receiveState!.status != SessionStatus.sending) {+ return Response.badRequest();+ }state = state?.copyWith(receiveState: state?.receiveState?.withFileStatus(fileId, FileStatus.finished),);+ print('Saved ${receivingFile.file.fileName}.');} catch (e, st) {state = state?.copyWith(receiveState: state?.receiveState?.withFileStatus(fileId, FileStatus.failed),@@ -208,8 +217,6 @@ class ServerNotifier extends StateNotifier<ServerState?> {print(st);}- print('Saved ${receivingFile.file.fileName}.');-final progressNotifier = _ref.read(progressProvider.notifier);progressNotifier.setProgress(fileId, 1);@@ -300,6 +307,19 @@ class ServerNotifier extends StateNotifier<ServerState?> {}}+ /// In addition to [closeSession], this method also cancels incoming requests.+ void cancelSession() {+ final tempState = state;+ if (tempState == null) {+ // the server is not running+ return;+ }+ closeSession();++ // TODO: cancel incoming requests (https://github.com/dart-lang/shelf/issues/319)+ // restartServer(alias: tempState.alias, port: tempState.port);+ }+void closeSession() {state = state?.copyWith(receiveState: null,diff --git a/lib/util/file_saver.dart b/lib/util/file_saver.dartindex ec6a280e..5f60b3a6 100644--- a/lib/util/file_saver.dart+++ b/lib/util/file_saver.dart@@ -8,18 +8,33 @@ Future<void> saveFile({required void Function(int savedBytes) onProgress,}) async {final sink = File(destinationPath).openWrite();- int lastNotifyBytes = 0;- int savedBytes = 0;- await stream.forEach((event) {- sink.add(event);+ try {+ int lastNotifyBytes = 0;+ int savedBytes = 0;+ await stream.forEach((event) {+ sink.add(event);- savedBytes += event.length;- if (savedBytes - lastNotifyBytes >= 100 * 1024) {- lastNotifyBytes = savedBytes;- onProgress(savedBytes);- }- });+ savedBytes += event.length;+ if (savedBytes - lastNotifyBytes >= 100 * 1024) {+ lastNotifyBytes = savedBytes;+ onProgress(savedBytes);+ }+ });- onProgress(savedBytes); // always emit final event- await sink.close();+ onProgress(savedBytes); // always emit final event+ } catch (_) {+ try {+ await sink.close();+ await File(destinationPath).delete();+ } catch (e) {+ print(e);+ }+ rethrow;+ } finally {+ try {+ await sink.close();+ } catch (e) {+ print(e);+ }+ }}diff --git a/lib/widget/dialogs/cancel_session_dialog.dart b/lib/widget/dialogs/cancel_session_dialog.dartnew file mode 100644index 00000000..a046e843--- /dev/null+++ b/lib/widget/dialogs/cancel_session_dialog.dart@@ -0,0 +1,30 @@+import 'package:flutter/material.dart';+import 'package:localsend_app/gen/strings.g.dart';+import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';+import 'package:routerino/routerino.dart';++class CancelSessionDialog extends StatelessWidget {+ const CancelSessionDialog();++ @override+ Widget build(BuildContext context) {+ return CustomBottomSheet(+ title: t.dialogs.cancelSession.title,+ description: t.dialogs.cancelSession.content,+ child: Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ TextButton(+ onPressed: () => context.pop(false),+ child: Text(t.general.continueStr),+ ),+ ElevatedButton.icon(+ onPressed: () => context.pop(true),+ icon: const Icon(Icons.close),+ label: Text(t.general.cancel),+ ),+ ],+ ),+ );+ }+}diff --git a/lib/widget/dialogs/custom_bottom_sheet.dart b/lib/widget/dialogs/custom_bottom_sheet.dartnew file mode 100644index 00000000..70083da0--- /dev/null+++ b/lib/widget/dialogs/custom_bottom_sheet.dart@@ -0,0 +1,24 @@+import 'package:flutter/material.dart';+import 'package:routerino/routerino.dart';++class CustomBottomSheet extends StatelessWidget {+ final String title;+ final String? description;+ final Widget child;+ const CustomBottomSheet({+ required this.title,+ required this.description,+ required this.child,+ });++ @override+ Widget build(BuildContext context) {+ return RouterinoBottomSheet(+ title: title,+ description: description,+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ borderRadius: 20,+ child: child,+ );+ }+}