feat: Desktop Sync Client (Tauri) - Grundgeruest

Tauri 2 Desktop-Client mit:

Rust-Backend:
- MiniCloudApi: Login, Token-Refresh, Upload, Download, Sync-Tree,
  Sync-Changes, File-Locking (Lock/Unlock/Heartbeat)
- SyncEngine: Full-Sync (Server-Tree vs. lokales Dateisystem),
  Delta-Sync (nur Aenderungen seit letztem Sync), bidirektionaler
  Abgleich mit SHA-256 Checksummen, Ordner-Erstellung,
  Lock-Status-Pruefung vor Upload, Konflikt-Erkennung
- FileWatcher: Filesystem-Watcher (notify crate) fuer Echtzeit-
  Erkennung lokaler Aenderungen, filtert temp/hidden files

Vue-Frontend:
- Login-Screen: Server-URL, Benutzername, Passwort
- Main-Screen: Sync-Ordner setzen, Sync starten, Dateiliste mit
  Lock-Status, Sync-Protokoll
- Dark-Mode Support

Tauri-Kommandos: login, set_sync_dir, start_sync, delta_sync,
  get_status, get_file_tree

Zum Bauen (Linux):
  sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev
  cd clients/desktop && npm install && npm run tauri build

Windows/Mac: Tauri Voraussetzungen installieren, dann gleicher Befehl

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Stefan Hacker 2026-04-11 23:26:57 +02:00
parent 748537b9f5
commit 06ad65dbb3
39 changed files with 8735 additions and 0 deletions

24
clients/desktop/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,7 @@
# Tauri + Vue 3
This template should help get you started developing with Tauri + Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + Vue 3 App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

1563
clients/desktop/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
{
"name": "tauri-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"vue": "^3.5.13",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.1",
"vite": "^6.0.3",
"@tauri-apps/cli": "^2"
}
}

View File

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

7
clients/desktop/src-tauri/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

6111
clients/desktop/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
[package]
name = "minicloud-sync"
version = "0.1.0"
description = "Mini-Cloud Desktop Sync Client"
authors = ["Mini-Cloud"]
edition = "2021"
[lib]
name = "minicloud_sync_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
tauri-plugin-notification = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", features = ["json", "multipart", "rustls-tls"], default-features = false }
tokio = { version = "1", features = ["full"] }
notify = "7"
sha2 = "0.10"
dirs = "6"
rusqlite = { version = "0.34", features = ["bundled"] }
chrono = { version = "0.4", features = ["serde"] }
keyring = "3"

View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,108 @@
mod sync;
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::State;
use sync::api::MiniCloudApi;
use sync::engine::SyncEngine;
struct AppState {
api: Mutex<Option<MiniCloudApi>>,
sync_engine: Mutex<Option<SyncEngine>>,
sync_dir: Mutex<Option<PathBuf>>,
username: Mutex<Option<String>>,
}
#[tauri::command]
async fn login(
state: State<'_, AppState>,
server_url: String,
username: String,
password: String,
) -> Result<serde_json::Value, String> {
let mut api = MiniCloudApi::new(&server_url);
let result = api.login(&username, &password).await?;
*state.api.lock().unwrap() = Some(api);
*state.username.lock().unwrap() = Some(username);
Ok(serde_json::json!({
"username": result.user.username,
"role": result.user.role,
}))
}
#[tauri::command]
fn set_sync_dir(state: State<'_, AppState>, path: String) -> Result<String, String> {
let sync_path = PathBuf::from(&path);
if !sync_path.exists() {
std::fs::create_dir_all(&sync_path).map_err(|e| e.to_string())?;
}
*state.sync_dir.lock().unwrap() = Some(sync_path);
Ok(format!("Sync-Ordner gesetzt: {}", path))
}
#[tauri::command]
async fn start_sync(state: State<'_, AppState>) -> Result<Vec<String>, String> {
let api = state.api.lock().unwrap().clone()
.ok_or("Nicht eingeloggt")?;
let sync_dir = state.sync_dir.lock().unwrap().clone()
.ok_or("Kein Sync-Ordner gesetzt")?;
let mut engine = SyncEngine::new(sync_dir, api);
let log = engine.full_sync().await?;
*state.sync_engine.lock().unwrap() = Some(engine);
Ok(log)
}
#[tauri::command]
async fn delta_sync(state: State<'_, AppState>) -> Result<Vec<String>, String> {
let mut engine_guard = state.sync_engine.lock().unwrap();
let engine = engine_guard.as_mut().ok_or("Sync nicht gestartet")?;
engine.delta_sync().await
}
#[tauri::command]
async fn get_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let logged_in = state.api.lock().unwrap().is_some();
let sync_dir = state.sync_dir.lock().unwrap().clone();
let username = state.username.lock().unwrap().clone();
Ok(serde_json::json!({
"logged_in": logged_in,
"username": username,
"sync_dir": sync_dir.map(|p| p.to_string_lossy().to_string()),
}))
}
#[tauri::command]
async fn get_file_tree(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let api = state.api.lock().unwrap().clone()
.ok_or("Nicht eingeloggt")?;
let tree = api.get_sync_tree().await?;
Ok(serde_json::to_value(tree).map_err(|e| e.to_string())?)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.manage(AppState {
api: Mutex::new(None),
sync_engine: Mutex::new(None),
sync_dir: Mutex::new(None),
username: Mutex::new(None),
})
.invoke_handler(tauri::generate_handler![
login,
set_sync_dir,
start_sync,
delta_sync,
get_status,
get_file_tree,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
tauri_app_lib::run()
}

View File

@ -0,0 +1,250 @@
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Clone)]
pub struct MiniCloudApi {
client: Client,
pub server_url: String,
pub access_token: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LoginResponse {
pub access_token: String,
pub user: UserInfo,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserInfo {
pub id: i64,
pub username: String,
pub role: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FileEntry {
pub id: i64,
pub name: String,
pub is_folder: bool,
pub size: Option<i64>,
pub checksum: Option<String>,
pub updated_at: Option<String>,
pub children: Option<Vec<FileEntry>>,
pub locked: Option<bool>,
pub locked_by: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SyncTreeResponse {
pub tree: Vec<FileEntry>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SyncChangesResponse {
pub changes: Vec<FileEntry>,
pub server_time: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LockResponse {
pub locked: Option<bool>,
pub locked_by: Option<String>,
pub error: Option<String>,
}
impl MiniCloudApi {
pub fn new(server_url: &str) -> Self {
Self {
client: Client::builder()
.danger_accept_invalid_certs(false)
.build()
.unwrap(),
server_url: server_url.trim_end_matches('/').to_string(),
access_token: String::new(),
}
}
fn auth_header(&self) -> String {
format!("Bearer {}", self.access_token)
}
pub async fn login(&mut self, username: &str, password: &str) -> Result<LoginResponse, String> {
let url = format!("{}/api/auth/login", self.server_url);
let body = serde_json::json!({
"username": username,
"password": password,
});
let resp = self.client.post(&url)
.json(&body)
.send()
.await
.map_err(|e| format!("Verbindungsfehler: {}", e))?;
if !resp.status().is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(format!("Login fehlgeschlagen: {}", text));
}
let data: LoginResponse = resp.json().await
.map_err(|e| format!("Antwort-Fehler: {}", e))?;
self.access_token = data.access_token.clone();
Ok(data)
}
pub async fn refresh_token(&mut self) -> Result<String, String> {
let url = format!("{}/api/auth/refresh", self.server_url);
let resp = self.client.post(&url)
.header("Authorization", self.auth_header())
.send()
.await
.map_err(|e| format!("Refresh fehlgeschlagen: {}", e))?;
if !resp.status().is_success() {
return Err("Token-Refresh fehlgeschlagen".to_string());
}
let data: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
if let Some(token) = data.get("access_token").and_then(|t| t.as_str()) {
self.access_token = token.to_string();
Ok(token.to_string())
} else {
Err("Kein Token in Antwort".to_string())
}
}
pub async fn get_sync_tree(&self) -> Result<Vec<FileEntry>, String> {
let url = format!("{}/api/sync/tree", self.server_url);
let resp = self.client.get(&url)
.header("Authorization", self.auth_header())
.send()
.await
.map_err(|e| format!("Sync-Tree Fehler: {}", e))?;
let data: SyncTreeResponse = resp.json().await
.map_err(|e| format!("Parse-Fehler: {}", e))?;
Ok(data.tree)
}
pub async fn get_changes(&self, since: &str) -> Result<SyncChangesResponse, String> {
let url = format!("{}/api/sync/changes?since={}", self.server_url, since);
let resp = self.client.get(&url)
.header("Authorization", self.auth_header())
.send()
.await
.map_err(|e| format!("Changes Fehler: {}", e))?;
resp.json().await.map_err(|e| format!("Parse-Fehler: {}", e))
}
pub async fn download_file(&self, file_id: i64, dest: &Path) -> Result<(), String> {
let url = format!("{}/api/files/{}/download?token={}",
self.server_url, file_id, self.access_token);
let resp = self.client.get(&url)
.send()
.await
.map_err(|e| format!("Download Fehler: {}", e))?;
if !resp.status().is_success() {
return Err(format!("Download fehlgeschlagen: {}", resp.status()));
}
let bytes = resp.bytes().await.map_err(|e| e.to_string())?;
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
std::fs::write(dest, &bytes).map_err(|e| format!("Schreiben fehlgeschlagen: {}", e))
}
pub async fn upload_file(&self, file_path: &Path, parent_id: Option<i64>) -> Result<FileEntry, String> {
let url = format!("{}/api/files/upload", self.server_url);
let file_name = file_path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("file")
.to_string();
let file_bytes = std::fs::read(file_path)
.map_err(|e| format!("Datei lesen fehlgeschlagen: {}", e))?;
let mut form = reqwest::multipart::Form::new()
.part("file", reqwest::multipart::Part::bytes(file_bytes).file_name(file_name));
if let Some(pid) = parent_id {
form = form.text("parent_id", pid.to_string());
}
let resp = self.client.post(&url)
.header("Authorization", self.auth_header())
.multipart(form)
.send()
.await
.map_err(|e| format!("Upload Fehler: {}", e))?;
if !resp.status().is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(format!("Upload fehlgeschlagen: {}", text));
}
resp.json().await.map_err(|e| format!("Parse-Fehler: {}", e))
}
pub async fn create_folder(&self, name: &str, parent_id: Option<i64>) -> Result<FileEntry, String> {
let url = format!("{}/api/files/folder", self.server_url);
let body = serde_json::json!({
"name": name,
"parent_id": parent_id,
});
let resp = self.client.post(&url)
.header("Authorization", self.auth_header())
.json(&body)
.send()
.await
.map_err(|e| e.to_string())?;
resp.json().await.map_err(|e| e.to_string())
}
pub async fn lock_file(&self, file_id: i64, client_info: &str) -> Result<(), String> {
let url = format!("{}/api/files/{}/lock", self.server_url, file_id);
let body = serde_json::json!({ "client_info": client_info });
let resp = self.client.post(&url)
.header("Authorization", self.auth_header())
.json(&body)
.send()
.await
.map_err(|e| e.to_string())?;
if resp.status().as_u16() == 423 {
let data: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
let by = data.get("locked_by").and_then(|v| v.as_str()).unwrap_or("?");
return Err(format!("Datei gesperrt von {}", by));
}
if !resp.status().is_success() {
return Err("Lock fehlgeschlagen".to_string());
}
Ok(())
}
pub async fn unlock_file(&self, file_id: i64) -> Result<(), String> {
let url = format!("{}/api/files/{}/unlock", self.server_url, file_id);
self.client.post(&url)
.header("Authorization", self.auth_header())
.send()
.await
.map_err(|e| e.to_string())?;
Ok(())
}
pub async fn heartbeat(&self, file_id: i64) -> Result<(), String> {
let url = format!("{}/api/files/{}/heartbeat", self.server_url, file_id);
self.client.post(&url)
.header("Authorization", self.auth_header())
.send()
.await
.map_err(|e| e.to_string())?;
Ok(())
}
}

View File

@ -0,0 +1,196 @@
use crate::sync::api::{FileEntry, MiniCloudApi};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Compare local files with server tree and determine actions
pub struct SyncEngine {
pub sync_dir: PathBuf,
pub api: MiniCloudApi,
last_sync: Option<String>,
}
#[derive(Debug, Clone)]
pub enum SyncAction {
Download { id: i64, name: String, server_path: String },
Upload { local_path: PathBuf, parent_id: Option<i64> },
CreateFolder { name: String, parent_id: Option<i64> },
Delete { local_path: PathBuf },
Conflict { local_path: PathBuf, server_id: i64, locked_by: String },
}
impl SyncEngine {
pub fn new(sync_dir: PathBuf, api: MiniCloudApi) -> Self {
Self { sync_dir, api, last_sync: None }
}
/// Full sync: compare server tree with local filesystem
pub async fn full_sync(&mut self) -> Result<Vec<String>, String> {
let server_tree = self.api.get_sync_tree().await?;
let mut log = Vec::new();
// Download missing/changed files from server
self.sync_download_recursive(&server_tree, &self.sync_dir.clone(), &mut log).await;
// Upload local files not on server
self.sync_upload_recursive(&server_tree, &self.sync_dir.clone(), None, &mut log).await;
// Update last sync time
self.last_sync = Some(chrono::Utc::now().to_rfc3339());
Ok(log)
}
/// Delta sync: only changes since last sync
pub async fn delta_sync(&mut self) -> Result<Vec<String>, String> {
let since = self.last_sync.clone().unwrap_or_else(|| "2000-01-01T00:00:00Z".to_string());
let changes = self.api.get_changes(&since).await?;
let mut log = Vec::new();
for entry in &changes.changes {
let rel_path = self.sync_dir.join(&entry.name);
if entry.is_folder {
if !rel_path.exists() {
std::fs::create_dir_all(&rel_path).ok();
log.push(format!("Ordner erstellt: {}", entry.name));
}
} else {
// Check if locked
if entry.locked.unwrap_or(false) {
log.push(format!("Uebersprungen (gesperrt von {}): {}",
entry.locked_by.as_deref().unwrap_or("?"), entry.name));
continue;
}
// Download if checksum differs
let needs_download = if rel_path.exists() {
let local_hash = compute_file_hash(&rel_path);
local_hash != entry.checksum.as_deref().unwrap_or("")
} else {
true
};
if needs_download {
match self.api.download_file(entry.id, &rel_path).await {
Ok(_) => log.push(format!("Heruntergeladen: {}", entry.name)),
Err(e) => log.push(format!("Fehler {}: {}", entry.name, e)),
}
}
}
}
self.last_sync = Some(changes.server_time);
Ok(log)
}
async fn sync_download_recursive(&self, entries: &[FileEntry], local_dir: &Path, log: &mut Vec<String>) {
for entry in entries {
let local_path = local_dir.join(&entry.name);
if entry.is_folder {
std::fs::create_dir_all(&local_path).ok();
if let Some(children) = &entry.children {
Box::pin(self.sync_download_recursive(children, &local_path, log)).await;
}
} else {
// Skip locked files
if entry.locked.unwrap_or(false) {
continue;
}
let needs_download = if local_path.exists() {
let local_hash = compute_file_hash(&local_path);
local_hash != entry.checksum.as_deref().unwrap_or("")
} else {
true
};
if needs_download {
match self.api.download_file(entry.id, &local_path).await {
Ok(_) => log.push(format!("Heruntergeladen: {}", entry.name)),
Err(e) => log.push(format!("Fehler {}: {}", entry.name, e)),
}
}
}
}
}
async fn sync_upload_recursive(&self, server_entries: &[FileEntry], local_dir: &Path,
parent_id: Option<i64>, log: &mut Vec<String>) {
let server_names: HashMap<String, &FileEntry> = server_entries.iter()
.map(|e| (e.name.clone(), e))
.collect();
let entries = match std::fs::read_dir(local_dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
let path = entry.path();
// Skip hidden files and sync metadata
if name.starts_with('.') || name == ".minicloud_sync" {
continue;
}
if path.is_dir() {
if let Some(server_entry) = server_names.get(&name) {
// Folder exists on server, recurse
if let Some(children) = &server_entry.children {
Box::pin(self.sync_upload_recursive(
children, &path, Some(server_entry.id), log
)).await;
}
} else {
// Folder doesn't exist on server, create + upload contents
match self.api.create_folder(&name, parent_id).await {
Ok(folder) => {
log.push(format!("Ordner erstellt: {}", name));
Box::pin(self.sync_upload_recursive(
&[], &path, Some(folder.id), log
)).await;
}
Err(e) => log.push(format!("Ordner-Fehler {}: {}", name, e)),
}
}
} else {
// File
let needs_upload = if let Some(server_entry) = server_names.get(&name) {
// Check if local version is newer
let local_hash = compute_file_hash(&path);
local_hash != server_entry.checksum.as_deref().unwrap_or("")
} else {
true // New file
};
if needs_upload {
// Check if file is locked on server
if let Some(server_entry) = server_names.get(&name) {
if server_entry.locked.unwrap_or(false) {
log.push(format!("Zurueckgehalten (gesperrt): {}", name));
continue;
}
}
match self.api.upload_file(&path, parent_id).await {
Ok(_) => log.push(format!("Hochgeladen: {}", name)),
Err(e) => log.push(format!("Upload-Fehler {}: {}", name, e)),
}
}
}
}
}
}
pub fn compute_file_hash(path: &Path) -> String {
let data = match std::fs::read(path) {
Ok(d) => d,
Err(_) => return String::new(),
};
let mut hasher = Sha256::new();
hasher.update(&data);
format!("{:x}", hasher.finalize())
}

View File

@ -0,0 +1,3 @@
pub mod api;
pub mod engine;
pub mod watcher;

View File

@ -0,0 +1,58 @@
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::PathBuf;
use std::sync::mpsc;
pub struct FileWatcher {
_watcher: RecommendedWatcher,
pub receiver: mpsc::Receiver<FileChange>,
}
#[derive(Debug, Clone)]
pub struct FileChange {
pub path: PathBuf,
pub kind: ChangeKind,
}
#[derive(Debug, Clone)]
pub enum ChangeKind {
Created,
Modified,
Deleted,
}
impl FileWatcher {
pub fn new(watch_dir: &PathBuf) -> Result<Self, String> {
let (tx, rx) = mpsc::channel();
let mut watcher = RecommendedWatcher::new(
move |result: Result<Event, notify::Error>| {
if let Ok(event) = result {
let kind = match event.kind {
EventKind::Create(_) => Some(ChangeKind::Created),
EventKind::Modify(_) => Some(ChangeKind::Modified),
EventKind::Remove(_) => Some(ChangeKind::Deleted),
_ => None,
};
if let Some(kind) = kind {
for path in event.paths {
// Skip hidden files and temp files
let name = path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
if name.starts_with('.') || name.starts_with('~') || name.ends_with(".tmp") {
continue;
}
let _ = tx.send(FileChange { path, kind: kind.clone() });
}
}
}
},
Config::default(),
).map_err(|e| format!("Watcher-Fehler: {}", e))?;
watcher.watch(watch_dir.as_ref(), RecursiveMode::Recursive)
.map_err(|e| format!("Watch-Fehler: {}", e))?;
Ok(Self { _watcher: watcher, receiver: rx })
}
}

View File

@ -0,0 +1,37 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "MiniCloud Sync",
"version": "0.1.0",
"identifier": "com.minicloud.sync",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "Mini-Cloud Sync",
"width": 700,
"height": 550,
"resizable": true,
"center": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

244
clients/desktop/src/App.vue Normal file
View File

@ -0,0 +1,244 @@
<script setup>
import { ref, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
const screen = ref("login"); // login | main
const serverUrl = ref("https://");
const username = ref("");
const password = ref("");
const loginError = ref("");
const loginLoading = ref(false);
const syncDir = ref("");
const syncLog = ref([]);
const syncing = ref(false);
const userInfo = ref(null);
const fileTree = ref([]);
const statusMsg = ref("Nicht verbunden");
async function handleLogin() {
loginError.value = "";
loginLoading.value = true;
try {
const result = await invoke("login", {
serverUrl: serverUrl.value,
username: username.value,
password: password.value,
});
userInfo.value = result;
screen.value = "main";
statusMsg.value = `Verbunden als ${result.username}`;
// Set default sync dir
syncDir.value = `${await getDefaultSyncDir()}/MiniCloud`;
await loadFileTree();
} catch (err) {
loginError.value = String(err);
} finally {
loginLoading.value = false;
}
}
async function getDefaultSyncDir() {
// Use home directory
try {
const home = await invoke("get_status");
return home.sync_dir || (navigator.platform.includes("Win") ? "C:\\Users" : "/home");
} catch {
return "/home";
}
}
async function setSyncFolder() {
try {
await invoke("set_sync_dir", { path: syncDir.value });
statusMsg.value = `Sync-Ordner: ${syncDir.value}`;
} catch (err) {
statusMsg.value = `Fehler: ${err}`;
}
}
async function runSync() {
syncing.value = true;
statusMsg.value = "Synchronisiere...";
try {
await invoke("set_sync_dir", { path: syncDir.value });
const log = await invoke("start_sync");
syncLog.value = log;
statusMsg.value = `Sync fertig: ${log.length} Aktionen`;
await loadFileTree();
} catch (err) {
statusMsg.value = `Sync-Fehler: ${err}`;
} finally {
syncing.value = false;
}
}
async function loadFileTree() {
try {
fileTree.value = await invoke("get_file_tree");
} catch (err) {
console.error("Tree-Fehler:", err);
}
}
function formatSize(bytes) {
if (!bytes) return "";
const units = ["B", "KB", "MB", "GB"];
let i = 0;
let size = bytes;
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
return `${size.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;
}
</script>
<template>
<!-- Login -->
<div v-if="screen === 'login'" class="login-screen">
<div class="login-card">
<div class="login-header">
<div class="logo-icon"></div>
<h1>Mini-Cloud</h1>
<p>Desktop Sync Client</p>
</div>
<form @submit.prevent="handleLogin">
<div class="field">
<label>Server-URL</label>
<input v-model="serverUrl" placeholder="https://cloud.example.com" />
</div>
<div class="field">
<label>Benutzername</label>
<input v-model="username" placeholder="Benutzername" autofocus />
</div>
<div class="field">
<label>Passwort</label>
<input v-model="password" type="password" placeholder="Passwort" />
</div>
<div v-if="loginError" class="error">{{ loginError }}</div>
<button type="submit" :disabled="loginLoading" class="btn-primary">
{{ loginLoading ? "Verbinde..." : "Anmelden" }}
</button>
</form>
</div>
</div>
<!-- Main -->
<div v-else class="main-screen">
<div class="toolbar">
<div class="toolbar-left">
<span class="logo-small"></span>
<strong>Mini-Cloud</strong>
<span class="status-badge">{{ statusMsg }}</span>
</div>
<div class="toolbar-right">
<span class="user-info">{{ userInfo?.username }}</span>
</div>
</div>
<div class="content">
<!-- Sync Settings -->
<div class="section">
<h3>Sync-Ordner</h3>
<div class="sync-row">
<input v-model="syncDir" class="sync-input" />
<button @click="runSync" :disabled="syncing" class="btn-primary">
{{ syncing ? "Synchronisiere..." : "Jetzt synchronisieren" }}
</button>
</div>
</div>
<!-- File Tree -->
<div class="section">
<h3>Server-Dateien</h3>
<div class="file-tree">
<div v-for="entry in fileTree" :key="entry.id" class="tree-item">
<span class="tree-icon">{{ entry.is_folder ? "📁" : "📄" }}</span>
<span class="tree-name">{{ entry.name }}</span>
<span v-if="entry.locked" class="tree-lock" :title="'Gesperrt von ' + entry.locked_by">
🔒 {{ entry.locked_by }}
</span>
<span v-if="!entry.is_folder" class="tree-size">{{ formatSize(entry.size) }}</span>
</div>
<div v-if="!fileTree.length" class="empty">Keine Dateien</div>
</div>
</div>
<!-- Sync Log -->
<div v-if="syncLog.length" class="section">
<h3>Sync-Protokoll</h3>
<div class="log-list">
<div v-for="(msg, i) in syncLog" :key="i" class="log-item">{{ msg }}</div>
</div>
</div>
</div>
</div>
</template>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px; color: #1a1a1a; background: #f0f2f5;
}
.login-screen {
height: 100vh; display: flex; align-items: center; justify-content: center;
}
.login-card {
background: white; border-radius: 12px; padding: 2rem; width: 360px;
box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
.login-header { text-align: center; margin-bottom: 1.5rem; }
.logo-icon { font-size: 2.5rem; }
.login-header h1 { font-size: 1.3rem; margin: 0.5rem 0 0.25rem; }
.login-header p { color: #666; font-size: 0.85rem; }
.field { margin-bottom: 0.75rem; }
.field label { display: block; margin-bottom: 0.25rem; font-weight: 500; font-size: 0.85rem; }
.field input {
width: 100%; padding: 0.5rem; border: 1px solid #ddd; border-radius: 6px;
font-size: 0.9rem; background: #fafafa;
}
.field input:focus { border-color: #4a90d9; outline: none; background: white; }
.error { color: #e53e3e; font-size: 0.85rem; margin-bottom: 0.75rem; }
.btn-primary {
width: 100%; padding: 0.6rem; background: #4a90d9; color: white;
border: none; border-radius: 6px; font-size: 0.9rem; cursor: pointer; font-weight: 500;
}
.btn-primary:hover { background: #3a7bc8; }
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
.main-screen { height: 100vh; display: flex; flex-direction: column; }
.toolbar {
display: flex; align-items: center; justify-content: space-between;
padding: 0.5rem 1rem; background: white; border-bottom: 1px solid #e0e0e0;
}
.toolbar-left { display: flex; align-items: center; gap: 0.5rem; }
.logo-small { font-size: 1.2rem; }
.status-badge { font-size: 0.8rem; color: #666; background: #f0f0f0; padding: 0.2rem 0.5rem; border-radius: 4px; }
.user-info { font-size: 0.85rem; color: #666; }
.content { flex: 1; overflow-y: auto; padding: 1rem; }
.section { background: white; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; }
.section h3 { margin-bottom: 0.75rem; font-size: 0.95rem; }
.sync-row { display: flex; gap: 0.5rem; }
.sync-input { flex: 1; padding: 0.5rem; border: 1px solid #ddd; border-radius: 6px; font-size: 0.85rem; }
.file-tree { max-height: 300px; overflow-y: auto; }
.tree-item {
display: flex; align-items: center; gap: 0.5rem;
padding: 0.375rem 0; border-bottom: 1px solid #f5f5f5; font-size: 0.85rem;
}
.tree-icon { flex-shrink: 0; }
.tree-name { flex: 1; }
.tree-lock { font-size: 0.75rem; color: #e67e22; }
.tree-size { font-size: 0.75rem; color: #999; }
.empty { text-align: center; color: #999; padding: 1rem; }
.log-list { max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 0.8rem; }
.log-item { padding: 0.25rem 0; border-bottom: 1px solid #f5f5f5; }
@media (prefers-color-scheme: dark) {
body { color: #e0e0e0; background: #1a1a1a; }
.login-card, .section { background: #2a2a2a; }
.toolbar { background: #2a2a2a; border-color: #3a3a3a; }
.field input, .sync-input { background: #333; border-color: #444; color: #e0e0e0; }
.status-badge { background: #3a3a3a; color: #aaa; }
.tree-item { border-color: #333; }
}
</style>

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

View File

@ -0,0 +1,4 @@
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");

View File

@ -0,0 +1,31 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(async () => ({
plugins: [vue()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));