Skip to content

An open-source cross-platform alternative to AirDrop

feat: send files

Tien Do Nam3eff68cc0687
diff --git a/analysis_options.yaml b/analysis_options.yaml
index e1893910..f8fd8fb2 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -13,3 +13,4 @@ linter:
rules:
avoid_print: false
use_key_in_widget_constructors: false
+ sort_pub_dependencies: true
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 43e5696e..560e55a9 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -1,5 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.localsend.localsend_app">
+
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
<application
android:label="LocalSend"
android:name="${applicationName}"
diff --git a/lib/model/file_type.dart b/lib/model/file_type.dart
index fe0b3d4b..9ed448fd 100644
--- a/lib/model/file_type.dart
+++ b/lib/model/file_type.dart
@@ -7,26 +7,3 @@ enum FileType {
text,
other,
}
-
-extension FileTypeGuessExt on String {
- FileType guessFileType() {
- final extension = substring(lastIndexOf('.') + 1).toLowerCase();
- switch (extension) {
- case 'jpg':
- case 'jpeg':
- case 'png':
- case 'gif':
- case 'svg':
- return FileType.image;
- case 'mp4':
- case 'mov':
- return FileType.video;
- case 'pdf':
- return FileType.pdf;
- case 'txt':
- return FileType.text;
- default:
- return FileType.other;
- }
- }
-}
diff --git a/lib/model/send/sending_file.dart b/lib/model/send/sending_file.dart
index 5c242bb9..bc44e83f 100644
--- a/lib/model/send/sending_file.dart
+++ b/lib/model/send/sending_file.dart
@@ -1,5 +1,3 @@
-import 'dart:typed_data';
-
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:localsend_app/model/dto/file_dto.dart';
@@ -10,6 +8,7 @@ class SendingFile with _$SendingFile {
const factory SendingFile({
required FileDto file,
required String? token,
- required Future<Uint8List> Function() read,
+ required String? path, // android, iOS, desktop
+ required List<int>? bytes, // web
}) = _SendingFile;
}
diff --git a/lib/pages/send_page.dart b/lib/pages/send_page.dart
index 6d322590..f0a756f4 100644
--- a/lib/pages/send_page.dart
+++ b/lib/pages/send_page.dart
@@ -20,14 +20,14 @@ class _SendPageState extends ConsumerState<SendPage> {
Device? _myDevice;
Device? _targetDevice;
- // show name of sender after one second
+ // show name of sender after a delay
bool _showName = false;
@override
void initState() {
super.initState();
- sleepAsync(1000).then((value) {
+ sleepAsync(500).then((value) {
if (mounted) {
setState(() => _showName = true);
}
diff --git a/lib/provider/network/send_provider.dart b/lib/provider/network/send_provider.dart
index 3c3c5488..379000db 100644
--- a/lib/provider/network/send_provider.dart
+++ b/lib/provider/network/send_provider.dart
@@ -1,18 +1,21 @@
+import 'dart:io';
+
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
+import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:localsend_app/main.dart';
import 'package:localsend_app/model/device.dart';
import 'package:localsend_app/model/dto/file_dto.dart';
import 'package:localsend_app/model/dto/info_dto.dart';
import 'package:localsend_app/model/dto/send_request_dto.dart';
-import 'package:localsend_app/model/file_type.dart';
import 'package:localsend_app/model/send/send_state.dart';
import 'package:localsend_app/model/send/sending_file.dart';
import 'package:localsend_app/model/session_status.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/routes.dart';
import 'package:localsend_app/util/api_route_builder.dart';
+import 'package:localsend_app/util/file_path_helper.dart';
import 'package:uuid/uuid.dart';
const _uuid = Uuid();
@@ -49,8 +52,9 @@ class SendNotifier extends StateNotifier<SendState?> {
size: file.size,
fileType: file.name.guessFileType(),
),
- read: () async => file.bytes!,
token: null,
+ path: kIsWeb ? null : file.path,
+ bytes: file.bytes,
),
);
})),
@@ -84,15 +88,16 @@ class SendNotifier extends StateNotifier<SendState?> {
);
final responseMap = response.data as Map;
+ final sendingFiles = {
+ for (final file in requestState.files.values)
+ file.file.id: responseMap.containsKey(file.file.id) ? file.copyWith(token: responseMap[file.file.id]) : file,
+ };
state = requestState.copyWith(
status: SessionStatus.sending,
- files: {
- for (final file in requestState.files.values)
- file.file.id: responseMap.containsKey(file.file.id) ? file.copyWith(token: responseMap[file.file.id]) : file,
- }
+ files: sendingFiles,
);
- print('Response: ${response.statusCode}, ${response.data}, ${response.data.runtimeType}');
+ await _send(target, sendingFiles);
} on DioError catch (e) {
if (e.type != DioErrorType.response && e.type != DioErrorType.cancel) {
print(e);
@@ -103,6 +108,39 @@ class SendNotifier extends StateNotifier<SendState?> {
}
}
+ Future<void> _send(Device target, Map<String, SendingFile> files) async {
+ for (final file in files.values) {
+ final token = file.token;
+ if (token == null) {
+ continue;
+ }
+
+ print('Sending ${file.file.fileName}');
+
+ try {
+ await Dio().post(
+ ApiRoute.send.target(target, query: {
+ 'fileId': file.file.id,
+ 'token': token,
+ }),
+ options: Options(
+ headers: {
+ 'Content-Length': file.file.size,
+ }
+ ),
+ data: file.path != null ? File(file.path!).openRead() : file.bytes!,
+ );
+ } on DioError catch (e) {
+ print(e);
+ }
+ }
+
+ state = state?.copyWith(
+ status: SessionStatus.finished,
+ );
+ print('Files sent successfully.');
+ }
+
Future<void> cancel() async {
final target = state?.target;
if (target == null) {
diff --git a/lib/provider/network/server_provider.dart b/lib/provider/network/server_provider.dart
index 6f0c930a..bc0e4dfd 100644
--- a/lib/provider/network/server_provider.dart
+++ b/lib/provider/network/server_provider.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:localsend_app/main.dart';
import 'package:localsend_app/model/dto/info_dto.dart';
@@ -11,11 +12,14 @@ import 'package:localsend_app/model/server/receiving_file.dart';
import 'package:localsend_app/model/server/server_state.dart';
import 'package:localsend_app/model/session_status.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
+import 'package:localsend_app/provider/progress_provider.dart';
import 'package:localsend_app/routes.dart';
import 'package:localsend_app/service/persistence_service.dart';
import 'package:localsend_app/util/alias_generator.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:localsend_app/util/device_info_helper.dart';
+import 'package:localsend_app/util/file_path_helper.dart';
+import 'package:path_provider/path_provider.dart' as path;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
@@ -24,15 +28,16 @@ import 'package:uuid/uuid.dart';
/// This provider manages receiving file requests.
final serverProvider = StateNotifierProvider<ServerNotifier, ServerState?>((ref) {
final deviceInfo = ref.watch(deviceRawInfoProvider);
- return ServerNotifier(deviceInfo);
+ return ServerNotifier(ref, deviceInfo);
});
const _uuid = Uuid();
class ServerNotifier extends StateNotifier<ServerState?> {
final DeviceInfoResult deviceInfo;
+ final Ref _ref;
- ServerNotifier(this.deviceInfo) : super(null);
+ ServerNotifier(this._ref, this.deviceInfo) : super(null);
Future<ServerState?> startServer({required String alias, required int port}) async {
if (state != null) {
@@ -49,9 +54,47 @@ class ServerNotifier extends StateNotifier<ServerState?> {
port = defaultPort;
}
- final app = Router();
+ final router = Router();
- app.get(ApiRoute.info.path, (Request request) {
+ final String destinationDir;
+ switch (defaultTargetPlatform) {
+ case TargetPlatform.android:
+ destinationDir = '/storage/emulated/0/Download';
+ break;
+ case TargetPlatform.iOS:
+ destinationDir = (await path.getApplicationDocumentsDirectory()).path;
+ break;
+ case TargetPlatform.linux:
+ case TargetPlatform.macOS:
+ case TargetPlatform.windows:
+ case TargetPlatform.fuchsia:
+ destinationDir = (await path.getDownloadsDirectory())!.path;
+ break;
+ }
+
+ print('Destination Directory: $destinationDir');
+ _configureRoutes(router, alias, port, destinationDir);
+
+ print('Starting server...');
+ ServerState? newServerState;
+ try {
+ newServerState = ServerState(
+ httpServer: await serve(router, '0.0.0.0', port),
+ alias: alias,
+ port: port,
+ receiveState: null,
+ );
+ print('Server started. (Port: ${newServerState.port})');
+ } catch (e) {
+ print(e);
+ }
+
+ state = newServerState;
+ return newServerState;
+ }
+
+ void _configureRoutes(Router router, String alias, int port, String tempDir) {
+ router.get(ApiRoute.info.path, (Request request) {
final dto = InfoDto(
alias: alias,
deviceModel: deviceInfo.deviceModel,
@@ -60,20 +103,19 @@ class ServerNotifier extends StateNotifier<ServerState?> {
return Response.ok(jsonEncode(dto.toJson()), headers: {'Content-Type': 'application/json'});
});
- app.post(ApiRoute.sendRequest.path, (Request request) async {
+ router.post(ApiRoute.sendRequest.path, (Request request) async {
if (state!.receiveState != null) {
// block incoming requests when we are already in a session
return Response.badRequest();
}
- final ip = request.context['shelf.io.connection_info'] as HttpConnectionInfo;
final payload = await request.readAsString();
final dto = SendRequestDto.fromJson(jsonDecode(payload));
final streamController = StreamController<bool>();
state = state!.copyWith(
receiveState: ReceiveState(
status: SessionStatus.waiting,
- sender: dto.info.toDevice(ip.remoteAddress.address, port),
+ sender: dto.info.toDevice(request.ip, port),
files: {
for (final file in dto.files.values)
file.id: ReceivingFile(
@@ -101,7 +143,59 @@ class ServerNotifier extends StateNotifier<ServerState?> {
}
});
- app.post(ApiRoute.cancel.path, (Request request) {
+ router.post(ApiRoute.send.path, (Request request) async {
+ final receiveState = state?.receiveState;
+ if (receiveState == null || request.ip != receiveState.sender.ip) {
+ // reject because there is no session or IP does not match session
+ print('No session or wrong IP');
+ return Response.badRequest();
+ }
+
+ final fileId = request.url.queryParameters['fileId'];
+ final token = request.url.queryParameters['token'];
+ if (fileId == null || token == null) {
+ // reject because of missing parameters
+ print('Missing parameters');
+ return Response.badRequest();
+ }
+
+ final receivingFile = receiveState.files[fileId];
+ if (receivingFile == null || receivingFile.token != token) {
+ // reject because there is no file or token does not match
+ print('Wrong token');
+ return Response.badRequest();
+ }
+
+ // begin of actual file transfer
+ String destinationPath = '$tempDir/${receivingFile.file.fileName}';
+ File testFile;
+ int counter = 1;
+ do {
+ destinationPath = counter == 1 ? '$tempDir/${receivingFile.file.fileName}' : '$tempDir/${receivingFile.file.fileName.withCount(counter)}';
+ testFile = File(destinationPath);
+ counter++;
+ } while(await testFile.exists());
+
+ print('Saving ${receivingFile.file.fileName} to $destinationPath');
+
+ final destinationFile = File(destinationPath).openWrite();
+ int currByte = 0;
+ final subscription = request.read().listen((event) {
+ destinationFile.add(event);
+ currByte++;
+ if (currByte % (100 * 1024) == 0 && receivingFile.file.size != 0) {
+ // update progress every 100 KB
+ _ref.read(progressProvider.notifier).setProgress(fileId, currByte / receivingFile.file.size);
+ }
+ });
+ await subscription.asFuture();
+ await destinationFile.close();
+ print('Saved ${receivingFile.file.fileName}.');
+ _ref.read(progressProvider.notifier).setProgress(fileId, 1);
+ return Response.ok('');
+ });
+
+ router.post(ApiRoute.cancel.path, (Request request) {
final ip = request.context['shelf.io.connection_info'] as HttpConnectionInfo;
if (state?.receiveState?.sender.ip == ip.remoteAddress.address) {
@@ -110,23 +204,6 @@ class ServerNotifier extends StateNotifier<ServerState?> {
return Response.ok('');
});
-
- print('Starting server...');
- ServerState? newServerState;
- try {
- newServerState = ServerState(
- httpServer: await serve(app, '0.0.0.0', port),
- alias: alias,
- port: port,
- receiveState: null,
- );
- print('Server started. (Port: ${newServerState.port})');
- } catch (e) {
- print(e);
- }
-
- state = newServerState;
- return newServerState;
}
Future<void> stopServer() async {
@@ -194,3 +271,9 @@ class ServerNotifier extends StateNotifier<ServerState?> {
);
}
}
+
+extension on Request {
+ String get ip {
+ return (context['shelf.io.connection_info'] as HttpConnectionInfo).remoteAddress.address;
+ }
+}
diff --git a/lib/provider/progress_provider.dart b/lib/provider/progress_provider.dart
new file mode 100644
index 00000000..29f2cefa
--- /dev/null
+++ b/lib/provider/progress_provider.dart
@@ -0,0 +1,24 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+/// A provider holding the progress of the send process.
+/// It is implemented as [ChangeNotifier] for performance reasons.
+final progressProvider = ChangeNotifierProvider((ref) => ProgressNotifier());
+
+class ProgressNotifier extends ChangeNotifier {
+ final _progressMap = <String, double>{}; // file id -> 0..1
+
+ void setProgress(String fileId, double progress) {
+ _progressMap[fileId] = progress;
+ notifyListeners();
+ }
+
+ double getProgress(String fileId) {
+ return _progressMap[fileId] ?? 0.0;
+ }
+
+ void reset() {
+ _progressMap.clear();
+ notifyListeners();
+ }
+}
diff --git a/lib/util/api_route_builder.dart b/lib/util/api_route_builder.dart
index b52386b2..5319e070 100644
--- a/lib/util/api_route_builder.dart
+++ b/lib/util/api_route_builder.dart
@@ -15,7 +15,13 @@ enum ApiRoute {
final String path;
/// The client url
- String target(Device target) => 'http://${target.ip}:${target.port}$path';
+ String target(Device target, {Map<String, String>? query}) {
+ if (query != null) {
+ return 'http://${target.ip}:${target.port}$path?${query.entries.map((e) => '${e.key}=${e.value}').join('&')}';
+ } else {
+ return 'http://${target.ip}:${target.port}$path';
+ }
+ }
/// The client url for polling
String targetRaw(String ip, int port) => 'http://$ip:$port$path';
diff --git a/lib/util/file_path_helper.dart b/lib/util/file_path_helper.dart
new file mode 100644
index 00000000..bd80f662
--- /dev/null
+++ b/lib/util/file_path_helper.dart
@@ -0,0 +1,63 @@
+import 'package:localsend_app/model/file_type.dart';
+
+/// Matches myFile-123 -> 123
+final _fileNumberRegex = RegExp(r'^(.*)(?:-(\d+))$');
+
+extension FilePathStringExt on String {
+ String get extension {
+ final index = lastIndexOf('.');
+ if (index != -1) {
+ return substring(index + 1).toLowerCase();
+ } else {
+ return '';
+ }
+ }
+
+ String withExtension(String ext) {
+ if (ext == '') {
+ return this;
+ } else {
+ return '$this.$ext';
+ }
+ }
+
+ String withCount(int count) {
+ final index = lastIndexOf('.');
+ final String fileName;
+ final String extension;
+ if (index != -1) {
+ fileName = substring(0, index);
+ extension = substring(index + 1).toLowerCase();
+ } else {
+ fileName = this;
+ extension = '';
+ }
+
+ final match = _fileNumberRegex.firstMatch(fileName);
+ if (match != null) {
+ return '${match.group(1)}-$count'.withExtension(extension);
+ } else {
+ return '$fileName-$count'.withExtension(extension);
+ }
+ }
+
+ FileType guessFileType() {
+ switch (extension) {
+ case 'jpg':
+ case 'jpeg':
+ case 'png':
+ case 'gif':
+ case 'svg':
+ return FileType.image;
+ case 'mp4':
+ case 'mov':
+ return FileType.video;
+ case 'pdf':
+ return FileType.pdf;
+ case 'txt':
+ return FileType.text;
+ default:
+ return FileType.other;
+ }
+ }
+}
diff --git a/lib/widget/animated_opacity_cross_fade.dart b/lib/widget/animated_opacity_cross_fade.dart
new file mode 100644
index 00000000..cde332ab
--- /dev/null
+++ b/lib/widget/animated_opacity_cross_fade.dart
@@ -0,0 +1,60 @@
+import 'package:flutter/material.dart';
+import 'package:localsend_app/util/sleep.dart';
+
+/// The same as AnimatedCrossFade but with an opacity animation
+class AnimatedOpacityCrossFade extends StatefulWidget {
+ final CrossFadeState crossFadeState;
+ final int durationMillis;
+ final Widget firstChild;
+ final Widget secondChild;
+
+ const AnimatedOpacityCrossFade({
+ required this.crossFadeState,
+ required this.durationMillis,
+ required this.firstChild,
+ required this.secondChild,
+ });
+
+ @override
+ State<AnimatedOpacityCrossFade> createState() => _AnimatedOpacityCrossFadeState();
+}
+
+class _AnimatedOpacityCrossFadeState extends State<AnimatedOpacityCrossFade> {
+ late CrossFadeState _internalState;
+ double _opacity = 1;
+
+ @override
+ void initState() {
+ super.initState();
+ _internalState = widget.crossFadeState;
+ }
+
+ @override
+ void didUpdateWidget(AnimatedOpacityCrossFade oldWidget) {
+ super.didUpdateWidget(oldWidget);
+
+ if (oldWidget.crossFadeState != widget.crossFadeState) {
+ setState(() {
+ _opacity = 0;
+ });
+ final targetState = widget.crossFadeState;
+ sleepAsync(widget.durationMillis).then((_) {
+ if (mounted && targetState == widget.crossFadeState) {
+ setState(() {
+ _internalState = widget.crossFadeState;
+ _opacity = 1;
+ });
+ }
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedOpacity(
+ opacity: _opacity,
+ duration: Duration(milliseconds: widget.durationMillis ~/ 2),
+ child: _internalState == CrossFadeState.showFirst ? widget.firstChild : widget.secondChild,
+ );
+ }
+}
diff --git a/lib/widget/device_list_tile.dart b/lib/widget/device_list_tile.dart
index 1a9c2ac3..80eec853 100644
--- a/lib/widget/device_list_tile.dart
+++ b/lib/widget/device_list_tile.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/device.dart';
import 'package:localsend_app/util/ip_helper.dart';
+import 'package:localsend_app/widget/animated_opacity_cross_fade.dart';
import 'package:localsend_app/widget/device_bage.dart';
class DeviceListTile extends StatelessWidget {
@@ -31,10 +32,9 @@ class DeviceListTile extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FittedBox(
- child: AnimatedCrossFade(
+ child: AnimatedOpacityCrossFade(
crossFadeState: thisDevice ? CrossFadeState.showFirst : CrossFadeState.showSecond,
- alignment: Alignment.topLeft,
- duration: const Duration(milliseconds: 200),
+ durationMillis: 300,
firstChild: Text(t.send.thisDevice, style: const TextStyle(fontSize: 20)),
secondChild: Text(device.alias, style: const TextStyle(fontSize: 20)),
),
diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift
index 2afd909b..20d068b3 100644
--- a/macos/Flutter/GeneratedPluginRegistrant.swift
+++ b/macos/Flutter/GeneratedPluginRegistrant.swift
@@ -8,6 +8,7 @@ import Foundation
import device_info_plus
import network_info_plus
import package_info_plus
+import path_provider_macos
import screen_retriever
import shared_preferences_macos
import window_manager
@@ -16,6 +17,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
NetworkInfoPlusPlugin.register(with: registry.registrar(forPlugin: "NetworkInfoPlusPlugin"))
FLTPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FLTPackageInfoPlusPlugin"))
+ PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
ScreenRetrieverPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin"))
diff --git a/pubspec.lock b/pubspec.lock
index c62f4fe3..b31e2ce8 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -466,6 +466,27 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.2"
+ path_provider:
+ dependency: "direct main"
+ description:
+ name: path_provider
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "2.0.11"
+ path_provider_android:
+ dependency: transitive
+ description:
+ name: path_provider_android
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "2.0.22"
+ path_provider_ios:
+ dependency: transitive
+ description:
+ name: path_provider_ios
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "2.0.11"
path_provider_linux:
dependency: transitive
description:
@@ -473,6 +494,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.7"
+ path_provider_macos:
+ dependency: transitive
+ description:
+ name: path_provider_macos
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "2.0.6"
path_provider_platform_interface:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index b472da5d..34d999a0 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -12,15 +12,16 @@ dependencies:
collection: 1.16.0
device_info_plus: 8.0.0
dio: 4.0.6
+ file_picker: 5.2.4
flutter:
sdk: flutter
- network_info_plus: 3.0.1
- file_picker: 5.2.4
flutter_riverpod: 2.1.1
freezed_annotation: 2.2.0
go_router: 6.0.0
json_annotation: 4.7.0
+ network_info_plus: 3.0.1
package_info_plus: 3.0.2
+ path_provider: 2.0.11
shared_preferences: 2.0.15
shelf: 1.4.0
shelf_router: 1.1.3