1use crate::*;
2
3pub fn file_link(path: &str, zip: bool) -> Value {
4 let root = env("SNOWGLOBE_STORE_ROOT", "/srv");
5 let Some(relative) = std::path::Path::new(path).strip_prefix(&root).ok() else {
6 return Value::Null;
7 };
8 let path = relative
9 .components()
10 .map(|c| encoded(&c.as_os_str().to_string_lossy()))
11 .collect::<Vec<_>>()
12 .join("/");
13 let Ok(files) = std::env::var("SNOWGLOBE_FILES_URL") else {
14 return Value::Null;
15 };
16 json!(format!("{files}/{path}{}", if zip { "?zip" } else { "" }))
17}
18fn qbt_link(path: &str, zip: bool) -> Value {
19 file_link(
20 &if path == "/data/media" || path.starts_with("/data/media/") {
21 format!("/srv/clover/Media{}", &path[11..])
22 } else {
23 path.into()
24 },
25 zip,
26 )
27}
28async fn qbt(app: Arc<App>, route: &str, form: Option<Value>) -> Result<Value> {
29 let base = telemetry::endpoint(app.clone(), "qbittorrent")
30 .await
31 .map_err(|_| Error::new(503, "qBittorrent is unavailable. Check its service status."))?;
32 let mut request = if form.is_some() {
33 app.request(Method::POST, &format!("{base}/api/v2/{route}"))?
34 } else {
35 app.request(Method::GET, &format!("{base}/api/v2/{route}"))?
36 };
37 if let Some(form) = form {
38 request = request.form(&form);
39 }
40 let response = request.send().await?;
41 if !response.status().is_success() {
42 return Err(Error::new(
43 502,
44 format!(
45 "qBittorrent refused the request ({}). Retry from its page.",
46 response.status()
47 ),
48 ));
49 }
50 if response
51 .headers()
52 .get("content-type")
53 .and_then(|h| h.to_str().ok())
54 .is_some_and(|h| h.contains("json"))
55 {
56 Ok(response.json().await?)
57 } else {
58 Ok(json!(response.text().await?))
59 }
60}
61async fn seed_state(app: Arc<App>) -> Result<Arc<Document>> {
62 let state = app.clone();
63 app.cache
64 .get(
65 "seed-state".into(),
66 Duration::from_secs(5),
67 move || async move {
68 let (data, prefs) = tokio::try_join!(
69 qbt(state.clone(), "sync/maindata?rid=0", None),
70 qbt(state.clone(), "app/preferences", None)
71 )?;
72 let mut value = data["server_state"].clone();
73 if let (Some(value), Some(prefs)) = (value.as_object_mut(), prefs.as_object()) {
74 value.extend(prefs.clone());
75 }
76 let t = (now() / 5.0).floor() * 5.0;
77 let mut samples = state.seed_samples.lock().unwrap();
78 if samples.last().is_none_or(|s| s["t"] != t) {
79 samples.push(
80 json!({"t":t,"down":value["dl_info_speed"],"up":value["up_info_speed"]}),
81 );
82 }
83 samples.retain(|s| number(&s["t"]) >= t - 3600.0);
84 Ok(value)
85 },
86 )
87 .await
88}
89async fn vm_call(action: &str, payload: Option<Value>) -> Result<Value> {
90 let mut request = json!({"operation":format!("vm.{action}")});
91 if let Some(payload) = payload {
92 request["payload"] = payload;
93 }
94 host::call(request).await
95}
96
97fn vm_name(name: &str) -> Result<()> {
98 if regex::Regex::new(r"^[a-z0-9][a-z0-9-]{0,62}$")
99 .unwrap()
100 .is_match(name)
101 {
102 Ok(())
103 } else {
104 Err(Error::new(400, "No VM has that name."))
105 }
106}
107fn validate_vm(mut spec: Value) -> Result<Value> {
108 vm_name(string(&spec["name"]))?;
109 spec["description"] = json!("");
110 spec["autostart"] = json!(false);
111 spec["start"] = json!(spec["mode"] == "preset");
112 if string(&spec["image"]).is_empty() {
113 return Err(Error::new(400, "Pick an OS image."));
114 }
115 for (key, min) in [
116 ("vcpus", 1.0),
117 ("memory", 536870912.0),
118 ("disk", 1073741824.0),
119 ] {
120 let n = number(&spec[key]);
121 if !spec[key].is_number() || n.fract() != 0.0 || n < min {
122 return Err(Error::new(400, format!("Invalid {key}.")));
123 }
124 }
125 Ok(spec)
126}
127async fn paper(app: Arc<App>, path: &str, body: Option<Value>) -> Result<Value> {
128 let jobs = core::scan(app.clone()).await?;
129 let host = jobs.value["clover-source-of-truth"]["job"]["Meta"]["snowglobe_hostname"]
130 .as_str()
131 .ok_or_else(|| Error::new(502, "Paper Clover is unavailable."))?;
132 let key = host::call(
133 json!({"operation":"deploy.secret.get","service":"clover-source-of-truth","key":"key"}),
134 )
135 .await?;
136 let key = key
137 .as_str()
138 .ok_or_else(|| Error::new(502, "Paper Clover is unavailable."))?;
139 let url = format!("https://{host}/{path}");
140 let request = if let Some(body) = body {
141 app.http.post(&url).json(&body)
142 } else {
143 app.http.get(&url)
144 };
145 let response = request
146 .header("Authorization", key)
147 .timeout(Duration::from_secs(10))
148 .send()
149 .await?;
150 if path == "scan" {
151 if response.status() == 409 {
152 return Err(Error::new(
153 409,
154 "File scans are off on this host. Turn on the Paper Clover indexer to use this action.",
155 ));
156 }
157 if response.status() != 202 {
158 return Err(Error::new(
159 502,
160 "Paper Clover couldn't start the scan. Check its service logs.",
161 ));
162 }
163 return Ok(Value::Null);
164 }
165 if !response.status().is_success() {
166 return Err(Error::new(
167 502,
168 format!("Paper Clover answered {}.", response.status()),
169 ));
170 }
171 Ok(response.json().await?)
172}
173
174pub async fn route(
175 app: Arc<App>,
176 method: &Method,
177 parts: &[&str],
178 query: &HashMap<String, String>,
179 me: &Value,
180 body: Value,
181) -> Result<Response> {
182 let value = match parts {
183 ["seedbox"] if method == Method::GET => {
184 let (state, mut torrents) = tokio::try_join!(
185 seed_state(app.clone()),
186 qbt(app.clone(), "torrents/info", None)
187 )?;
188 for torrent in torrents.as_array_mut().unwrap() {
189 let root = torrent["root_path"]
190 .as_str()
191 .filter(|s| !s.is_empty())
192 .unwrap_or(string(&torrent["save_path"]))
193 .to_owned();
194 torrent["folder"] = qbt_link(&root, false);
195 torrent["zip"] = if string(&torrent["root_path"]).is_empty() {
196 Value::Null
197 } else {
198 qbt_link(string(&torrent["root_path"]), true)
199 };
200 }
201 json!({"state":state.value,"downloads":qbt_link(string(&state.value["save_path"]),false),"torrents":torrents})
202 }
203 ["seedbox", "history"] if method == Method::GET => {
204 seed_state(app.clone()).await?;
205 let samples = app.seed_samples.lock().unwrap();
206 json!([("download","down"),("upload","up")].map(|(name,key)| json!({"name":name,"t":samples.iter().map(|s| s["t"].clone()).collect::<Vec<_>>(),"v":samples.iter().map(|s| s[key].clone()).collect::<Vec<_>>()})))
207 }
208 ["seedbox", "torrents"] if method == Method::POST => {
209 let url = string(&body["url"]).trim();
210 if !regex::Regex::new(r"(?i)^(magnet:\?|https?://)")
211 .unwrap()
212 .is_match(url)
213 {
214 return Err(Error::new(
215 400,
216 "Paste a magnet link or a link to a .torrent file",
217 ));
218 }
219 qbt(app, "torrents/add", Some(json!({"urls":url}))).await?;
220 Value::Null
221 }
222 ["seedbox", "torrents", hash, tail @ ..] => {
223 if !regex::Regex::new(r"^[0-9a-f]{40}$").unwrap().is_match(hash) {
224 return Err(Error::new(
225 400,
226 "Torrent hashes are 40 lowercase hex characters.",
227 ));
228 }
229 match tail {
230 ["files"] if method == Method::GET => {
231 let route = format!("torrents/files?{}", params(&[("hash", hash.to_string())]));
232 let (torrents, mut files) = tokio::try_join!(
233 qbt(app.clone(), "torrents/info", None),
234 qbt(app.clone(), &route, None)
235 )?;
236 let root = array(&torrents)
237 .iter()
238 .find(|t| t["hash"] == *hash)
239 .and_then(|t| t["save_path"].as_str());
240 for file in files.as_array_mut().unwrap() {
241 file["link"] = root
242 .map(|root| {
243 qbt_link(&format!("{root}/{}", string(&file["name"])), false)
244 })
245 .unwrap_or(Value::Null);
246 }
247 files
248 }
249 [action]
250 if method == Method::POST
251 && [
252 "stop",
253 "start",
254 "topPrio",
255 "increasePrio",
256 "decreasePrio",
257 "bottomPrio",
258 ]
259 .contains(action) =>
260 {
261 qbt(
262 app,
263 &format!("torrents/{action}"),
264 Some(json!({"hashes":hash})),
265 )
266 .await?;
267 Value::Null
268 }
269 [] if method == Method::DELETE => {
270 let files = query.get("files").map(String::as_str).unwrap_or("0");
271 if !["0", "1"].contains(&files) {
272 return Err(Error::new(400, "Invalid files option."));
273 }
274 qbt(app,"torrents/delete",Some(json!({"hashes":hash,"deleteFiles":if files=="1" {"true"} else {"false"}}))).await?;
275 Value::Null
276 }
277 _ => return Err(Error::new(404, "Not Found")),
278 }
279 }
280 ["vms"] if method == Method::GET => {
281 let mut values = Vec::new();
282 for (action, ttl) in [("node", 600), ("domains", 5), ("library", 15)] {
283 let value = app
284 .cache
285 .get(
286 format!("vms:{action}"),
287 Duration::from_secs(ttl),
288 move || async move { vm_call(action, None).await },
289 )
290 .await?;
291 values.push(value.value.clone());
292 }
293 let allocated: f64 = array(&values[1])
294 .iter()
295 .filter(|vm| vm["host"] == values[0]["name"] && !["shutoff", "crashed"].contains(&string(&vm["state"])))
296 .map(|vm| number(&vm["balloon"]))
297 .sum();
298 values[0]["availableMemory"] =
299 json!((number(&values[0]["memory"]) - allocated).max(0.0));
300 values[1]
301 .as_array_mut()
302 .unwrap()
303 .retain(|domain| vms::visible(me, domain));
304 for domain in values[1].as_array_mut().unwrap() {
305 domain["usage"] = app
306 .vm_usage
307 .lock()
308 .unwrap()
309 .get(string(&domain["name"]))
310 .cloned()
311 .unwrap_or(Value::Null);
312 }
313 json!({"node":values[0],"domains":values[1],"library":values[2],"canPublish":array(&me["sections"]).iter().any(|section| section == "admin")})
314 }
315 ["vms", "history"] if method == Method::GET => {
316 if let Some(name) = query.get("name") {
317 vms::authorize(me, name).await?;
318 }
319 let owned = vm_call("domains", None).await?;
320 let range = telemetry::query_number(query, "range", 300.0, 60.0, 86400.0)?;
321 let mut query = query.clone();
322 query.insert("range".into(), range.to_string());
323 if let Some(name) = query.get("name").cloned() {
324 query.insert("service".into(), name);
325 }
326 let (cpu, memory) = tokio::try_join!(
327 telemetry::metrics(app.clone(), "vm.cpu", &query, None, None),
328 telemetry::metrics(app.clone(), "vm.memory", &query, None, None)
329 )?;
330 let mut domains = serde_json::Map::new();
331 for (values, key) in [(&cpu.value, "cpu"), (&memory.value, "memory")] {
332 for series in array(values) {
333 if !array(&owned).iter().any(|domain| {
334 domain["name"] == series["name"] && vms::visible(me, domain)
335 }) {
336 continue;
337 }
338 let domain = domains
339 .entry(string(&series["name"]).to_owned())
340 .or_insert_with(|| json!({"cpu":[],"memory":[]}));
341 domain[key] = series["v"].clone();
342 }
343 }
344 json!({"t":cpu.value[0]["t"].as_array().or(memory.value[0]["t"].as_array()).cloned().unwrap_or_default(),"domains":domains})
345 }
346 ["vms"] if method == Method::POST => {
347 let mut spec = validate_vm(body)?;
348 spec["owner"] = me["id"].clone();
349 spec["username"] = me["name"].clone();
350 vm_call("create", Some(spec)).await?;
351 app.cache.invalidate("vms:domains");
352 Value::Null
353 }
354 ["vms", name, tail @ ..] => {
355 vm_name(name)?;
356 match tail {
357 ["clipboard"] if method == Method::POST => {
358 vm_call("clipboard", Some(json!({"name":name,"text":body["text"]}))).await?;
359 }
360 ["access"] if method == Method::GET => {
361 let mut response =
362 Document::new(vm_call("access", Some(json!({"name":name}))).await?)
363 .response();
364 response
365 .headers_mut()
366 .insert("cache-control", "no-store".parse().unwrap());
367 return Ok(response);
368 }
369 ["media"] if method == Method::PUT => {
370 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;
371 }
372 ["preset"] if method == Method::POST => {
373 need(me, "admin")?;
374 vm_call("preset", Some(json!({"name":name,"id":body["id"],"os":body["os"],"description":body["description"]}))).await?;
375 app.cache.invalidate("vms:library");
376 }
377 [] if method == Method::PATCH => {
378 let mut payload = json!({"name":name});
379 if let Some(v) = body.get("autostart") {
380 if !v.is_boolean() {
381 return Err(Error::new(400, "Invalid autostart."));
382 }
383 payload["autostart"] = v.clone();
384 }
385 if let Some(v) = body.get("description") {
386 let v = v
387 .as_str()
388 .ok_or_else(|| Error::new(400, "Enter a description."))?
389 .trim();
390 if v.chars().count() > 200 {
391 return Err(Error::new(
392 400,
393 "Keep the description under 200 characters.",
394 ));
395 }
396 payload["description"] = json!(v);
397 }
398 vm_call("update", Some(payload)).await?;
399 }
400 [] if method == Method::DELETE => {
401 let disks = query.get("disks").map(String::as_str).unwrap_or("1");
402 if !["0", "1"].contains(&disks) {
403 return Err(Error::new(400, "Invalid disks option."));
404 }
405 vm_call("remove", Some(json!({"name":name,"disks":disks=="1"}))).await?;
406 }
407 [action]
408 if method == Method::POST
409 && ["start", "shutdown", "reboot", "destroy", "resume", "suspend"]
410 .contains(action) =>
411 {
412 vm_call("act", Some(json!({"name":name,"action":action}))).await?;
413 }
414 _ => return Err(Error::new(404, "Not Found")),
415 }
416 app.cache.invalidate("vms:domains");
417 Value::Null
418 }
419 ["paper-clover"] if method == Method::GET => {
420 let mut value = paper(app, "stats", None).await?;
421 value["browse"] = std::env::var("SNOWGLOBE_PUBLISHED_ROOT")
422 .ok()
423 .map(|p| file_link(&p, false))
424 .unwrap_or(Value::Null);
425 value
426 }
427 ["paper-clover", "activity"] if method == Method::GET => {
428 paper(app, "activity", None).await?
429 }
430 ["paper-clover", "scan"] if method == Method::POST => {
431 let path = &body["path"];
432 if !path.is_null()
433 && (!path.is_string()
434 || !string(path).starts_with('/')
435 || string(path).split('/').any(|s| s == ".."))
436 {
437 return Err(Error::new(
438 400,
439 "Paths can't contain \"..\". Write the full path, like /2026/friends.",
440 ));
441 }
442 paper(
443 app,
444 "scan",
445 Some(if path.is_null() {
446 json!({})
447 } else {
448 json!({"path":path})
449 }),
450 )
451 .await?;
452 return Ok(StatusCode::ACCEPTED.into_response());
453 }
454 _ => return Err(Error::new(404, "Not Found")),
455 };
456 Ok(if value.is_null() {
457 StatusCode::NO_CONTENT.into_response()
458 } else {
459 Document::new(value).response()
460 })
461}