Compare commits
30 Commits
release-20
...
release-20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74c3c5c17e | ||
|
|
3632a578e1 | ||
|
|
8a9905fc56 | ||
|
|
1e39cbb0c5 | ||
|
|
40be58f2fc | ||
|
|
3f08b5b54a | ||
|
|
bfec99ae35 | ||
|
|
d9afd3aa81 | ||
|
|
e72113d91d | ||
|
|
7c4ff619c1 | ||
|
|
9c4217f450 | ||
|
|
cc09002171 | ||
|
|
5d8cdd7760 | ||
|
|
145436eefc | ||
|
|
10c95c5ff3 | ||
|
|
329654cc4e | ||
|
|
22b592a652 | ||
|
|
817dc49db2 | ||
|
|
b2a60d3d1e | ||
|
|
520903fa3f | ||
|
|
c45f2f50e9 | ||
|
|
791eabe9bd | ||
|
|
12f93dd640 | ||
|
|
7306db8c2f | ||
|
|
ce0ecd62af | ||
|
|
f2379b67d8 | ||
|
|
755f35c94c | ||
|
|
175cac953e | ||
|
|
2c812fc4f6 | ||
|
|
08df851970 |
@@ -26,23 +26,22 @@ jobs:
|
||||
run: |
|
||||
cd frontend
|
||||
npm install
|
||||
# Run Tailwind manually first
|
||||
npx @tailwindcss/cli -i input.css -o public/tailwind.css
|
||||
# Trunk'ın optimizasyonunu kapalı (0) tutuyoruz çünkü Cargo.toml'daki opt-level='z' zaten o işi yapıyor.
|
||||
trunk build --release
|
||||
|
||||
- name: Build Backend (MIPS)
|
||||
env:
|
||||
# Ensure we are building a fully static binary
|
||||
# -C link-self-contained=no: Let Zig (the linker) handle CRT objects (crt1.o, etc.)
|
||||
RUSTFLAGS: "-C target-feature=+crt-static -C link-self-contained=no -C link-arg=-msoft-float"
|
||||
# -s ve -w ile binary içindeki gereksiz tüm yükleri siliyoruz.
|
||||
RUSTFLAGS: "-C target-feature=+crt-static -C link-self-contained=no -C link-arg=-msoft-float -C link-arg=-s -C link-arg=-w"
|
||||
CFLAGS_mips_unknown_linux_musl: "-msoft-float"
|
||||
run: |
|
||||
cd backend
|
||||
cargo zigbuild --target mips-unknown-linux-musl --release -Z build-std=std,panic_abort
|
||||
file target/mips-unknown-linux-musl/release/backend
|
||||
# Sadece gerekli özellikleri derliyoruz (Boyut tasarrufu için swagger kapalı)
|
||||
cargo zigbuild -p backend --target mips-unknown-linux-musl --release -Z build-std=std,panic_abort --no-default-features --features push-notifications
|
||||
|
||||
- name: Rename Binary
|
||||
run: mv target/mips-unknown-linux-musl/release/backend target/mips-unknown-linux-musl/release/vibetorrent-mips
|
||||
- name: Create Release Assets
|
||||
run: |
|
||||
mv target/mips-unknown-linux-musl/release/backend target/mips-unknown-linux-musl/release/vibetorrent-mips
|
||||
|
||||
- name: Generate Release Tag
|
||||
id: tag
|
||||
@@ -56,8 +55,10 @@ jobs:
|
||||
REPO="admin/vibetorrent"
|
||||
API_URL="${{ gitea.server_url }}/api/v1"
|
||||
|
||||
# Create release
|
||||
RELEASE_RESPONSE=$(curl -s -X POST "${API_URL}/repos/${REPO}/releases" -H "Authorization: token ${RELEASE_TOKEN}" -H "Content-Type: application/json" -d "{
|
||||
RELEASE_RESPONSE=$(curl -s -X POST "${API_URL}/repos/${REPO}/releases" \
|
||||
-H "Authorization: token ${RELEASE_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"tag_name\": \"${TAG}\",
|
||||
\"name\": \"Release ${TAG}\",
|
||||
\"body\": \"Automated build from commit ${{ gitea.sha }}\",
|
||||
@@ -66,15 +67,9 @@ jobs:
|
||||
}")
|
||||
|
||||
RELEASE_ID=$(echo "$RELEASE_RESPONSE" | jq -r '.id')
|
||||
echo "Release ID: $RELEASE_ID"
|
||||
if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then exit 1; fi
|
||||
|
||||
if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then
|
||||
echo "Failed to create release:"
|
||||
echo "$RELEASE_RESPONSE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Upload binary as release asset
|
||||
curl -s -X POST "${API_URL}/repos/${REPO}/releases/${RELEASE_ID}/assets?name=vibetorrent-mips" -H "Authorization: token ${RELEASE_TOKEN}" -H "Content-Type: application/octet-stream" --data-binary @target/mips-unknown-linux-musl/release/vibetorrent-mips
|
||||
|
||||
echo "Release ${TAG} created with binary attached."
|
||||
curl -s -X POST "${API_URL}/repos/${REPO}/releases/${RELEASE_ID}/assets?name=vibetorrent-mips" \
|
||||
-H "Authorization: token ${RELEASE_TOKEN}" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @target/mips-unknown-linux-musl/release/vibetorrent-mips
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -6,3 +6,5 @@ result.xml
|
||||
frontend/dist
|
||||
backend.log
|
||||
.runner
|
||||
.env
|
||||
backend/.env
|
||||
|
||||
12
Cargo.toml
12
Cargo.toml
@@ -2,13 +2,19 @@
|
||||
members = ["backend", "frontend", "shared"]
|
||||
resolver = "2"
|
||||
|
||||
# Optimize for size (aggressive)
|
||||
[profile.release]
|
||||
# En küçük binary boyutu
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
# En derin kod temizliği (dead code elimination)
|
||||
lto = "fat"
|
||||
# En iyi optimizasyon için tek birim derleme
|
||||
codegen-units = 1
|
||||
# Hata izleme kodlarını atarak yer kazan
|
||||
panic = "abort"
|
||||
# Sembolleri ve hata ayıklama bilgilerini kesin sil
|
||||
strip = true
|
||||
# Artık (incremental) build'i kapat ki optimizasyon tam olsun
|
||||
incremental = false
|
||||
|
||||
[patch.crates-io]
|
||||
coarsetime = { path = "third_party/coarsetime" }
|
||||
coarsetime = { path = "third_party/coarsetime" }
|
||||
@@ -1,8 +0,0 @@
|
||||
# Database
|
||||
DATABASE_URL=sqlite:vibetorrent.db
|
||||
|
||||
# VAPID Keys for Push Notifications
|
||||
# Generate new keys for production using: cargo run --bin web-push --features web-push -- generate-vapid-keys
|
||||
VAPID_PUBLIC_KEY=BEdPj6XQR7MGzM28Nev9wokF5upHoydNDahouJbQ9ZdBJpEFAN1iNfANSEvY0ItasNY5zcvvqN_tjUt64Rfd0gU
|
||||
VAPID_PRIVATE_KEY=aUcCYJ7kUd9UClCaWwad0IVgbYJ6svwl19MjSX7GH10
|
||||
VAPID_EMAIL=mailto:admin@vibetorrent.app
|
||||
@@ -3,3 +3,12 @@ RTORRENT_SOCKET=/tmp/rtorrent.sock
|
||||
|
||||
# Backend Listen Port
|
||||
PORT=3000
|
||||
|
||||
# Database URL
|
||||
DATABASE_URL=sqlite:vibetorrent.db
|
||||
|
||||
# VAPID Keys for Push Notifications
|
||||
# Generate new keys for production using: npx web-push generate-vapid-keys
|
||||
VAPID_PUBLIC_KEY=YOUR_PUBLIC_VAPID_KEY
|
||||
VAPID_PRIVATE_KEY=YOUR_PRIVATE_VAPID_KEY
|
||||
VAPID_EMAIL=mailto:your-email@example.com
|
||||
@@ -4,8 +4,9 @@ version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[features]
|
||||
default = ["push-notifications"]
|
||||
default = ["push-notifications", "swagger"]
|
||||
push-notifications = ["web-push", "openssl"]
|
||||
swagger = ["utoipa-swagger-ui"]
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8", features = ["macros", "ws"] }
|
||||
@@ -29,7 +30,7 @@ shared = { path = "../shared" }
|
||||
thiserror = "2.0.18"
|
||||
dotenvy = "0.15.7"
|
||||
utoipa = { version = "5.4.0", features = ["axum_extras"] }
|
||||
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
|
||||
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"], optional = true }
|
||||
web-push = { version = "0.10", default-features = false, features = ["hyper-client"], optional = true }
|
||||
base64 = "0.22"
|
||||
openssl = { version = "0.10", features = ["vendored"], optional = true }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite, Row};
|
||||
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite, Row, sqlite::SqliteConnectOptions};
|
||||
use std::time::Duration;
|
||||
use anyhow::Result;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Db {
|
||||
@@ -9,10 +10,16 @@ pub struct Db {
|
||||
|
||||
impl Db {
|
||||
pub async fn new(db_url: &str) -> Result<Self> {
|
||||
let options = SqliteConnectOptions::from_str(db_url)?
|
||||
.create_if_missing(true)
|
||||
.busy_timeout(Duration::from_secs(10)) // Bekleme süresini 10 saniyeye çıkardık
|
||||
.journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
|
||||
.synchronous(sqlx::sqlite::SqliteSynchronous::Normal);
|
||||
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(5)
|
||||
.acquire_timeout(Duration::from_secs(3))
|
||||
.connect(db_url)
|
||||
.acquire_timeout(Duration::from_secs(10))
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
|
||||
let db = Self { pool };
|
||||
@@ -21,21 +28,6 @@ impl Db {
|
||||
}
|
||||
|
||||
async fn run_migrations(&self) -> Result<()> {
|
||||
// WAL mode - enables concurrent reads while writing
|
||||
sqlx::query("PRAGMA journal_mode=WAL")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
// NORMAL synchronous - faster than FULL, still safe enough
|
||||
sqlx::query("PRAGMA synchronous=NORMAL")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
// 5 second busy timeout - reduces "database locked" errors
|
||||
sqlx::query("PRAGMA busy_timeout=5000")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::migrate!("./migrations").run(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use shared::{AppEvent, NotificationLevel, SystemNotification, Torrent, TorrentUpdate};
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -8,24 +9,32 @@ pub enum DiffResult {
|
||||
}
|
||||
|
||||
pub fn diff_torrents(old: &[Torrent], new: &[Torrent]) -> DiffResult {
|
||||
// 1. Structural Check (Length or Order changed)
|
||||
// 1. Structural Check: Eğer torrent sayısı değişmişse (yeni eklenen veya silinen),
|
||||
// şimdilik basitlik adına FullUpdate gönderiyoruz.
|
||||
if old.len() != new.len() {
|
||||
return DiffResult::FullUpdate;
|
||||
}
|
||||
|
||||
for (i, t) in new.iter().enumerate() {
|
||||
if old[i].hash != t.hash {
|
||||
// 2. Hash Set Karşılaştırması:
|
||||
// Sıralama değişmiş olabilir ama torrentler aynı mı?
|
||||
let old_map: HashMap<&str, &Torrent> = old.iter().map(|t| (t.hash.as_str(), t)).collect();
|
||||
|
||||
// Eğer yeni listedeki bir hash eski listede yoksa, yapı değişmiş demektir.
|
||||
for new_t in new {
|
||||
if !old_map.contains_key(new_t.hash.as_str()) {
|
||||
return DiffResult::FullUpdate;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Field Updates
|
||||
// 3. Alan Güncellemeleri (Partial Updates)
|
||||
// Buraya geldiğimizde biliyoruz ki old ve new listelerindeki torrentler (hash olarak) aynı,
|
||||
// sadece sıraları farklı olabilir veya içindeki veriler güncellenmiş olabilir.
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (i, new_t) in new.iter().enumerate() {
|
||||
let old_t = &old[i];
|
||||
for new_t in new {
|
||||
// old_map'ten ilgili torrente hash ile ulaşalım (sıradan bağımsız)
|
||||
let old_t = old_map.get(new_t.hash.as_str()).unwrap();
|
||||
|
||||
// Initialize with all None
|
||||
let mut update = TorrentUpdate {
|
||||
hash: new_t.hash.clone(),
|
||||
name: None,
|
||||
@@ -42,7 +51,7 @@ pub fn diff_torrents(old: &[Torrent], new: &[Torrent]) -> DiffResult {
|
||||
|
||||
let mut has_changes = false;
|
||||
|
||||
// Compare fields
|
||||
// Alanları karşılaştır
|
||||
if old_t.name != new_t.name {
|
||||
update.name = Some(new_t.name.clone());
|
||||
has_changes = true;
|
||||
@@ -63,7 +72,7 @@ pub fn diff_torrents(old: &[Torrent], new: &[Torrent]) -> DiffResult {
|
||||
update.percent_complete = Some(new_t.percent_complete);
|
||||
has_changes = true;
|
||||
|
||||
// Check for torrent completion: reached 100%
|
||||
// Torrent tamamlanma kontrolü
|
||||
if old_t.percent_complete < 100.0 && new_t.percent_complete >= 100.0 {
|
||||
tracing::info!("Torrent completed: {} ({})", new_t.name, new_t.hash);
|
||||
events.push(AppEvent::Notification(SystemNotification {
|
||||
@@ -83,8 +92,7 @@ pub fn diff_torrents(old: &[Torrent], new: &[Torrent]) -> DiffResult {
|
||||
if old_t.status != new_t.status {
|
||||
update.status = Some(new_t.status.clone());
|
||||
has_changes = true;
|
||||
|
||||
// Log status changes for debugging
|
||||
|
||||
tracing::debug!(
|
||||
"Torrent status changed: {} ({}) {:?} -> {:?}",
|
||||
new_t.name, new_t.hash, old_t.status, new_t.status
|
||||
@@ -110,4 +118,4 @@ pub fn diff_torrents(old: &[Torrent], new: &[Torrent]) -> DiffResult {
|
||||
tracing::debug!("Generated {} partial updates", events.len());
|
||||
DiffResult::Partial(events)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -690,8 +690,10 @@ pub async fn handle_timeout_error(err: BoxError) -> (StatusCode, &'static str) {
|
||||
(status = 200, description = "VAPID public key", body = String)
|
||||
)
|
||||
)]
|
||||
pub async fn get_push_public_key_handler() -> impl IntoResponse {
|
||||
let public_key = push::get_vapid_public_key();
|
||||
pub async fn get_push_public_key_handler(
|
||||
State(state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let public_key = state.push_store.get_public_key();
|
||||
(StatusCode::OK, Json(serde_json::json!({ "publicKey": public_key }))).into_response()
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ use tower_http::{
|
||||
trace::TraceLayer,
|
||||
};
|
||||
use utoipa::OpenApi;
|
||||
#[cfg(feature = "swagger")]
|
||||
use utoipa_swagger_ui::SwaggerUi;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -98,6 +99,7 @@ struct Args {
|
||||
reset_password: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "swagger")]
|
||||
#[cfg(feature = "push-notifications")]
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
@@ -146,6 +148,7 @@ struct Args {
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
#[cfg(feature = "swagger")]
|
||||
#[cfg(not(feature = "push-notifications"))]
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
@@ -255,9 +258,7 @@ async fn main() {
|
||||
}
|
||||
};
|
||||
|
||||
// Update in DB (using a direct query since db.rs doesn't have update_password yet)
|
||||
// We should add `update_password` to db.rs for cleaner code, but for now direct query is fine or we can extend Db.
|
||||
// Let's extend Db.rs first to be clean.
|
||||
// Update in DB
|
||||
if let Err(e) = db.update_password(user_id, &password_hash).await {
|
||||
tracing::error!("Failed to update password in DB: {}", e);
|
||||
std::process::exit(1);
|
||||
@@ -464,9 +465,13 @@ async fn main() {
|
||||
}
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()))
|
||||
// Setup & Auth Routes
|
||||
let app = Router::new();
|
||||
|
||||
#[cfg(feature = "swagger")]
|
||||
let app = app.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()));
|
||||
|
||||
// Setup & Auth Routes
|
||||
let app = app
|
||||
.route("/api/setup/status", get(handlers::setup::get_setup_status_handler))
|
||||
.route("/api/setup", post(handlers::setup::setup_handler))
|
||||
.route(
|
||||
|
||||
@@ -5,6 +5,7 @@ use utoipa::ToSchema;
|
||||
use web_push::{
|
||||
HyperWebPushClient, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder,
|
||||
};
|
||||
use futures::StreamExt;
|
||||
|
||||
use crate::db::Db;
|
||||
|
||||
@@ -20,17 +21,34 @@ pub struct PushKeys {
|
||||
pub auth: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct VapidConfig {
|
||||
pub private_key: String,
|
||||
pub public_key: String,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PushSubscriptionStore {
|
||||
db: Option<Db>,
|
||||
subscriptions: Arc<RwLock<Vec<PushSubscription>>>,
|
||||
vapid_config: VapidConfig,
|
||||
}
|
||||
|
||||
impl PushSubscriptionStore {
|
||||
pub fn new() -> Self {
|
||||
let private_key = std::env::var("VAPID_PRIVATE_KEY").expect("VAPID_PRIVATE_KEY must be set in .env");
|
||||
let public_key = std::env::var("VAPID_PUBLIC_KEY").expect("VAPID_PUBLIC_KEY must be set in .env");
|
||||
let email = std::env::var("VAPID_EMAIL").expect("VAPID_EMAIL must be set in .env");
|
||||
|
||||
Self {
|
||||
db: None,
|
||||
subscriptions: Arc::new(RwLock::new(Vec::new())),
|
||||
vapid_config: VapidConfig {
|
||||
private_key,
|
||||
public_key,
|
||||
email,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,9 +65,18 @@ impl PushSubscriptionStore {
|
||||
}
|
||||
tracing::info!("Loaded {} push subscriptions from database", subscriptions_vec.len());
|
||||
|
||||
let private_key = std::env::var("VAPID_PRIVATE_KEY").expect("VAPID_PRIVATE_KEY must be set in .env");
|
||||
let public_key = std::env::var("VAPID_PUBLIC_KEY").expect("VAPID_PUBLIC_KEY must be set in .env");
|
||||
let email = std::env::var("VAPID_EMAIL").expect("VAPID_EMAIL must be set in .env");
|
||||
|
||||
Ok(Self {
|
||||
db: Some(db.clone()),
|
||||
subscriptions: Arc::new(RwLock::new(subscriptions_vec)),
|
||||
vapid_config: VapidConfig {
|
||||
private_key,
|
||||
public_key,
|
||||
email,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -91,6 +118,10 @@ impl PushSubscriptionStore {
|
||||
pub async fn get_all_subscriptions(&self) -> Vec<PushSubscription> {
|
||||
self.subscriptions.read().await.clone()
|
||||
}
|
||||
|
||||
pub fn get_public_key(&self) -> &str {
|
||||
&self.vapid_config.public_key
|
||||
}
|
||||
}
|
||||
|
||||
/// Send push notification to all subscribed clients
|
||||
@@ -116,50 +147,68 @@ pub async fn send_push_notification(
|
||||
"tag": "vibetorrent"
|
||||
});
|
||||
|
||||
let client = HyperWebPushClient::new();
|
||||
let client = Arc::new(HyperWebPushClient::new());
|
||||
let vapid_config = store.vapid_config.clone();
|
||||
let payload_str = payload.to_string();
|
||||
|
||||
let vapid_private_key = std::env::var("VAPID_PRIVATE_KEY").expect("VAPID_PRIVATE_KEY must be set in .env");
|
||||
let vapid_email = std::env::var("VAPID_EMAIL").expect("VAPID_EMAIL must be set in .env");
|
||||
// Send notifications concurrently
|
||||
futures::stream::iter(subscriptions)
|
||||
.for_each_concurrent(10, |subscription| {
|
||||
let client = client.clone();
|
||||
let vapid_config = vapid_config.clone();
|
||||
let payload_str = payload_str.clone();
|
||||
|
||||
for subscription in subscriptions {
|
||||
let subscription_info = SubscriptionInfo {
|
||||
endpoint: subscription.endpoint.clone(),
|
||||
keys: web_push::SubscriptionKeys {
|
||||
p256dh: subscription.keys.p256dh.clone(),
|
||||
auth: subscription.keys.auth.clone(),
|
||||
},
|
||||
};
|
||||
async move {
|
||||
let subscription_info = SubscriptionInfo {
|
||||
endpoint: subscription.endpoint.clone(),
|
||||
keys: web_push::SubscriptionKeys {
|
||||
p256dh: subscription.keys.p256dh.clone(),
|
||||
auth: subscription.keys.auth.clone(),
|
||||
},
|
||||
};
|
||||
|
||||
let mut sig_builder = VapidSignatureBuilder::from_base64(
|
||||
&vapid_private_key,
|
||||
web_push::URL_SAFE_NO_PAD,
|
||||
&subscription_info,
|
||||
)?;
|
||||
let sig_res = VapidSignatureBuilder::from_base64(
|
||||
&vapid_config.private_key,
|
||||
web_push::URL_SAFE_NO_PAD,
|
||||
&subscription_info,
|
||||
);
|
||||
|
||||
sig_builder.add_claim("sub", vapid_email.as_str());
|
||||
sig_builder.add_claim("aud", subscription.endpoint.as_str());
|
||||
let signature = sig_builder.build()?;
|
||||
match sig_res {
|
||||
Ok(mut sig_builder) => {
|
||||
sig_builder.add_claim("sub", vapid_config.email.as_str());
|
||||
sig_builder.add_claim("aud", subscription.endpoint.as_str());
|
||||
|
||||
match sig_builder.build() {
|
||||
Ok(signature) => {
|
||||
let mut builder = WebPushMessageBuilder::new(&subscription_info);
|
||||
builder.set_vapid_signature(signature);
|
||||
builder.set_payload(web_push::ContentEncoding::Aes128Gcm, payload_str.as_bytes());
|
||||
|
||||
let mut builder = WebPushMessageBuilder::new(&subscription_info);
|
||||
builder.set_vapid_signature(signature);
|
||||
|
||||
let payload_str = payload.to_string();
|
||||
builder.set_payload(web_push::ContentEncoding::Aes128Gcm, payload_str.as_bytes());
|
||||
|
||||
match client.send(builder.build()?).await {
|
||||
Ok(_) => {
|
||||
tracing::debug!("Push notification sent to: {}", subscription.endpoint);
|
||||
match builder.build() {
|
||||
Ok(msg) => {
|
||||
match client.send(msg).await {
|
||||
Ok(_) => {
|
||||
tracing::debug!("Push notification sent to: {}", subscription.endpoint);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to send push notification to {}: {}", subscription.endpoint, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to build push message: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to build VAPID signature: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to create VAPID signature builder: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to send push notification: {}", e);
|
||||
// TODO: Remove invalid subscriptions
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_vapid_public_key() -> String {
|
||||
std::env::var("VAPID_PUBLIC_KEY").expect("VAPID_PUBLIC_KEY must be set in .env")
|
||||
}
|
||||
|
||||
@@ -2,14 +2,15 @@ use governor::clock::QuantaInstant;
|
||||
use governor::middleware::NoOpMiddleware;
|
||||
use tower_governor::governor::GovernorConfig;
|
||||
use tower_governor::governor::GovernorConfigBuilder;
|
||||
use tower_governor::key_extractor::GlobalKeyExtractor;
|
||||
use tower_governor::key_extractor::SmartIpKeyExtractor;
|
||||
|
||||
pub fn get_login_rate_limit_config() -> GovernorConfig<GlobalKeyExtractor, NoOpMiddleware<QuantaInstant>> {
|
||||
// GLOBAL TEST: Kim olursa olsun 2 denemeden sonra 30 saniye bloklanır.
|
||||
pub fn get_login_rate_limit_config() -> GovernorConfig<SmartIpKeyExtractor, NoOpMiddleware<QuantaInstant>> {
|
||||
// 5 yanlış denemeden sonra bloklanır.
|
||||
// Her yeni hak için 60 saniye (1 dakika) bekleme süresi.
|
||||
GovernorConfigBuilder::default()
|
||||
.key_extractor(GlobalKeyExtractor)
|
||||
.per_second(30)
|
||||
.burst_size(2)
|
||||
.key_extractor(SmartIpKeyExtractor)
|
||||
.per_second(60)
|
||||
.burst_size(5)
|
||||
.finish()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ RUN apt-get update && apt-get install -y \
|
||||
jq \
|
||||
# Needed for some crate compilations
|
||||
protobuf-compiler \
|
||||
# Install binaryen to have wasm-opt available system-wide
|
||||
binaryen \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 2. Install Node.js v20 (Manual install to support multi-arch cleanly)
|
||||
@@ -70,7 +72,7 @@ RUN . "$HOME/.cargo/env" && \
|
||||
ARCH=$(dpkg --print-architecture) && \
|
||||
if [ "$ARCH" = "amd64" ]; then TRUNK_ARCH="x86_64-unknown-linux-gnu"; \
|
||||
elif [ "$ARCH" = "arm64" ]; then TRUNK_ARCH="aarch64-unknown-linux-gnu"; fi && \
|
||||
wget -qO- "https://github.com/trunk-rs/trunk/releases/download/v0.21.5/trunk-$TRUNK_ARCH.tar.gz" | tar -xzf - -C /root/.cargo/bin/ && \
|
||||
wget -qO- "https://github.com/trunk-rs/trunk/releases/download/v0.21.14/trunk-$TRUNK_ARCH.tar.gz" | tar -xzf - -C /root/.cargo/bin/ && \
|
||||
chmod +x /root/.cargo/bin/trunk && \
|
||||
# Install wasm-bindgen-cli (Compiling from source to avoid glibc issues, doing it ONCE here)
|
||||
cargo install wasm-bindgen-cli --version 0.2.108
|
||||
|
||||
@@ -51,4 +51,4 @@ web-sys = { version = "0.3", features = [
|
||||
] }
|
||||
shared = { path = "../shared" }
|
||||
tailwind_fuse = "0.3.2"
|
||||
js-sys = "0.3.85"
|
||||
js-sys = "0.3.85"
|
||||
@@ -86,12 +86,15 @@
|
||||
id="app-loading"
|
||||
style="
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
font-family: sans-serif;
|
||||
"
|
||||
>
|
||||
<div
|
||||
id="app-loading-spinner"
|
||||
style="
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
@@ -102,6 +105,32 @@
|
||||
opacity: 0.5;
|
||||
"
|
||||
></div>
|
||||
<div
|
||||
id="app-loading-error"
|
||||
style="display: none; text-align: center; margin-top: 20px; padding: 0 20px"
|
||||
>
|
||||
<p style="color: #ef4444; font-weight: bold; margin-bottom: 8px">
|
||||
Uygulama yüklenemedi
|
||||
</p>
|
||||
<p style="font-size: 14px; opacity: 0.7">
|
||||
Bağlantınız yavaş olabilir veya bir sistem hatası oluşmuş olabilir.
|
||||
</p>
|
||||
<button
|
||||
onclick="location.reload()"
|
||||
style="
|
||||
margin-top: 16px;
|
||||
padding: 8px 16px;
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
"
|
||||
>
|
||||
Sayfayı Yenile
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
@keyframes spin {
|
||||
@@ -114,6 +143,34 @@
|
||||
display: none !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// App loading timeout handler
|
||||
(function () {
|
||||
var timeout = setTimeout(function () {
|
||||
if (!document.body.classList.contains("app-loaded")) {
|
||||
var spinner = document.getElementById("app-loading-spinner");
|
||||
var error = document.getElementById("app-loading-error");
|
||||
if (spinner) spinner.style.display = "none";
|
||||
if (error) error.style.display = "block";
|
||||
}
|
||||
}, 15000); // 15 seconds timeout
|
||||
|
||||
// Clean up timeout if app loads
|
||||
var observer = new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
if (
|
||||
mutation.attributeName === "class" &&
|
||||
document.body.classList.contains("app-loaded")
|
||||
) {
|
||||
clearTimeout(timeout);
|
||||
observer.disconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(document.body, { attributes: true });
|
||||
})();
|
||||
</script>
|
||||
|
||||
<!-- Service Worker Registration & PWA Setup -->
|
||||
<script>
|
||||
|
||||
@@ -41,6 +41,8 @@ pub fn Login() -> impl IntoView {
|
||||
logging::log!("Login successful, redirecting...");
|
||||
// Force a full reload to re-run auth checks in App.rs
|
||||
let _ = window().location().set_href("/");
|
||||
} else if resp.status() == 429 {
|
||||
set_error.set(Some("Çok fazla başarısız deneme yaptınız. Lütfen bir süre bekleyip tekrar deneyin.".to_string()));
|
||||
} else {
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
logging::error!("Login failed: {}", text);
|
||||
|
||||
@@ -143,6 +143,12 @@ pub fn provide_torrent_store() {
|
||||
|
||||
// Initialize SSE connection with auto-reconnect
|
||||
create_effect(move |_| {
|
||||
// Sadece kullanıcı giriş yapmışsa bağlantıyı başlat
|
||||
if user.get().is_none() {
|
||||
logging::log!("SSE: User not authenticated, skipping connection.");
|
||||
return;
|
||||
}
|
||||
|
||||
spawn_local(async move {
|
||||
let mut backoff_ms: u32 = 1000; // Start with 1 second
|
||||
let max_backoff_ms: u32 = 30000; // Max 30 seconds
|
||||
|
||||
Reference in New Issue
Block a user