Skip to content

Commit

Permalink
* Added Test version
Browse files Browse the repository at this point in the history
  • Loading branch information
alvinosh committed May 31, 2024
1 parent 72b1d55 commit 5eb7e1e
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 60 deletions.
65 changes: 65 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ futures-lite = "2.3.0"
futures-buffered = "0.2.6"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
dirs = "5.0.1"
open = "5.1.3"

[features]
# this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled.
Expand Down
68 changes: 46 additions & 22 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,24 @@ use iroh::{
};
use iroh_base::ticket::BlobTicket;
use iroh_blobs::{util::SetTagOption, BlobFormat};
use rand::Rng;
use serde::Serialize;
use tauri::{InvokeError, Manager};
use walkdir::WalkDir;

struct AppState {
pub iroh: Node<iroh_blobs::store::fs::Store>,
pub iroh: Node<iroh_blobs::store::mem::Store>,
}

impl AppState {
fn new(iroh: Node<iroh_blobs::store::fs::Store>) -> Self {
fn new(iroh: Node<iroh_blobs::store::mem::Store>) -> Self {
AppState { iroh }
}
}

async fn setup<R: tauri::Runtime>(handle: tauri::AppHandle<R>) -> Result<()> {
let suffix = rand::thread_rng().gen::<[u8; 16]>();
let iroh_data_dir =
std::env::current_dir()?.join(format!(".ark-drop-data-{}", hex::encode(suffix)));

// create the iroh node
let node = iroh::node::Node::persistent(iroh_data_dir)
.await?
.spawn()
.await?;
let node = iroh::node::Node::memory().spawn().await?;

handle.manage(AppState::new(node));

Ok(())
Expand All @@ -46,21 +40,24 @@ fn main() {
let handle = app.handle();

tauri::async_runtime::spawn(async move {
println!("starting backend...");
if let Err(err) = setup(handle).await {
eprintln!("failed: {:?}", err);
}
});

Ok(())
})
.invoke_handler(tauri::generate_handler![generate_ticket, recieve_files])
.invoke_handler(tauri::generate_handler![
generate_ticket,
recieve_files,
open_file
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

async fn create_file_collection(
db: &Node<iroh_blobs::store::fs::Store>,
db: &Node<iroh_blobs::store::mem::Store>,
path: &PathBuf,
) -> Result<Vec<(PathBuf, AddOutcome)>> {
try_join_all(
Expand Down Expand Up @@ -104,8 +101,7 @@ async fn generate_ticket(
let collection = outcome
.into_iter()
.map(|(path, outcome)| {
// not sure if unwrap is safe here
let name = path.into_os_string().into_string().unwrap();
let name = path.file_name().unwrap().to_string_lossy().to_string();
let hash = outcome.hash;
return (name, hash);
})
Expand All @@ -123,19 +119,30 @@ async fn generate_ticket(
.map_err(InvokeError::from_anyhow)
}

#[derive(Serialize)]
struct FileInfo {
pub path: PathBuf,
pub name: String,
pub size: u64,
}

#[derive(Serialize)]
struct RecieveFilesResponse {
pub files: Vec<FileInfo>,
pub downloaded_size: u64,
}

#[tauri::command]
async fn recieve_files(
state: tauri::State<'_, AppState>,
ticket: String,
) -> Result<(), InvokeError> {
) -> Result<RecieveFilesResponse, InvokeError> {
let node = &state.iroh;

let ticket = BlobTicket::from_str(&ticket)
.map_err(|e| InvokeError::from_anyhow(anyhow::anyhow!("failed to parse ticket: {}", e)))?;

let addrs: iroh_net::NodeAddr = node.my_addr().await.map_err(InvokeError::from_anyhow)?;

if (ticket.format() != BlobFormat::HashSeq) {
if ticket.format() != BlobFormat::HashSeq {
return Err(InvokeError::from_anyhow(anyhow::anyhow!(
"unsupported format: {:?}",
ticket.format()
Expand All @@ -160,6 +167,8 @@ async fn recieve_files(
.context("expect hash with `BlobFormat::HashSeq` to be a collection")
.map_err(InvokeError::from_anyhow)?;

let mut files: Vec<FileInfo> = Vec::new();

for (name, hash) in collection.iter() {
let content = node
.blobs
Expand All @@ -169,7 +178,7 @@ async fn recieve_files(

let path = PathBuf::from(name);

let file_path = std::env::current_dir()
let file_path = dirs::desktop_dir()
.context("failed to get current directory")
.map_err(InvokeError::from_anyhow)?
.join(
Expand All @@ -178,10 +187,25 @@ async fn recieve_files(
.map_err(InvokeError::from_anyhow)?,
);

files.push(FileInfo {
path: file_path.clone(),
name: name.clone(),
size: content.len() as u64,
});

std::fs::write(&file_path, content)
.context("failed to write file")
.map_err(InvokeError::from_anyhow)?;
}

Ok(())
Ok(RecieveFilesResponse {
files,
downloaded_size: outcome.downloaded_size,
})
}

#[tauri::command]
fn open_file(file: PathBuf) -> Result<(), InvokeError> {
open::that(file)
.map_err(|e| InvokeError::from_anyhow(anyhow::anyhow!("failed to open file: {}", e)))
}
26 changes: 6 additions & 20 deletions src/lib/components/FileTransfer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import { formatBytes, formatTime } from '$lib/util';
import FileUploaded from './FileUploaded.svelte';
let file = 'Img 2718. JPG';
let transferedSize = 1_500_000; // bytes
let fileSize = 4_700_000; // bytes
export let fileName = 'Img 2718. JPG';
export let transferedSize = 1_500_000; // bytes
export let fileSize = 4_700_000; // bytes
let internetSpeed = 1_000_000; // bytes/s
let timeLeft = (fileSize - transferedSize) / internetSpeed; // seconds
Expand All @@ -20,20 +20,6 @@
const dispatch = createEventDispatcher();
onMount(() => {
const updateSpeed = 10;
const interval = setInterval(() => {
transferedSize += internetSpeed / updateSpeed;
timeLeft = (fileSize - transferedSize) / internetSpeed;
if (transferedSize >= fileSize) {
clearInterval(interval);
dispatch('done');
}
}, 1000 / updateSpeed);
return () => clearInterval(interval);
});
let openModal = false;
</script>

Expand All @@ -44,7 +30,7 @@
<FileType />
</div>
<div class="flex flex-1 flex-col justify-between py-1">
<span class="text-sm font-medium text-gray-modern-900">{file}</span>
<span class="text-sm font-medium text-gray-modern-900">{fileName}</span>
<p class="flex flex-row items-center gap-1 text-xs text-gray-modern-500">
{formatBytes(transferedSize)} of {formatBytes(fileSize)}
<svg
Expand Down Expand Up @@ -82,7 +68,7 @@
{:else}
<FileUploaded
fileUploaded={{
fileName: file,
fileName: fileName,
fileSize: fileSize,
recipient: 'Aurora',
sentAt: new Date()
Expand All @@ -107,7 +93,7 @@
<FileType />
</div>
<div class="flex flex-1 flex-col justify-between py-1">
<span class="text-sm font-medium text-gray-modern-900">{file}</span>
<span class="text-sm font-medium text-gray-modern-900">{fileName}</span>
<p class="flex flex-row items-center gap-1 text-xs text-gray-modern-500">
{formatBytes(fileSize)}
</p>
Expand Down
4 changes: 1 addition & 3 deletions src/routes/transfers/recieve/confirm/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@
{code}
on:click={async () => {
if (code === data.confirmationCode) {
await invoke('recieve_files', {
ticket: data.hash
});
goto('/transfers/transferring?ticket=' + data.hash);
} else {
goto('/transfers/failed');
}
Expand Down
Loading

0 comments on commit 5eb7e1e

Please sign in to comment.