Compare commits

...

6 Commits

Author SHA1 Message Date
spinline
a4fe8d065c debug: log user value in SSE loop
All checks were successful
Build MIPS Binary / build (push) Successful in 5m21s
2026-02-09 23:55:57 +03:00
spinline
3215b38272 fix: add missing spawn_local import
All checks were successful
Build MIPS Binary / build (push) Successful in 5m20s
2026-02-09 23:48:52 +03:00
spinline
8eb594e804 refactor: move SSE logic to spawn_local with continuous user check
Some checks failed
Build MIPS Binary / build (push) Failing after 1m15s
2026-02-09 22:48:00 +03:00
spinline
518af10cd7 fix: use .0 for reading and .1 for writing signals
All checks were successful
Build MIPS Binary / build (push) Successful in 5m20s
2026-02-09 22:37:06 +03:00
spinline
0304c5cb7d fix: prevent panic by using signals for redirects and fix auth flow
Some checks failed
Build MIPS Binary / build (push) Failing after 1m15s
2026-02-09 22:32:19 +03:00
spinline
cee609700a fix: use navigate inside Router context and fix auth redirect flow
Some checks failed
Build MIPS Binary / build (push) Has been cancelled
2026-02-09 22:30:59 +03:00
2 changed files with 121 additions and 120 deletions

View File

@@ -25,9 +25,7 @@ pub fn App() -> impl IntoView {
match setup_res { match setup_res {
Ok(status) => { Ok(status) => {
if !status.completed { if !status.completed {
log::info!("Setup not completed, redirecting to /setup"); log::info!("Setup not completed");
let navigate = use_navigate();
navigate("/setup", Default::default());
is_loading.1.set(false); is_loading.1.set(false);
return; return;
} }
@@ -48,27 +46,12 @@ pub fn App() -> impl IntoView {
} }
is_authenticated.1.set(true); is_authenticated.1.set(true);
let pathname = window().location().pathname().unwrap_or_default();
if pathname == "/login" || pathname == "/setup" {
log::info!("Already authenticated, redirecting to home");
let navigate = use_navigate();
navigate("/", Default::default());
}
} }
Ok(false) => { Ok(false) => {
log::info!("Not authenticated"); log::info!("Not authenticated");
let pathname = window().location().pathname().unwrap_or_default();
if pathname != "/login" && pathname != "/setup" {
let navigate = use_navigate();
navigate("/login", Default::default());
}
} }
Err(e) => { Err(e) => {
log::error!("Auth check failed: {:?}", e); log::error!("Auth check failed: {:?}", e);
let navigate = use_navigate();
navigate("/login", Default::default());
} }
} }
@@ -92,10 +75,39 @@ pub fn App() -> impl IntoView {
<div class="relative w-full h-screen" style="height: 100dvh;"> <div class="relative w-full h-screen" style="height: 100dvh;">
<Router> <Router>
<Routes fallback=|| view! { <div class="p-4">"404 Not Found"</div> }> <Routes fallback=|| view! { <div class="p-4">"404 Not Found"</div> }>
<Route path=leptos_router::path!("/login") view=move || view! { <Login /> } /> <Route path=leptos_router::path!("/login") view=move || {
<Route path=leptos_router::path!("/setup") view=move || view! { <Setup /> } /> let authenticated = is_authenticated.0.get();
Effect::new(move |_| {
if authenticated {
log::info!("Already authenticated, redirecting to home");
let navigate = use_navigate();
navigate("/", Default::default());
}
});
view! { <Login /> }
} />
<Route path=leptos_router::path!("/setup") view=move || {
Effect::new(move |_| {
if is_authenticated.0.get() {
let navigate = use_navigate();
navigate("/", Default::default());
}
});
view! { <Setup /> }
} />
<Route path=leptos_router::path!("/") view=move || { <Route path=leptos_router::path!("/") view=move || {
Effect::new(move |_| {
if !is_loading.0.get() && !is_authenticated.0.get() {
log::info!("Not authenticated, redirecting to login");
let navigate = use_navigate();
navigate("/login", Default::default());
}
});
view! { view! {
<Show when=move || !is_loading.0.get() fallback=|| view! { <Show when=move || !is_loading.0.get() fallback=|| view! {
<div class="flex items-center justify-center h-screen bg-base-100"> <div class="flex items-center justify-center h-screen bg-base-100">
@@ -112,6 +124,13 @@ pub fn App() -> impl IntoView {
}/> }/>
<Route path=leptos_router::path!("/settings") view=move || { <Route path=leptos_router::path!("/settings") view=move || {
Effect::new(move |_| {
if !is_authenticated.0.get() {
let navigate = use_navigate();
navigate("/login", Default::default());
}
});
view! { view! {
<Show when=move || !is_loading.0.get() fallback=|| ()> <Show when=move || !is_loading.0.get() fallback=|| ()>
<Show when=move || is_authenticated.0.get() fallback=|| ()> <Show when=move || is_authenticated.0.get() fallback=|| ()>
@@ -128,4 +147,4 @@ pub fn App() -> impl IntoView {
<ToastContainer /> <ToastContainer />
</div> </div>
} }
} }

View File

@@ -1,6 +1,7 @@
use futures::StreamExt; use futures::StreamExt;
use gloo_net::eventsource::futures::EventSource; use gloo_net::eventsource::futures::EventSource;
use leptos::prelude::*; use leptos::prelude::*;
use leptos::task::spawn_local;
use shared::{AppEvent, GlobalStats, NotificationLevel, SystemNotification, Torrent}; use shared::{AppEvent, GlobalStats, NotificationLevel, SystemNotification, Torrent};
use std::collections::HashMap; use std::collections::HashMap;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
@@ -11,10 +12,6 @@ pub struct NotificationItem {
pub notification: SystemNotification, pub notification: SystemNotification,
} }
// ============================================================================
// Toast Helper Functions
// ============================================================================
pub fn show_toast_with_signal( pub fn show_toast_with_signal(
notifications: RwSignal<Vec<NotificationItem>>, notifications: RwSignal<Vec<NotificationItem>>,
level: NotificationLevel, level: NotificationLevel,
@@ -29,7 +26,6 @@ pub fn show_toast_with_signal(
notifications.update(|list| list.push(item)); notifications.update(|list| list.push(item));
// Auto-remove after 5 seconds
leptos::prelude::set_timeout( leptos::prelude::set_timeout(
move || { move || {
notifications.update(|list| list.retain(|i| i.id != id)); notifications.update(|list| list.retain(|i| i.id != id));
@@ -47,10 +43,6 @@ pub fn show_toast(level: NotificationLevel, message: impl Into<String>) {
pub fn toast_success(message: impl Into<String>) { show_toast(NotificationLevel::Success, message); } pub fn toast_success(message: impl Into<String>) { show_toast(NotificationLevel::Success, message); }
pub fn toast_error(message: impl Into<String>) { show_toast(NotificationLevel::Error, message); } pub fn toast_error(message: impl Into<String>) { show_toast(NotificationLevel::Error, message); }
// ============================================================================
// Action Message Mapping
// ============================================================================
pub fn get_action_messages(action: &str) -> (&'static str, &'static str) { pub fn get_action_messages(action: &str) -> (&'static str, &'static str) {
match action { match action {
"start" => ("Torrent başlatıldı", "Torrent başlatılamadı"), "start" => ("Torrent başlatıldı", "Torrent başlatılamadı"),
@@ -75,10 +67,6 @@ pub struct PushKeys {
pub auth: String, pub auth: String,
} }
// ============================================================================
// Store Definition
// ============================================================================
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FilterStatus { pub enum FilterStatus {
All, Downloading, Seeding, Completed, Paused, Inactive, Active, Error, All, Downloading, Seeding, Completed, Paused, Inactive, Active, Error,
@@ -107,111 +95,105 @@ pub fn provide_torrent_store() {
let store = TorrentStore { torrents, filter, search_query, global_stats, notifications, user }; let store = TorrentStore { torrents, filter, search_query, global_stats, notifications, user };
provide_context(store); provide_context(store);
let notifications_for_effect = notifications; let user_for_sse = user;
let global_stats_for_effect = global_stats; let notifications_for_sse = notifications;
let torrents_for_effect = torrents; let global_stats_for_sse = global_stats;
let torrents_for_sse = torrents;
let show_browser_notification = show_browser_notification.clone(); let show_browser_notification = show_browser_notification.clone();
Effect::new(move |_| { spawn_local(async move {
let user_val = user.get(); let mut backoff_ms: u32 = 1000;
log::debug!("SSE Effect: user = {:?}", user_val); let mut was_connected = false;
if user_val.is_none() { let mut disconnect_notified = false;
log::debug!("SSE Effect: user is None, skipping connection");
return;
}
let notifications = notifications_for_effect; loop {
let global_stats = global_stats_for_effect; let user_val = user_for_sse.get();
let torrents = torrents_for_effect; log::debug!("SSE: user = {:?}", user_val);
let show_browser_notification = show_browser_notification.clone(); if user_val.is_none() {
log::debug!("SSE: User not authenticated, waiting...");
gloo_timers::future::TimeoutFuture::new(1000).await;
continue;
}
log::info!("SSE: Starting connection (user logged in)"); log::debug!("SSE: Creating EventSource...");
let es_result = EventSource::new("/api/events");
leptos::task::spawn_local(async move { match es_result {
let mut backoff_ms: u32 = 1000; Ok(mut es) => {
let mut was_connected = false; log::debug!("SSE: EventSource created, subscribing...");
let mut disconnect_notified = false; if let Ok(mut stream) = es.subscribe("message") {
log::debug!("SSE: Subscribed to message channel");
loop { let mut got_first_message = false;
log::debug!("SSE: Creating EventSource..."); while let Some(Ok((_, msg))) = stream.next().await {
let es_result = EventSource::new("/api/events"); log::debug!("SSE: Received message");
match es_result { if !got_first_message {
Ok(mut es) => { got_first_message = true;
log::debug!("SSE: EventSource created, subscribing to message channel..."); backoff_ms = 1000;
if let Ok(mut stream) = es.subscribe("message") { if was_connected && disconnect_notified {
log::debug!("SSE: Subscribed to message channel"); show_toast_with_signal(notifications_for_sse, NotificationLevel::Success, "Sunucu bağlantısı yeniden kuruldu");
let mut got_first_message = false; disconnect_notified = false;
while let Some(Ok((_, msg))) = stream.next().await {
log::debug!("SSE: Received message: {:?}", msg.data());
if !got_first_message {
got_first_message = true;
backoff_ms = 1000;
if was_connected && disconnect_notified {
show_toast_with_signal(notifications, NotificationLevel::Success, "Sunucu bağlantısı yeniden kuruldu");
disconnect_notified = false;
}
was_connected = true;
} }
was_connected = true;
}
if let Some(data_str) = msg.data().as_string() { if let Some(data_str) = msg.data().as_string() {
log::debug!("SSE: Parsing JSON: {}", data_str); log::debug!("SSE: Parsing JSON: {}", data_str);
if let Ok(event) = serde_json::from_str::<AppEvent>(&data_str) { if let Ok(event) = serde_json::from_str::<AppEvent>(&data_str) {
match event { match event {
AppEvent::FullList { torrents: list, .. } => { AppEvent::FullList { torrents: list, .. } => {
log::info!("SSE: Received FullList with {} torrents", list.len()); log::info!("SSE: Received FullList with {} torrents", list.len());
torrents.update(|map| { torrents_for_sse.update(|map| {
let new_hashes: std::collections::HashSet<String> = list.iter().map(|t| t.hash.clone()).collect(); let new_hashes: std::collections::HashSet<String> = list.iter().map(|t| t.hash.clone()).collect();
map.retain(|hash, _| new_hashes.contains(hash)); map.retain(|hash, _| new_hashes.contains(hash));
for new_torrent in list { for new_torrent in list {
map.insert(new_torrent.hash.clone(), new_torrent); map.insert(new_torrent.hash.clone(), new_torrent);
}
});
log::debug!("SSE: torrents map now has {} entries", torrents.with(|m| m.len()));
}
AppEvent::Update(update) => {
torrents.update(|map| {
if let Some(t) = map.get_mut(&update.hash) {
if let Some(v) = update.name { t.name = v; }
if let Some(v) = update.size { t.size = v; }
if let Some(v) = update.down_rate { t.down_rate = v; }
if let Some(v) = update.up_rate { t.up_rate = v; }
if let Some(v) = update.percent_complete { t.percent_complete = v; }
if let Some(v) = update.completed { t.completed = v; }
if let Some(v) = update.eta { t.eta = v; }
if let Some(v) = update.status { t.status = v; }
if let Some(v) = update.error_message { t.error_message = v; }
if let Some(v) = update.label { t.label = Some(v); }
}
});
}
AppEvent::Stats(stats) => { global_stats.set(stats); }
AppEvent::Notification(n) => {
show_toast_with_signal(notifications, n.level.clone(), n.message.clone());
if n.message.contains("tamamlandı") || n.level == shared::NotificationLevel::Error {
show_browser_notification("VibeTorrent", &n.message);
} }
});
log::debug!("SSE: torrents map now has {} entries", torrents_for_sse.with(|m| m.len()));
}
AppEvent::Update(update) => {
torrents_for_sse.update(|map| {
if let Some(t) = map.get_mut(&update.hash) {
if let Some(v) = update.name { t.name = v; }
if let Some(v) = update.size { t.size = v; }
if let Some(v) = update.down_rate { t.down_rate = v; }
if let Some(v) = update.up_rate { t.up_rate = v; }
if let Some(v) = update.percent_complete { t.percent_complete = v; }
if let Some(v) = update.completed { t.completed = v; }
if let Some(v) = update.eta { t.eta = v; }
if let Some(v) = update.status { t.status = v; }
if let Some(v) = update.error_message { t.error_message = v; }
if let Some(v) = update.label { t.label = Some(v); }
}
});
}
AppEvent::Stats(stats) => { global_stats_for_sse.set(stats); }
AppEvent::Notification(n) => {
show_toast_with_signal(notifications_for_sse, n.level.clone(), n.message.clone());
if n.message.contains("tamamlandı") || n.level == shared::NotificationLevel::Error {
show_browser_notification("VibeTorrent", &n.message);
} }
} }
} }
} }
} }
if was_connected && !disconnect_notified {
show_toast_with_signal(notifications, NotificationLevel::Warning, "Sunucu bağlantısı kesildi, yeniden bağlanılıyor...");
disconnect_notified = true;
}
} }
}
Err(_) => {
if was_connected && !disconnect_notified { if was_connected && !disconnect_notified {
show_toast_with_signal(notifications, NotificationLevel::Warning, "Sunucu bağlantısı kurulamıyor..."); show_toast_with_signal(notifications_for_sse, NotificationLevel::Warning, "Sunucu bağlantısı kesildi, yeniden bağlanılıyor...");
disconnect_notified = true; disconnect_notified = true;
} }
} }
} }
gloo_timers::future::TimeoutFuture::new(backoff_ms).await; Err(_) => {
backoff_ms = std::cmp::min(backoff_ms * 2, 30000); if was_connected && !disconnect_notified {
show_toast_with_signal(notifications_for_sse, NotificationLevel::Warning, "Sunucu bağlantısı kurulamıyor...");
disconnect_notified = true;
}
}
} }
}); log::debug!("SSE: Reconnecting in {}ms...", backoff_ms);
gloo_timers::future::TimeoutFuture::new(backoff_ms).await;
backoff_ms = std::cmp::min(backoff_ms * 2, 30000);
}
}); });
} }