diff --git a/caesar-cli/src/cli/args.rs b/caesar-cli/src/cli/args.rs index 56fa0fe..9e48aa7 100644 --- a/caesar-cli/src/cli/args.rs +++ b/caesar-cli/src/cli/args.rs @@ -79,7 +79,12 @@ impl Args { name, }) => { println!("Receive for {name:?}"); - receiver::start_receiver(relay.as_deref().unwrap_or(&cfg.app_origin), name).await; + receiver::start_receiver( + ".".to_string(), + relay.as_deref().unwrap_or(&cfg.app_origin), + name, + ) + .await; } Some(Commands::Serve { port, diff --git a/caesar-core/src/receiver/client.rs b/caesar-core/src/receiver/client.rs index d572173..18ea827 100644 --- a/caesar-core/src/receiver/client.rs +++ b/caesar-core/src/receiver/client.rs @@ -22,9 +22,6 @@ use tracing::error; const DESTINATION: u8 = 0; const NONCE_SIZE: usize = 12; -#[cfg(target_os = "android")] -const FILE_PATH_PREFIX: &str = "/storage/emulated/0/Documents"; - struct File { name: String, size: u64, @@ -69,28 +66,18 @@ fn on_leave_room(context: &mut Context, _: usize) -> Status { } } -fn on_list(context: &mut Context, list: ListPacket) -> Status { +fn on_list(filepath: String, context: &mut Context, list: ListPacket) -> Status { if context.shared_key.is_none() { return Status::Err("Invalid list packet: no shared key established".into()); } - #[cfg(target_os = "android")] - let mut prefix = std::path::PathBuf::from(std::env::current_exe().unwrap()); - // #[cfg(target_os = "android")] - // prefix.pop(); - // #[cfg(target_os = "android")] - // println!("prefix: {:?}", prefix); for entry in list.entries { let path = sanitize_filename::sanitize(entry.name.clone()); - #[cfg(target_os = "android")] - let file_path = format!("{}/{}", FILE_PATH_PREFIX, path); - // let file_path = format!("{}/{}", prefix.display(), path); + let file_path = format!("{}/{}", filepath, path); - #[cfg(target_os = "android")] if Path::new(&file_path).exists() { return Status::Err(format!("The file '{}' already exists.", path)); } - #[cfg(target_os = "android")] let handle = match fs::File::create(&file_path) { Ok(handle) => handle, Err(error) => { @@ -100,21 +87,6 @@ fn on_list(context: &mut Context, list: ListPacket) -> Status { )); } }; - #[cfg(not(target_os = "android"))] - if Path::new(&path).exists() { - return Status::Err(format!("The file '{}' already exists.", path)); - } - - #[cfg(not(target_os = "android"))] - let handle = match fs::File::create(&path) { - Ok(handle) => handle, - Err(error) => { - return Status::Err(format!( - "Error: Failed to create file '{}': {}", - path, error - )); - } - }; let file = File { name: entry.name, @@ -232,7 +204,7 @@ fn on_handshake(context: &mut Context, handshake: HandshakePacket) -> Status { Status::Continue() } -fn on_message(context: &mut Context, message: WebSocketMessage) -> Status { +fn on_message(filepath: String, context: &mut Context, message: WebSocketMessage) -> Status { match message.clone() { WebSocketMessage::Text(text) => { let packet = match serde_json::from_str(&text) { @@ -263,7 +235,7 @@ fn on_message(context: &mut Context, message: WebSocketMessage) -> Status { let packet = Packet::decode(data.as_ref()).unwrap(); let value = packet.value.unwrap(); return match value { - Value::List(list) => on_list(context, list), + Value::List(list) => on_list(filepath, context, list), Value::Chunk(chunk) => on_chunk(context, chunk), Value::Handshake(handshake) => on_handshake(context, handshake), _ => Status::Err(format!("Unexpected packet: {:?}", value)), @@ -275,7 +247,7 @@ fn on_message(context: &mut Context, message: WebSocketMessage) -> Status { Status::Err("Invalid message type".into()) } -pub async fn start(socket: Socket, fragment: &str) { +pub async fn start(filepath: String, socket: Socket, fragment: &str) { let Some(index) = fragment.rfind('-') else { println!("Error: The invite code '{}' is not valid.", fragment); return; @@ -316,7 +288,7 @@ pub async fn start(socket: Socket, fragment: &str) { let outgoing_handler = receiver.stream().map(Ok).forward(outgoing); let incoming_handler = incoming.try_for_each(|message| { - match on_message(&mut context, message) { + match on_message(filepath.clone(), &mut context, message) { Status::Exit() => { context.sender.send_json_packet(JsonPacket::Leave); println!("Transfer has completed."); @@ -338,6 +310,7 @@ pub async fn start(socket: Socket, fragment: &str) { future::select(incoming_handler, outgoing_handler).await; } + #[cfg(test)] mod tests { use super::*; @@ -412,58 +385,15 @@ mod tests { }; let text_message = WebSocketMessage::Text(r#"{"type":"join","size":10}"#.to_string()); - assert_eq!(on_message(&mut context, text_message), Status::Continue()); + assert_eq!( + on_message("".to_string(), &mut context, text_message), + Status::Continue() + ); } #[test] fn test_on_chunk() { let (sender, _) = flume::bounded(1000); - // let mut context = Context { - // hmac: vec![], - // sender: sender.clone(), - // key: EphemeralSecret::random(&mut OsRng), - // shared_key: Some(Aes128Gcm::new(Key::::from_slice(&[0u8; 16]))), - // files: vec![File { - // name: "file1.txt".to_string(), - // size: 100, - // progress: 0, - // handle: fs::File::create("file1.txt").unwrap(), - // }], - // sequence: 0, - // index: 0, - // progress: 0, - // length: 0, - // }; - - // let chunk_packet = ChunkPacket { - // sequence: 0, - // chunk: b"Hello, world!".to_vec(), - // }; - // assert_eq!(on_chunk(&mut context, chunk_packet), Status::Continue()); - // assert_eq!(context.sequence, 1); - // assert_eq!(context.length, 14); - // assert_eq!(context.progress, 14); - - // let chunk_packet = ChunkPacket { - // sequence: 1, - // chunk: b"Hello, world!".to_vec(), - // }; - // assert_eq!( - // on_chunk(&mut context, chunk_packet), - // Status::Err("Expected sequence 1, but got 1.".into()) - // ); - - // context.files.clear(); - // let chunk_packet = ChunkPacket { - // sequence: 0, - // chunk: b"Hello, world!".to_vec(), - // }; - // assert_eq!( - // on_chunk(&mut context, chunk_packet), - // Status::Err("Invalid file index.".into()) - // ); - - // Test a chunk packet with no shared key let mut context = Context { hmac: vec![], sender, diff --git a/caesar-core/src/receiver/mod.rs b/caesar-core/src/receiver/mod.rs index 74acadd..64b5341 100644 --- a/caesar-core/src/receiver/mod.rs +++ b/caesar-core/src/receiver/mod.rs @@ -10,7 +10,7 @@ use tokio_tungstenite::{ }; use tracing::{debug, error}; -pub async fn start_receiver(relay: &str, name: &str) -> Result<()> { +pub async fn start_receiver(filepath: String, relay: &str, name: &str) -> Result<()> { let http_url = replace_protocol(relay); let res = http_client::download_info(http_url.as_str(), name) .await @@ -18,12 +18,24 @@ pub async fn start_receiver(relay: &str, name: &str) -> Result<()> { debug!("Got room_id from Server: {:?}", res); let res_ip = String::from("ws://") + res.ip.as_str() + ":9000"; - if let Err(local_err) = start_ws_com(res_ip.as_str(), res.local_room_id.as_str()).await { + #[cfg(not(target_os = "android"))] + if let Err(local_err) = start_ws_com( + filepath.clone(), + res_ip.as_str(), + res.local_room_id.as_str(), + ) + .await + { debug!("Failed to connect local: {local_err}"); - if let Err(relay_err) = start_ws_com(relay, res.relay_room_id.as_str()).await { + if let Err(relay_err) = start_ws_com(filepath, relay, res.relay_room_id.as_str()).await { debug!("Failed to connect remote: {relay_err}"); } } + + #[cfg(target_os = "android")] + if let Err(relay_err) = start_ws_com(filepath, relay, res.relay_room_id.as_str()).await { + debug!("Failed to connect remote: {relay_err}"); + } let _success = http_client::download_success(http_url.as_str(), name) .await .map_err(|e| anyhow!("Failed to download success: {}", e))?; @@ -32,7 +44,7 @@ pub async fn start_receiver(relay: &str, name: &str) -> Result<()> { Ok(()) } -pub async fn start_ws_com(relay: &str, name: &str) -> Result<()> { +pub async fn start_ws_com(filepath: String, relay: &str, name: &str) -> Result<()> { let url = String::from(relay) + "/ws"; let mut request = url .into_client_request() @@ -48,7 +60,7 @@ pub async fn start_ws_com(relay: &str, name: &str) -> Result<()> { .await { Ok(Ok((socket, _))) => { - receiver::start(socket, name).await; + receiver::start(filepath, socket, name).await; Ok(()) } Ok(Err(e)) => { diff --git a/flutter_test_gui/lib/consts/consts.dart b/flutter_test_gui/lib/consts/consts.dart index a18dd10..f0f9e16 100644 --- a/flutter_test_gui/lib/consts/consts.dart +++ b/flutter_test_gui/lib/consts/consts.dart @@ -1,7 +1,11 @@ import 'package:flutter/material.dart'; class Constants { - static const backColor = Color(0xFF32363E); - static const highlightColor = Color(0xFF98C379); - static const textColor = Color(0xFFABB2BF); + static const backColor = Color(0xFF303446); + static const highlightColor = Color(0xFF8caaee); + static const textColor = Color(0xFFc6d0f5); + // static const backColor = Color(0xFF32363E); + // static const highlightColor = Color(0xFF98C379); + // static const highlightColor = Color(0xFFa6d189); + // static const textColor = Color(0xFFABB2BF); } diff --git a/flutter_test_gui/lib/main.dart b/flutter_test_gui/lib/main.dart index c56714f..3f17f5a 100644 --- a/flutter_test_gui/lib/main.dart +++ b/flutter_test_gui/lib/main.dart @@ -6,6 +6,7 @@ import 'package:bitsdojo_window/bitsdojo_window.dart'; import 'package:flutter_test_gui/pages/settings_screen.dart'; import 'package:flutter_test_gui/pages/send_screen.dart'; import 'package:flutter_test_gui/pages/receive_screen.dart'; +import 'package:flutter_test_gui/consts/consts.dart'; Future main() async { await RustLib.init(); @@ -23,9 +24,9 @@ Future main() async { } } -const backColor = Color(0xFF32363E); -const highlightColor = Color(0xFF98C379); -const textColor = Color(0xFFABB2BF); +// const backColor = Color(0xFF32363E); +// const highlightColor = Color(0xFF98C379); +// const textColor = Color(0xFFABB2BF); class MyApp extends StatefulWidget { const MyApp({super.key}); @@ -73,13 +74,13 @@ class _MyHomePageState extends State { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( - backgroundColor: backColor, + backgroundColor: Constants.backColor, appBar: AppBar( - backgroundColor: const Color(0xFF282C34), + backgroundColor: const Color(0xFF292c3c), //0xFF282C34), centerTitle: true, title: Text( widget.title, - style: const TextStyle(color: textColor), + style: const TextStyle(color: Constants.textColor), ), actions: [ PopupMenuButton( @@ -102,7 +103,7 @@ class _MyHomePageState extends State { ), body: _screens[_selectedIndex], bottomNavigationBar: BottomNavigationBar( - backgroundColor: const Color(0xFF282C34), + backgroundColor: const Color(0xFF292c3c), //0xFF282C34), items: const [ BottomNavigationBarItem( icon: Icon(Icons.send), @@ -114,8 +115,8 @@ class _MyHomePageState extends State { ), ], currentIndex: _selectedIndex, - selectedItemColor: highlightColor, - unselectedItemColor: textColor, + selectedItemColor: Constants.highlightColor, + unselectedItemColor: Constants.textColor, onTap: _onItemTapped, ), ), diff --git a/flutter_test_gui/lib/pages/receive_screen.dart b/flutter_test_gui/lib/pages/receive_screen.dart index 3e763ed..b3e895c 100644 --- a/flutter_test_gui/lib/pages/receive_screen.dart +++ b/flutter_test_gui/lib/pages/receive_screen.dart @@ -1,5 +1,6 @@ import 'dart:io'; +import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test_gui/main.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; @@ -31,7 +32,8 @@ class ReceiveScreenState extends State { if (barcode.raw == null) { debugPrint('Failed to scan qr code'); } else { - final String code = barcode.raw.toString(); + final String code = barcode.barcodes.first.displayValue.toString(); + print(code); setState(() { inputValue = code; _showScanner = false; @@ -69,12 +71,20 @@ class ReceiveScreenState extends State { Future _startTransfer(String appOrigin) async { final input = inputValue.trim(); + String filePath = ''; if (input.isNotEmpty) { + String? selectDirectory = await FilePicker.platform.getDirectoryPath(); + if (selectDirectory == null) { + print("User doesnt choose a directory"); + } else { + print("user choose: $selectDirectory"); + filePath = selectDirectory; + } if (Platform.isAndroid) { if (await _requestPermission(Permission.manageExternalStorage)) { try { - final outcome = - await startRustReceiver(transfername: input, relay: appOrigin); + final outcome = await startRustReceiver( + filepath: filePath, transfername: input, relay: appOrigin); print('Ergebnis von Rust: $outcome'); } catch (e) { print('Fehler beim Starten des Receivers: $e'); @@ -93,8 +103,8 @@ class ReceiveScreenState extends State { } } else { try { - final outcome = - await startRustReceiver(transfername: input, relay: appOrigin); + final outcome = await startRustReceiver( + filepath: filePath, transfername: input, relay: appOrigin); print('Ergebnis von Rust: $outcome'); } catch (e) { print('Fehler beim Starten des Receivers: $e'); @@ -112,7 +122,7 @@ class ReceiveScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: backColor, + backgroundColor: Constants.backColor, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/flutter_test_gui/lib/pages/transfer_screen.dart b/flutter_test_gui/lib/pages/transfer_screen.dart index 3e204d7..4862e77 100644 --- a/flutter_test_gui/lib/pages/transfer_screen.dart +++ b/flutter_test_gui/lib/pages/transfer_screen.dart @@ -58,9 +58,9 @@ class TransferScreenState extends State { // } else {} // } else { try { - final outcome = - await startRustReceiver(transfername: input, relay: appOrigin); - print('Ergebnis von Rust: $outcome'); + // final outcome = + // await startRustReceiver(transfername: input, relay: appOrigin); + // print('Ergebnis von Rust: $outcome'); } catch (e) { print('Fehler beim Starten des Receivers: $e'); } diff --git a/flutter_test_gui/lib/src/rust/api/simple.dart b/flutter_test_gui/lib/src/rust/api/simple.dart index 53e3e2a..520d23f 100644 --- a/flutter_test_gui/lib/src/rust/api/simple.dart +++ b/flutter_test_gui/lib/src/rust/api/simple.dart @@ -18,6 +18,12 @@ Future startRustSender( .startRustSender(name: name, relay: relay, files: files, hint: hint); Future startRustReceiver( - {required String relay, required String transfername, dynamic hint}) => + {required String filepath, + required String relay, + required String transfername, + dynamic hint}) => RustLib.instance.api.startRustReceiver( - relay: relay, transfername: transfername, hint: hint); + filepath: filepath, + relay: relay, + transfername: transfername, + hint: hint); diff --git a/flutter_test_gui/lib/src/rust/frb_generated.dart b/flutter_test_gui/lib/src/rust/frb_generated.dart index f1a4cdd..e72d048 100644 --- a/flutter_test_gui/lib/src/rust/frb_generated.dart +++ b/flutter_test_gui/lib/src/rust/frb_generated.dart @@ -72,7 +72,10 @@ abstract class RustLibApi extends BaseApi { Future initApp({dynamic hint}); Future startRustReceiver( - {required String relay, required String transfername, dynamic hint}); + {required String filepath, + required String relay, + required String transfername, + dynamic hint}); Future startRustSender( {required String name, @@ -138,10 +141,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @override Future startRustReceiver( - {required String relay, required String transfername, dynamic hint}) { + {required String filepath, + required String relay, + required String transfername, + dynamic hint}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(filepath, serializer); sse_encode_String(relay, serializer); sse_encode_String(transfername, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, @@ -152,7 +159,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { decodeErrorData: sse_decode_AnyhowException, ), constMeta: kStartRustReceiverConstMeta, - argValues: [relay, transfername], + argValues: [filepath, relay, transfername], apiImpl: this, hint: hint, )); @@ -160,7 +167,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { TaskConstMeta get kStartRustReceiverConstMeta => const TaskConstMeta( debugName: "start_rust_receiver", - argNames: ["relay", "transfername"], + argNames: ["filepath", "relay", "transfername"], ); @override diff --git a/flutter_test_gui/pubspec.yaml b/flutter_test_gui/pubspec.yaml index aa5de8e..014686b 100644 --- a/flutter_test_gui/pubspec.yaml +++ b/flutter_test_gui/pubspec.yaml @@ -1,32 +1,12 @@ name: flutter_test_gui description: "A new Flutter project." -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: "none" # Remove this line if you wish to publish to pub.dev +publish_to: "none" -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# In Android, build-name is used as versionName while build-number used as versionCode. -# Read more about Android versioning at https://developer.android.com/studio/publish/versioning -# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -# In Windows, build-name is used as the major, minor, and patch parts -# of the product and file versions while build-number is used as the build suffix. version: 1.0.0+1 environment: sdk: ">=3.3.4 <4.0.0" -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. dependencies: flutter: sdk: flutter @@ -39,66 +19,19 @@ dependencies: desktop_drop: ^0.4.4 shared_preferences: ^2.2.3 - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.6 rust_lib_flutter_test_gui: path: rust_builder flutter_rust_bridge: 2.0.0-dev.33 - # dio: ^5.4.3+1 - # path_provider: ^2.1.3 permission_handler: ^11.3.1 dev_dependencies: flutter_test: sdk: flutter - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. flutter_lints: ^3.0.0 integration_test: sdk: flutter -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. flutter: - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/flutter_test_lib/src/api/simple.rs b/flutter_test_lib/src/api/simple.rs index 261e5a1..83ec16e 100644 --- a/flutter_test_lib/src/api/simple.rs +++ b/flutter_test_lib/src/api/simple.rs @@ -46,19 +46,20 @@ pub async fn start_rust_sender(name: String, relay: String, files: Vec) Ok(()) } -// #[flutter_rust_bridge::frb(sync)] -// pub async fn start_rust_receiver(relay: String, transfername: String) -> Result<()> { -// let outcome = start_receiver(relay.as_str(), transfername.as_str()) -// .await -// .map_err(|e| anyhow!("Failed to start Caesar receiver: {}", e))?; -// println!("Result of receiver is: {:?}", outcome); -// Ok(()) -// } -pub async fn start_rust_receiver(relay: String, transfername: String) -> Result { - let outcome = start_receiver(relay.as_str(), transfername.as_str()) +pub async fn start_rust_receiver( + filepath: String, + relay: String, + transfername: String, +) -> Result { + // #[cfg(target_os = "android")] + let outcome = start_receiver(filepath, relay.as_str(), transfername.as_str()) .await .map_err(|e| anyhow!("Failed to start Caesar receiver: {}", e))?; + // #[cfg(not(target_os = "android"))] + // let outcome = start_receiver(relay.as_str(), transfername.as_str()) + // .await + // .map_err(|e| anyhow!("Failed to start Caesar receiver: {}", e))?; // Konvertieren Sie outcome zu einem String let outcome_string = format!("{:?}", outcome); diff --git a/flutter_test_lib/src/frb_generated.rs b/flutter_test_lib/src/frb_generated.rs index 97fdbc5..657d922 100644 --- a/flutter_test_lib/src/frb_generated.rs +++ b/flutter_test_lib/src/frb_generated.rs @@ -120,13 +120,19 @@ fn wire_start_rust_receiver_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_filepath = ::sse_decode(&mut deserializer); let api_relay = ::sse_decode(&mut deserializer); let api_transfername = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse( (move || async move { - crate::api::simple::start_rust_receiver(api_relay, api_transfername).await + crate::api::simple::start_rust_receiver( + api_filepath, + api_relay, + api_transfername, + ) + .await })() .await, )