641 lines
21 KiB
Rust
641 lines
21 KiB
Rust
use anyhow::{Context, Result};
|
|
use std::path::{Path, PathBuf};
|
|
|
|
pub struct InitOptions {
|
|
pub skip_db: bool,
|
|
pub skip_deps: bool,
|
|
pub force: bool,
|
|
pub scan_dir: Option<PathBuf>,
|
|
pub quiet: bool,
|
|
}
|
|
|
|
impl Default for InitOptions {
|
|
fn default() -> Self {
|
|
Self {
|
|
skip_db: false,
|
|
skip_deps: false,
|
|
force: false,
|
|
scan_dir: None,
|
|
quiet: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn log(opts: &InitOptions, msg: &str) {
|
|
if !opts.quiet {
|
|
println!("{}", msg);
|
|
}
|
|
}
|
|
|
|
fn step(opts: &InitOptions, msg: &str) {
|
|
if !opts.quiet {
|
|
println!(" {}", msg);
|
|
}
|
|
}
|
|
|
|
fn warn(opts: &InitOptions, msg: &str) {
|
|
if !opts.quiet {
|
|
println!(" ⚠️ {}", msg);
|
|
}
|
|
}
|
|
|
|
fn ok(opts: &InitOptions, msg: &str) {
|
|
if !opts.quiet {
|
|
println!(" ✅ {}", msg);
|
|
}
|
|
}
|
|
|
|
/// Main init entry point
|
|
pub async fn run(opts: InitOptions) -> Result<()> {
|
|
log(&opts, "🚀 momentry init v1.0.0");
|
|
log(&opts, "");
|
|
|
|
// Step 1: Resolve install root
|
|
let root = resolve_install_root()?;
|
|
log(&opts, &format!("📍 安裝根目錄: {}", root.display()));
|
|
log(&opts, "");
|
|
|
|
// Step 2: Fix config/.env
|
|
let env_map = fix_env_file(&root, &opts)?;
|
|
log(&opts, "");
|
|
|
|
// Step 3: Create directories
|
|
create_directories(&root, &opts)?;
|
|
log(&opts, "");
|
|
|
|
// Step 4: Validate JSON configs
|
|
validate_json_configs(&root, &opts)?;
|
|
log(&opts, "");
|
|
|
|
// Step 5: Dependency preflight
|
|
if !opts.skip_deps {
|
|
check_dependencies(&env_map, &opts).await;
|
|
log(&opts, "");
|
|
}
|
|
|
|
// Step 6: Database init
|
|
if !opts.skip_db {
|
|
init_database(&env_map, &opts).await;
|
|
log(&opts, "");
|
|
}
|
|
|
|
// Step 7: Verify scan
|
|
verify_scan(&root, &env_map, &opts);
|
|
log(&opts, "");
|
|
|
|
log(&opts, "🎉 初始化完成!");
|
|
log(&opts, " 啟動服務: ./scripts/start_all.sh");
|
|
Ok(())
|
|
}
|
|
|
|
fn resolve_install_root() -> Result<PathBuf> {
|
|
let exe = std::env::current_exe().context("cannot determine exe path")?;
|
|
exe.parent()
|
|
.and_then(|p| p.parent())
|
|
.map(|p| p.to_path_buf())
|
|
.context("cannot determine install root (expected <root>/bin/momentry)")
|
|
}
|
|
|
|
// ─── Step 2: .env ───────────────────────────────────────────────
|
|
|
|
/// Keys that MUST exist with absolute paths
|
|
fn required_env_keys(root: &Path) -> Vec<(String, String)> {
|
|
let r = root.display().to_string();
|
|
vec![
|
|
("MOMENTRY_ENV_FILE".into(), format!("{}/config/.env", r)),
|
|
("MOMENTRY_SFTP_ROOT".into(), format!("{}/var/sftpgo/data/demo", r)),
|
|
("MOMENTRY_STORAGE_ROOT".into(), format!("{}/var/sftpgo/data", r)),
|
|
("MOMENTRY_OUTPUT_DIR".into(), format!("{}/var/output", r)),
|
|
("MOMENTRY_DATA_DIR".into(), format!("{}/data", r)),
|
|
("MOMENTRY_PROCESSORS_DIR".into(), format!("{}/processors", r)),
|
|
("MOMENTRY_LOG_LEVEL".into(), "info".into()),
|
|
]
|
|
}
|
|
|
|
fn generate_api_key() -> String {
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
let t = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
|
|
let pid = std::process::id();
|
|
let hash = format!("{:x}{}", t, pid);
|
|
let padded: String = hash.chars().chain(std::iter::repeat('0')).take(64).collect();
|
|
format!("muser_{}", padded)
|
|
}
|
|
|
|
fn fix_env_file(root: &Path, opts: &InitOptions) -> Result<std::collections::HashMap<String, String>> {
|
|
log(opts, "📝 config/.env:");
|
|
|
|
let env_path = root.join("config").join(".env");
|
|
let example_path = root.join("config").join(".env.example");
|
|
|
|
let mut env_map = std::collections::HashMap::new();
|
|
let source_path = if env_path.exists() {
|
|
env_path.clone()
|
|
} else if example_path.exists() {
|
|
example_path.clone()
|
|
} else {
|
|
warn(opts, "無 .env 和 .env.example,將生成最小配置");
|
|
PathBuf::new()
|
|
};
|
|
|
|
if !source_path.as_os_str().is_empty() {
|
|
let content = std::fs::read_to_string(&source_path)
|
|
.context("cannot read env file")?;
|
|
for line in content.lines() {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
if let Some((key, value)) = line.split_once('=') {
|
|
env_map.insert(key.trim().to_string(), value.trim().to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
if !env_path.exists() {
|
|
if example_path.exists() {
|
|
std::fs::copy(&example_path, &env_path)
|
|
.context("cannot create config/.env")?;
|
|
step(opts, "從 .env.example 創建 config/.env");
|
|
} else {
|
|
std::fs::create_dir_all(root.join("config"))
|
|
.context("cannot create config dir")?;
|
|
std::fs::write(&env_path, "")
|
|
.context("cannot create config/.env")?;
|
|
step(opts, "創建空白 config/.env");
|
|
}
|
|
}
|
|
|
|
let root_str = root.display().to_string();
|
|
let mut changed = false;
|
|
for (_k, v) in env_map.iter_mut() {
|
|
if v.contains("@ROOT@") {
|
|
*v = v.replace("@ROOT@", &root_str);
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
let mut added = Vec::new();
|
|
for (key, default_val) in required_env_keys(root) {
|
|
let needs_set = match env_map.get(&key) {
|
|
None => true,
|
|
Some(v) => {
|
|
v.is_empty()
|
|
|| v.contains("@ROOT@")
|
|
|| (key == "MOMENTRY_API_KEY" && (v.is_empty() || v.contains("your_key")))
|
|
}
|
|
};
|
|
if needs_set {
|
|
let val = if key == "MOMENTRY_API_KEY" && env_map.get(&key).map_or(true, |v| v.is_empty()) {
|
|
generate_api_key()
|
|
} else {
|
|
default_val
|
|
};
|
|
env_map.insert(key.clone(), val.clone());
|
|
added.push(format!("+ {}={}", key, val));
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if env_map.get("FFMPEG_PATH").map_or(true, |v| v.is_empty()) {
|
|
if let Some(ffmpeg) = find_ffmpeg() {
|
|
env_map.insert("FFMPEG_PATH".into(), ffmpeg.display().to_string());
|
|
added.push(format!("+ FFMPEG_PATH={}", ffmpeg.display()));
|
|
changed = true;
|
|
}
|
|
}
|
|
if env_map.get("WHISPER_MODEL_PATH").map_or(true, |v| v.is_empty() || !Path::new(v).exists()) {
|
|
if let Some(model) = find_whisper_model(root) {
|
|
env_map.insert("WHISPER_MODEL_PATH".into(), model.display().to_string());
|
|
added.push(format!("+ WHISPER_MODEL_PATH={}", model.display()));
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if changed && !opts.force {
|
|
let mut content = std::fs::read_to_string(&env_path).unwrap_or_default();
|
|
for line in &added {
|
|
let kv = line.trim_start_matches("+ ");
|
|
if !content.contains(&format!("\n{}", kv)) && !content.contains(&format!("^{}", kv)) {
|
|
if !content.ends_with('\n') {
|
|
content.push('\n');
|
|
}
|
|
content.push_str(kv);
|
|
content.push('\n');
|
|
}
|
|
}
|
|
let content = content.replace("@ROOT@", &root_str);
|
|
std::fs::write(&env_path, content).context("cannot write config/.env")?;
|
|
} else if changed && opts.force {
|
|
let mut content = String::new();
|
|
content.push_str("# Generated by momentry init\n");
|
|
let mut keys: Vec<_> = env_map.iter().collect();
|
|
keys.sort_by(|a, b| a.0.cmp(b.0));
|
|
for (k, v) in keys {
|
|
content.push_str(&format!("{}={}\n", k, v));
|
|
}
|
|
std::fs::write(&env_path, content).context("cannot write config/.env")?;
|
|
}
|
|
|
|
if added.is_empty() {
|
|
ok(opts, "config/.env 完整(無需修改)");
|
|
} else {
|
|
for line in &added {
|
|
step(opts, line);
|
|
}
|
|
}
|
|
|
|
Ok(env_map)
|
|
}
|
|
|
|
fn find_ffmpeg() -> Option<PathBuf> {
|
|
let candidates = [
|
|
"/opt/homebrew/bin/ffmpeg",
|
|
"/usr/local/bin/ffmpeg",
|
|
"/usr/bin/ffmpeg",
|
|
];
|
|
candidates.iter().map(PathBuf::from).find(|p| p.exists())
|
|
}
|
|
|
|
fn find_whisper_model(root: &Path) -> Option<PathBuf> {
|
|
let candidates = [
|
|
root.join("tools/models/small.pt"),
|
|
root.join("tools/models/whisper-small-mlx/small.pt"),
|
|
root.join("tools/models/base.pt"),
|
|
];
|
|
candidates.into_iter().find(|p| p.exists())
|
|
}
|
|
|
|
// ─── Step 3: Directories ────────────────────────────────────────
|
|
|
|
fn create_directories(root: &Path, opts: &InitOptions) -> Result<()> {
|
|
log(opts, "📁 建立目錄:");
|
|
|
|
let dirs = [
|
|
("var/sftpgo/data/demo", "掃描根 (files/scan)"),
|
|
("var/sftpgo/data", "存儲根"),
|
|
("var/output", "處理輸出"),
|
|
("var/backup", "備份"),
|
|
("logs", "日誌"),
|
|
("thumbnails", "縮圖"),
|
|
("data", "數據"),
|
|
];
|
|
|
|
for (dir, desc) in &dirs {
|
|
let path = root.join(dir);
|
|
if !path.exists() {
|
|
std::fs::create_dir_all(&path)
|
|
.with_context(|| format!("cannot create {}", path.display()))?;
|
|
step(opts, &format!("{} ({})", dir, desc));
|
|
} else {
|
|
ok(opts, &format!("{} (已存在)", dir));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// ─── Step 4: JSON configs ───────────────────────────────────────
|
|
|
|
fn validate_json_configs(root: &Path, opts: &InitOptions) -> Result<()> {
|
|
log(opts, "⚙️ 配置文件:");
|
|
|
|
let admin_path = root.join("config").join("admin_config.json");
|
|
if admin_path.exists() {
|
|
let content = std::fs::read_to_string(&admin_path)
|
|
.context("cannot read admin_config.json")?;
|
|
match serde_json::from_str::<serde_json::Value>(&content) {
|
|
Ok(_) => {
|
|
let is_stub = content.len() < 200;
|
|
if is_stub {
|
|
warn(opts, "admin_config.json 是最小 stub,建議替換完整配置");
|
|
} else {
|
|
ok(opts, "config/admin_config.json");
|
|
}
|
|
}
|
|
Err(e) => {
|
|
warn(opts, &format!("admin_config.json JSON 解析失敗: {}", e));
|
|
}
|
|
}
|
|
} else {
|
|
let default_config = serde_json::json!({
|
|
"filter_config": {
|
|
"face": { "min_confidence": 0.5, "min_size": 30 }
|
|
},
|
|
"llm_config": {
|
|
"chat": {
|
|
"model": "gemma-4-12b-it",
|
|
"timeout": 30,
|
|
"url": "http://localhost:8080/v1/chat/completions"
|
|
},
|
|
"summary": {
|
|
"model": "gemma-4-12b-it",
|
|
"timeout": 60,
|
|
"url": "http://localhost:8080/v1/chat/completions"
|
|
}
|
|
},
|
|
"processor_config": {}
|
|
});
|
|
std::fs::write(&admin_path, serde_json::to_string_pretty(&default_config)?)
|
|
.context("cannot write admin_config.json")?;
|
|
step(opts, "config/admin_config.json (生成默認配置)");
|
|
}
|
|
|
|
let tools_path = root.join("config").join("processor_tools_v3.json");
|
|
if tools_path.exists() {
|
|
ok(opts, "config/processor_tools_v3.json");
|
|
} else {
|
|
warn(opts, "config/processor_tools_v3.json 不存在 — 請從安裝包複製");
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
// ─── Step 5: Dependencies ───────────────────────────────────────
|
|
|
|
async fn check_dependencies(env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
|
|
log(opts, "🔍 服務預檢:");
|
|
|
|
let db_url = env.get("DATABASE_URL").cloned()
|
|
.unwrap_or_else(|| "postgres://localhost:5432/momentry".into());
|
|
match check_tcp(&db_url).await {
|
|
Ok(_) => ok(opts, "PostgreSQL"),
|
|
Err(e) => warn(opts, &format!("PostgreSQL: {}", e)),
|
|
}
|
|
|
|
let redis_url = env.get("REDIS_URL").cloned()
|
|
.unwrap_or_else(|| crate::core::config::REDIS_URL.clone());
|
|
match check_redis(&redis_url).await {
|
|
Ok(_) => ok(opts, "Redis"),
|
|
Err(e) => warn(opts, &format!("Redis: {}", e)),
|
|
}
|
|
|
|
let qdrant_url = env.get("QDRANT_URL").cloned()
|
|
.unwrap_or_else(|| "http://localhost:6333".into());
|
|
match check_http(&qdrant_url).await {
|
|
Ok(_) => ok(opts, "Qdrant"),
|
|
Err(e) => warn(opts, &format!("Qdrant: {}", e)),
|
|
}
|
|
|
|
let ffmpeg = env.get("FFMPEG_PATH").cloned()
|
|
.unwrap_or_else(|| "/opt/homebrew/bin".into());
|
|
let ffmpeg_bin = Path::new(&ffmpeg).join("ffmpeg");
|
|
if ffmpeg_bin.exists() || which_exists("ffmpeg") {
|
|
ok(opts, "FFmpeg");
|
|
} else {
|
|
warn(opts, "FFmpeg not found");
|
|
}
|
|
|
|
if let Some(model) = env.get("WHISPER_MODEL_PATH") {
|
|
if Path::new(model).exists() {
|
|
let size = std::fs::metadata(model).map(|m| m.len()).unwrap_or(0);
|
|
if size > 100_000_000 {
|
|
ok(opts, &format!("Whisper model ({}MB)", size / 1_000_000));
|
|
} else {
|
|
warn(opts, &format!("Whisper model too small ({} bytes)", size));
|
|
}
|
|
} else {
|
|
warn(opts, &format!("Whisper model not found: {}", model));
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn check_tcp(url: &str) -> Result<()> {
|
|
let addr = url
|
|
.trim_start_matches("postgres://")
|
|
.trim_start_matches("postgresql://")
|
|
.split('/')
|
|
.next()
|
|
.unwrap_or("localhost:5432");
|
|
let addr = if addr.contains(':') {
|
|
addr.to_string()
|
|
} else {
|
|
format!("{}:5432", addr)
|
|
};
|
|
tokio::net::TcpStream::connect(&addr)
|
|
.await
|
|
.with_context(|| format!("cannot connect to {}", addr))?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn check_redis(url: &str) -> Result<()> {
|
|
let addr = url
|
|
.trim_start_matches("redis://")
|
|
.split('@')
|
|
.last()
|
|
.unwrap_or("localhost:6379");
|
|
let addr = if addr.contains(':') {
|
|
addr.to_string()
|
|
} else {
|
|
format!("{}:6379", addr)
|
|
};
|
|
let mut stream = tokio::net::TcpStream::connect(&addr)
|
|
.await
|
|
.with_context(|| format!("cannot connect to {}", addr))?;
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
stream.write_all(b"PING\r\n").await?;
|
|
let mut buf = [0u8; 16];
|
|
let n = stream.read(&mut buf).await?;
|
|
let resp = String::from_utf8_lossy(&buf[..n]);
|
|
if resp.contains("PONG") {
|
|
Ok(())
|
|
} else {
|
|
anyhow::bail!("unexpected response: {}", resp)
|
|
}
|
|
}
|
|
|
|
async fn check_http(url: &str) -> Result<()> {
|
|
let client = reqwest::Client::builder()
|
|
.timeout(std::time::Duration::from_secs(5))
|
|
.build()?;
|
|
let resp = client.get(format!("{}/collections", url)).send().await?;
|
|
if resp.status().is_success() {
|
|
Ok(())
|
|
} else {
|
|
anyhow::bail!("HTTP {}", resp.status())
|
|
}
|
|
}
|
|
|
|
fn which_exists(cmd: &str) -> bool {
|
|
std::process::Command::new("which")
|
|
.arg(cmd)
|
|
.output()
|
|
.map(|o| o.status.success())
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
// ─── Step 6: Database ───────────────────────────────────────────
|
|
|
|
async fn init_database(env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
|
|
log(opts, "🗄️ 數據庫:");
|
|
|
|
let db_url = match env.get("DATABASE_URL") {
|
|
Some(u) => u.clone(),
|
|
None => {
|
|
warn(opts, "DATABASE_URL 未設定,跳過");
|
|
return;
|
|
}
|
|
};
|
|
|
|
match try_init_db(&db_url, opts).await {
|
|
Ok(msg) => ok(opts, &msg),
|
|
Err(e) => {
|
|
warn(opts, &format!("DB 初始化失敗: {}", e));
|
|
step(opts, "可手動執行: psql -d momentry -f release/migrate_*.sql");
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn try_init_db(db_url: &str, _opts: &InitOptions) -> Result<String> {
|
|
let db_name = db_url
|
|
.rsplit('/')
|
|
.next()
|
|
.unwrap_or("momentry")
|
|
.split('?')
|
|
.next()
|
|
.unwrap_or("momentry");
|
|
|
|
let output = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-c", "SELECT 1"])
|
|
.output()
|
|
.context("psql not found in PATH")?;
|
|
|
|
if !output.status.success() {
|
|
let user_output = std::process::Command::new("psql")
|
|
.args(["-d", "postgres", "-c", &format!("CREATE DATABASE {}", db_name)])
|
|
.output();
|
|
match user_output {
|
|
Ok(o) if o.status.success() => {
|
|
let retry = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-c", "SELECT 1"])
|
|
.output()?;
|
|
if !retry.status.success() {
|
|
anyhow::bail!("cannot connect to database {}", db_name);
|
|
}
|
|
}
|
|
_ => anyhow::bail!("cannot connect to database {}", db_name),
|
|
}
|
|
}
|
|
|
|
let _ = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-c", "CREATE SCHEMA IF NOT EXISTS public"])
|
|
.output();
|
|
|
|
let _ = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-c",
|
|
"CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, checksum TEXT, duration_ms INT, applied_at TIMESTAMPTZ DEFAULT now())"])
|
|
.output();
|
|
|
|
let exe = std::env::current_exe()?;
|
|
let install_root = exe.parent().and_then(|p| p.parent())
|
|
.context("cannot find install root")?;
|
|
let release_dir = install_root.join("release");
|
|
|
|
let mut applied = 0;
|
|
let mut skipped = 0;
|
|
|
|
if release_dir.exists() {
|
|
let mut migrations: Vec<_> = std::fs::read_dir(&release_dir)?
|
|
.filter_map(|e| e.ok())
|
|
.map(|e| e.path())
|
|
.filter(|p| p.extension().map_or(false, |ext| ext == "sql"))
|
|
.filter(|p| {
|
|
p.file_name()
|
|
.map_or(false, |n| n.to_string_lossy().starts_with("migrate_"))
|
|
})
|
|
.collect();
|
|
migrations.sort();
|
|
|
|
for mig_path in migrations {
|
|
let mig_name = mig_path.file_name()
|
|
.map(|n| n.to_string_lossy().to_string())
|
|
.unwrap_or_default();
|
|
|
|
let check = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-t", "-c",
|
|
&format!("SELECT COUNT(*) FROM schema_migrations WHERE filename='{}'", mig_name)])
|
|
.output();
|
|
let already = check.ok()
|
|
.and_then(|o| String::from_utf8(o.stdout).ok())
|
|
.map(|s| s.trim().parse::<i64>().unwrap_or(0))
|
|
.unwrap_or(0) > 0;
|
|
|
|
if already {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
let sql = std::fs::read_to_string(&mig_path)?;
|
|
let start = std::time::Instant::now();
|
|
let result = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-f", &mig_path.display().to_string()])
|
|
.output();
|
|
let duration = start.elapsed().as_millis() as i32;
|
|
|
|
match result {
|
|
Ok(o) if o.status.success() => {
|
|
let _ = std::process::Command::new("psql")
|
|
.args(["-d", db_name, "-c",
|
|
&format!("INSERT INTO schema_migrations (filename, duration_ms) VALUES ('{}', {}) ON CONFLICT (filename) DO UPDATE SET duration_ms=EXCLUDED.duration_ms", mig_name, duration)])
|
|
.output();
|
|
applied += 1;
|
|
}
|
|
Ok(o) => {
|
|
let stderr = String::from_utf8_lossy(&o.stderr);
|
|
let _ = stderr;
|
|
}
|
|
Err(_) => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(format!("Schema public, migrations: {} applied, {} skipped", applied, skipped))
|
|
}
|
|
|
|
// ─── Step 7: Verify scan ────────────────────────────────────────
|
|
|
|
fn verify_scan(root: &Path, env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
|
|
log(opts, "✅ 驗證:");
|
|
|
|
let scan_dir = env.get("MOMENTRY_SFTP_ROOT")
|
|
.map(PathBuf::from)
|
|
.unwrap_or_else(|| root.join("var/sftpgo/data/demo"));
|
|
|
|
if scan_dir.exists() {
|
|
let count = count_media_files(&scan_dir);
|
|
ok(opts, &format!("掃描根: {} ({} files)", scan_dir.display(), count));
|
|
if count > 0 {
|
|
ok(opts, "files/scan 可用");
|
|
} else {
|
|
warn(opts, "掃描目錄為空(上傳文件後 files/scan 將返回結果)");
|
|
}
|
|
} else {
|
|
warn(opts, &format!("掃描根不存在: {}", scan_dir.display()));
|
|
}
|
|
|
|
if let Some(api_key) = env.get("MOMENTRY_API_KEY") {
|
|
if !api_key.is_empty() {
|
|
log(opts, "");
|
|
log(opts, " 驗證命令:");
|
|
log(opts, &format!(
|
|
" curl -H \"X-API-Key: {}\" http://localhost:3002/api/v1/files/scan?page_size=5",
|
|
api_key
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
fn count_media_files(dir: &Path) -> usize {
|
|
const EXTS: &[&str] = &["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"];
|
|
let mut count = 0;
|
|
if let Ok(entries) = std::fs::read_dir(dir) {
|
|
for entry in entries.flatten() {
|
|
if entry.path().is_dir() {
|
|
count += count_media_files(&entry.path());
|
|
} else if let Some(ext) = entry.path().extension() {
|
|
if EXTS.contains(&ext.to_string_lossy().to_lowercase().as_str()) {
|
|
count += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
count
|
|
} |