refactor(server): apply fmt + lint recos

This commit is contained in:
Edouard Vanbelle
2026-04-14 10:51:48 +02:00
parent af23c56486
commit 62a7713af5
7 changed files with 67 additions and 29 deletions
+30 -9
View File
@@ -132,8 +132,12 @@ fn process_release(manifest_dir: &Path, static_dir: &Path, out_dir: &Path) {
let theme_init = let theme_init =
fs::read_to_string(static_dir.join("js/core/theme-init.js")).unwrap_or_default(); fs::read_to_string(static_dir.join("js/core/theme-init.js")).unwrap_or_default();
let theme_init_min = js_minify_safe(&theme_init); let theme_init_min = js_minify_safe(&theme_init);
let rewritten_index = let rewritten_index = rewrite_index_html(
rewrite_index_html(&index_html, &format!("/css/{css_name}"), &format!("/js/{js_name}"), &theme_init_min); &index_html,
&format!("/css/{css_name}"),
&format!("/js/{js_name}"),
&theme_init_min,
);
fs::write(dist_dir.join("index.html"), &rewritten_index).expect("write dist index.html"); fs::write(dist_dir.join("index.html"), &rewritten_index).expect("write dist index.html");
// ── 8. Minify locale JSONs ─────────────────────────────────────────────── // ── 8. Minify locale JSONs ───────────────────────────────────────────────
@@ -301,7 +305,11 @@ fn build_js_module_bundle(entry_scripts: &[String], static_dir: &Path) -> String
/// DFS post-order: push `file` to `order` after all its imports. /// DFS post-order: push `file` to `order` after all its imports.
/// Marks files as seen before recursing to break circular dependencies. /// Marks files as seen before recursing to break circular dependencies.
fn collect_module_deps(file: &Path, order: &mut Vec<PathBuf>, seen: &mut std::collections::HashSet<PathBuf>) { fn collect_module_deps(
file: &Path,
order: &mut Vec<PathBuf>,
seen: &mut std::collections::HashSet<PathBuf>,
) {
let canonical = match file.canonicalize() { let canonical = match file.canonicalize() {
Ok(p) => p, Ok(p) => p,
Err(_) => { Err(_) => {
@@ -437,9 +445,8 @@ fn strip_esm_syntax(source: &str) -> String {
// ── export default expr ──────────────────────────────────────────────── // ── export default expr ────────────────────────────────────────────────
// Rare in our codebase; keep the value as a named variable. // Rare in our codebase; keep the value as a named variable.
if t.starts_with("export default ") { if let Some(rhs) = t.strip_prefix("export default ") {
let indent = &line[..line.len() - line.trim_start().len()]; let indent = &line[..line.len() - line.trim_start().len()];
let rhs = &t["export default ".len()..];
out.push_str(&format!("{indent}const _default = {rhs}")); out.push_str(&format!("{indent}const _default = {rhs}"));
out.push('\n'); out.push('\n');
continue; continue;
@@ -468,7 +475,11 @@ fn try_strip_export_prefix(line: &str) -> Option<String> {
if t.starts_with(prefix) { if t.starts_with(prefix) {
let indent_len = line.len() - line.trim_start().len(); let indent_len = line.len() - line.trim_start().len();
// Remove "export " (7 chars) right after the indent // Remove "export " (7 chars) right after the indent
return Some(format!("{}{}", &line[..indent_len], &line[indent_len + 7..])); return Some(format!(
"{}{}",
&line[..indent_len],
&line[indent_len + 7..]
));
} }
} }
None None
@@ -534,7 +545,11 @@ fn js_minify(source: &str, is_module: bool) -> Result<String, String> {
use oxc_span::SourceType; use oxc_span::SourceType;
let allocator = Allocator::default(); let allocator = Allocator::default();
let source_type = if is_module { SourceType::mjs() } else { SourceType::cjs() }; let source_type = if is_module {
SourceType::mjs()
} else {
SourceType::cjs()
};
let ret = Parser::new(&allocator, source, source_type).parse(); let ret = Parser::new(&allocator, source, source_type).parse();
if !ret.errors.is_empty() { if !ret.errors.is_empty() {
@@ -556,7 +571,11 @@ fn js_minify(source: &str, is_module: bool) -> Result<String, String> {
let output = Codegen::new() let output = Codegen::new()
.with_options(CodegenOptions { .with_options(CodegenOptions {
minify: true, minify: true,
comments: CommentOptions { normal: false, jsdoc: false, ..CommentOptions::default() }, comments: CommentOptions {
normal: false,
jsdoc: false,
..CommentOptions::default()
},
..Default::default() ..Default::default()
}) })
.build(&program); .build(&program);
@@ -670,7 +689,9 @@ fn rewrite_index_html(html: &str, css_path: &str, js_path: &str, inline_theme_js
// ── Replace all type="module" scripts with single bundle ───────────── // ── Replace all type="module" scripts with single bundle ─────────────
if t.starts_with("<script") && t.contains("type=\"module\"") && t.contains("src=\"") { if t.starts_with("<script") && t.contains("type=\"module\"") && t.contains("src=\"") {
if !js_done { if !js_done {
out.push(format!(" <script defer type=\"module\" src=\"{js_path}\"></script>")); out.push(format!(
" <script defer type=\"module\" src=\"{js_path}\"></script>"
));
js_done = true; js_done = true;
} }
continue; continue;
@@ -60,9 +60,7 @@ impl AudioMetadataService {
/// ///
/// All I/O is synchronous (id3 + mp3_duration crates), so this MUST /// All I/O is synchronous (id3 + mp3_duration crates), so this MUST
/// only be called inside `spawn_blocking`. /// only be called inside `spawn_blocking`.
fn extract_metadata_blocking( fn extract_metadata_blocking(file_path: &Path) -> Option<AudioMetadataFields> {
file_path: &Path,
) -> Option<AudioMetadataFields> {
if !file_path.exists() { if !file_path.exists() {
warn!("File does not exist: {:?}", file_path); warn!("File does not exist: {:?}", file_path);
return None; return None;
@@ -114,13 +112,14 @@ impl AudioMetadataService {
// ── Sync I/O on the blocking thread pool (never stalls Tokio workers) ── // ── Sync I/O on the blocking thread pool (never stalls Tokio workers) ──
let path = file_path.to_path_buf(); let path = file_path.to_path_buf();
let metadata = tokio::task::spawn_blocking(move || { let metadata = tokio::task::spawn_blocking(move || Self::extract_metadata_blocking(&path))
Self::extract_metadata_blocking(&path) .await
}) .map_err(|e| {
.await DomainError::internal_error(
.map_err(|e| { "AudioMetadataService",
DomainError::internal_error("AudioMetadataService", format!("spawn_blocking join error: {e}")) format!("spawn_blocking join error: {e}"),
})?; )
})?;
let Some(m) = metadata else { let Some(m) = metadata else {
return Ok(()); return Ok(());
+5 -1
View File
@@ -717,7 +717,11 @@ impl DedupService {
// Also clean up any thumbnail files for these blob hashes // Also clean up any thumbnail files for these blob hashes
// (thumbnails are keyed by blob_hash and live under // (thumbnails are keyed by blob_hash and live under
// storage_root/.thumbnails/{icon,preview,large}/{hash}.jpg). // storage_root/.thumbnails/{icon,preview,large}/{hash}.jpg).
let thumbnails_root = self.blob_root.parent().unwrap_or(&self.blob_root).join(".thumbnails"); let thumbnails_root = self
.blob_root
.parent()
.unwrap_or(&self.blob_root)
.join(".thumbnails");
for (hash, size) in &batch { for (hash, size) in &batch {
let blob_path = self.blob_path(hash); let blob_path = self.blob_path(hash);
if let Err(e) = fs::remove_file(&blob_path).await { if let Err(e) = fs::remove_file(&blob_path).await {
@@ -40,7 +40,12 @@ async fn generate_thumbnail_from_blob_path() {
// The key assertion: the service can read from a blob path (not a logical path) // The key assertion: the service can read from a blob path (not a logical path)
let result = svc let result = svc
.get_thumbnail("test-file-id", "ab1234567890", ThumbnailSize::Icon, &blob_path) .get_thumbnail(
"test-file-id",
"ab1234567890",
ThumbnailSize::Icon,
&blob_path,
)
.await; .await;
let thumb_bytes = result.expect("thumbnail generation should succeed from blob path"); let thumb_bytes = result.expect("thumbnail generation should succeed from blob path");
@@ -67,7 +72,12 @@ async fn generate_thumbnail_nonexistent_path_returns_error() {
let bad_path = tmp.path().join("does-not-exist.png"); let bad_path = tmp.path().join("does-not-exist.png");
let result = svc let result = svc
.get_thumbnail("missing-id", "nonexistent-hash", ThumbnailSize::Icon, &bad_path) .get_thumbnail(
"missing-id",
"nonexistent-hash",
ThumbnailSize::Icon,
&bad_path,
)
.await; .await;
assert!(result.is_err(), "should fail for nonexistent file"); assert!(result.is_err(), "should fail for nonexistent file");
+5 -1
View File
@@ -746,7 +746,11 @@ impl FileHandler {
tokio::spawn(async move { tokio::spawn(async move {
tracing::info!("🖼️ Generating thumbnails for: {}", file_id); tracing::info!("🖼️ Generating thumbnails for: {}", file_id);
thumbnail_service.generate_all_sizes_background(file_id, blob_hash_owned, file_path); thumbnail_service.generate_all_sizes_background(
file_id,
blob_hash_owned,
file_path,
);
}); });
} }
+5 -2
View File
@@ -16,7 +16,10 @@ use crate::application::services::share_service::ShareService;
use crate::{ use crate::{
application::{ application::{
dtos::share_dto::{CreateShareDto, UpdateShareDto}, dtos::share_dto::{CreateShareDto, UpdateShareDto},
ports::{file_ports::{FileRetrievalUseCase, OptimizedFileContent}, share_ports::ShareUseCase}, ports::{
file_ports::{FileRetrievalUseCase, OptimizedFileContent},
share_ports::ShareUseCase,
},
}, },
common::{di::AppState, errors::ErrorKind}, common::{di::AppState, errors::ErrorKind},
domain::entities::share::ShareItemType, domain::entities::share::ShareItemType,
@@ -290,7 +293,7 @@ pub async fn download_shared_file(
"Sharing is disabled", "Sharing is disabled",
"Disabled", "Disabled",
) )
.into_response() .into_response();
} }
}; };
+1 -4
View File
@@ -243,10 +243,7 @@ pub async fn auth_middleware(
if request.uri().path().starts_with("/webdav") { if request.uri().path().starts_with("/webdav") {
return Ok(Response::builder() return Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED) .status(StatusCode::UNAUTHORIZED)
.header( .header(header::WWW_AUTHENTICATE, r#"Basic realm="OxiCloud""#)
header::WWW_AUTHENTICATE,
r#"Basic realm="OxiCloud""#,
)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8") .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(axum::body::Body::from( .body(axum::body::Body::from(
"Invalid username or app password", "Invalid username or app password",