xget 0.1.1

xget: fast multi-connection download manager for the terminal: segmented Range downloads, queue, torrents, and curl-like requests.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};

use crate::state::{Engine, Status, Store};

pub fn runtime_dir() -> PathBuf {
    if let Ok(v) = std::env::var("XGET_RUNTIME_DIR") {
        if !v.trim().is_empty() {
            return PathBuf::from(v);
        }
    }
    if let Ok(v) = std::env::var("XDG_RUNTIME_DIR") {
        if !v.trim().is_empty() {
            return PathBuf::from(v);
        }
    }
    std::env::temp_dir()
}

pub fn socket_path() -> PathBuf {
    runtime_dir().join("xget.sock")
}

pub fn pid_path() -> PathBuf {
    runtime_dir().join("xget.pid")
}

fn read_pid() -> Option<u32> {
    std::fs::read_to_string(pid_path())
        .ok()
        .and_then(|s| s.trim().parse::<u32>().ok())
}

fn pid_alive(pid: u32) -> bool {
    PathBuf::from(format!("/proc/{pid}")).exists()
}

pub fn rpc_block(method: &str, params: Value) -> Option<Value> {
    let sock = socket_path();
    if !sock.exists() {
        return None;
    }
    let stream = std::os::unix::net::UnixStream::connect(&sock).ok()?;
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .ok()?;
    stream
        .set_write_timeout(Some(Duration::from_secs(5)))
        .ok()?;
    let mut reader = BufReader::new(stream.try_clone().ok()?);
    let mut writer = stream;
    let req = json!({"id": 1, "method": method, "params": params});
    let mut line = serde_json::to_string(&req).ok()?;
    line.push('\n');
    writer.write_all(line.as_bytes()).ok()?;
    writer.flush().ok()?;
    let mut resp_line = String::new();
    reader.read_line(&mut resp_line).ok()?;
    if resp_line.trim().is_empty() {
        return None;
    }
    serde_json::from_str(&resp_line).ok()
}

pub fn daemon_active() -> bool {
    match rpc_block("ping", json!({})) {
        Some(v) => v.get("result").and_then(|r| r.get("ok")).and_then(|o| o.as_bool()).unwrap_or(false),
        None => false,
    }
}

pub fn daemon_status_line() -> String {
    let sock = socket_path();
    match read_pid() {
        Some(pid) if pid_alive(pid) && daemon_active() => {
            let n = rpc_block("list", json!({}))
                .and_then(|v| v.get("result").and_then(|r| r.get("records")).and_then(|r| r.as_array()).map(|a| a.len()))
                .unwrap_or(0);
            format!("daemon running (pid {pid}, socket {}, {n} record(s))", sock.display())
        }
        Some(pid) if pid_alive(pid) => format!("daemon pid file present (pid {pid}) but socket not responding at {}", sock.display()),
        _ => {
            if daemon_active() {
                format!("daemon running (socket {})", sock.display())
            } else {
                format!("daemon not running (socket {})", sock.display())
            }
        }
    }
}

pub async fn run_server() -> Result<()> {
    let sock = socket_path();
    if let Some(parent) = sock.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("cannot create {}", parent.display()))?;
    }
    if sock.exists() {
        let _ = std::fs::remove_file(&sock);
    }
    let listener = tokio::net::UnixListener::bind(&sock)
        .with_context(|| format!("cannot bind {}", sock.display()))?;
    let pid = std::process::id();
    let _ = std::fs::write(pid_path(), pid.to_string());
    println!("xget daemon listening on {} (pid {pid})", sock.display());
    loop {
        let Ok((stream, _)) = listener.accept().await else {
            continue;
        };
        let shutdown = handle_conn(stream).await;
        if shutdown {
            break;
        }
    }
    let _ = std::fs::remove_file(&sock);
    let _ = std::fs::remove_file(pid_path());
    println!("xget daemon stopped");
    Ok(())
}

async fn handle_conn(stream: tokio::net::UnixStream) -> bool {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
    let (r, mut w) = stream.into_split();
    let mut reader = tokio::io::BufReader::new(r);
    let mut line = String::new();
    let n = reader.read_line(&mut line).await.unwrap_or(0);
    if n == 0 {
        return false;
    }
    let req: Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => {
            let _ = w.write_all(b"{\"id\":0,\"error\":\"bad request\"}\n").await;
            return false;
        }
    };
    let id = req.get("id").cloned().unwrap_or(json!(0));
    let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string();
    let params = req.get("params").cloned().unwrap_or(json!({}));
    let (result, error, shutdown): (Value, Option<String>, bool) = dispatch(&method, params);
    let resp = if let Some(e) = error {
        json!({"id": id, "error": e})
    } else {
        json!({"id": id, "result": result})
    };
    let mut out = serde_json::to_string(&resp).unwrap_or_else(|_| "{\"error\":\"encode\"}".to_string());
    out.push('\n');
    let _ = w.write_all(out.as_bytes()).await;
    shutdown
}

fn dispatch(method: &str, params: Value) -> (Value, Option<String>, bool) {
    match method {
        "ping" => (json!({"ok": true}), None, false),
        "list" => match Store::load() {
            Ok(s) => {
                let records = serde_json::to_value(s.all()).unwrap_or(json!([]));
                (json!({"records": records}), None, false)
            }
            Err(e) => (json!({}), Some(format!("{e:#}")), false),
        },
        "status" => {
            let id = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32);
            match Store::load() {
                Ok(s) => {
                    let records: Vec<&crate::state::Record> = match id {
                        Some(i) => s.get(i).into_iter().collect(),
                        None => s.all().iter().collect(),
                    };
                    let v = serde_json::to_value(&records).unwrap_or(json!([]));
                    (json!({"records": v}), None, false)
                }
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "add" => {
            let url = params.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let output = params.get("output").and_then(|v| v.as_str()).unwrap_or("").to_string();
            let connections = params.get("connections").and_then(|v| v.as_u64()).unwrap_or(16) as usize;
            let kind = params.get("kind").and_then(|v| v.as_str()).unwrap_or("direct");
            if url.is_empty() || output.is_empty() {
                return (json!({}), Some("add needs url and output".to_string()), false);
            }
            match Store::update(|s| {
                let engine = if kind == "torrent" { Engine::Torrent } else { Engine::Direct };
                let id = s.add(
                    url.clone(),
                    PathBuf::from(output.clone()),
                    connections.clamp(1, 32),
                    engine,
                    Vec::new(),
                    0,
                    None,
                    None,
                );
                if let Some(r) = s.get_mut(id) {
                    r.status = Status::Downloading;
                }
                id
            }) {
                Ok(id) => (json!({"id": id}), None, false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "pause" => {
            let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
                return (json!({}), Some("pause needs id".to_string()), false);
            };
            enum POut { Ok, NoSuch }
            match Store::update(|s| {
                let Some(r) = s.get_mut(id) else {
                    return POut::NoSuch;
                };
                r.status = Status::Paused;
                r.error = None;
                POut::Ok
            }) {
                Ok(POut::Ok) => (json!({"id": id, "status": "paused"}), None, false),
                Ok(POut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "resume_state" => {
            let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
                return (json!({}), Some("resume_state needs id".to_string()), false);
            };
            enum ROut { Ok, NoSuch }
            match Store::update(|s| {
                let Some(r) = s.get_mut(id) else {
                    return ROut::NoSuch;
                };
                r.status = Status::Downloading;
                r.error = None;
                ROut::Ok
            }) {
                Ok(ROut::Ok) => (json!({"id": id, "status": "active"}), None, false),
                Ok(ROut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "complete" => {
            let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
                return (json!({}), Some("complete needs id".to_string()), false);
            };
            let total = params.get("total").and_then(|v| v.as_u64());
            enum COut { Ok, NoSuch }
            match Store::update(|s| {
                let Some(r) = s.get_mut(id) else {
                    return COut::NoSuch;
                };
                r.status = Status::Completed;
                r.error = None;
                if let Some(t) = total {
                    r.total_bytes = Some(t);
                    r.downloaded = t;
                }
                COut::Ok
            }) {
                Ok(COut::Ok) => (json!({"id": id, "status": "done"}), None, false),
                Ok(COut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "fail" => {
            let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
                return (json!({}), Some("fail needs id".to_string()), false);
            };
            let err = params.get("error").and_then(|v| v.as_str()).unwrap_or("failed").to_string();
            enum FOut { Ok, NoSuch }
            match Store::update(|s| {
                let Some(r) = s.get_mut(id) else {
                    return FOut::NoSuch;
                };
                r.status = Status::Failed;
                r.error = Some(err.clone());
                FOut::Ok
            }) {
                Ok(FOut::Ok) => (json!({"id": id, "status": "failed"}), None, false),
                Ok(FOut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "remove" => {
            let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
                return (json!({}), Some("remove needs id".to_string()), false);
            };
            match Store::update(|s| s.remove(id).is_some()) {
                Ok(true) => (json!({"id": id, "removed": true}), None, false),
                Ok(false) => (json!({}), Some(format!("no such download with id {id}")), false),
                Err(e) => (json!({}), Some(format!("{e:#}")), false),
            }
        }
        "shutdown" => (json!({"ok": true}), None, true),
        _ => (json!({}), Some(format!("unknown method: {method}")), false),
    }
}

pub fn cmd_start() -> Result<()> {
    if daemon_active() {
        println!("daemon already running: {}", socket_path().display());
        return Ok(());
    }
    let exe = std::env::current_exe().context("cannot find xget binary")?;
    let mut cmd = std::process::Command::new(exe);
    cmd.arg("__daemon-run");
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::null());
    cmd.stderr(std::process::Stdio::null());
    let child = cmd.spawn().context("cannot start daemon process")?;
    let pid = child.id();
    drop(child);
    for _ in 0..50 {
        std::thread::sleep(Duration::from_millis(100));
        if daemon_active() {
            println!("daemon started (pid {pid}, socket {})", socket_path().display());
            return Ok(());
        }
    }
    bail!("daemon did not respond on {}", socket_path().display());
}

pub fn cmd_stop() -> Result<()> {
    if !daemon_active() {
        let _ = std::fs::remove_file(socket_path());
        let _ = std::fs::remove_file(pid_path());
        println!("daemon not running");
        return Ok(());
    }
    let _ = rpc_block("shutdown", json!({}));
    std::thread::sleep(Duration::from_millis(300));
    let _ = std::fs::remove_file(socket_path());
    let _ = std::fs::remove_file(pid_path());
    println!("daemon stopped");
    Ok(())
}

pub fn cmd_status() -> Result<()> {
    println!("{}", daemon_status_line());
    Ok(())
}

pub fn daemon_create_record(url: &str, output: &str, connections: usize, kind: &str) -> Option<u32> {
    let resp = rpc_block(
        "add",
        json!({"url": url, "output": output, "connections": connections, "kind": kind}),
    )?;
    if let Some(e) = resp.get("error") {
        let _ = e;
        return None;
    }
    resp.get("result")
        .and_then(|r| r.get("id"))
        .and_then(|v| v.as_u64())
        .map(|v| v as u32)
}

pub fn daemon_complete(id: u32, total: u64) -> bool {
    rpc_block("complete", json!({"id": id, "total": total})).is_some()
}

pub fn daemon_fail(id: u32, error: &str) -> bool {
    rpc_block("fail", json!({"id": id, "error": error})).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn socket_paths_are_sane() {
        let s = socket_path();
        assert!(s.to_string_lossy().contains("xget.sock"));
        let p = pid_path();
        assert!(p.to_string_lossy().contains("xget.pid"));
    }

    #[test]
    fn dispatch_ping_and_unknown() {
        let (r, e, sd) = dispatch("ping", json!({}));
        assert!(e.is_none() && !sd);
        assert_eq!(r.get("ok").and_then(|v| v.as_bool()), Some(true));
        let (_, e, _) = dispatch("nope", json!({}));
        assert!(e.is_some());
    }

    #[test]
    fn dispatch_validates_add_and_pause() {
        let (_, e, _) = dispatch("add", json!({}));
        assert!(e.is_some());
        let (_, e, _) = dispatch("pause", json!({}));
        assert!(e.is_some());
        let (_, e, _) = dispatch("remove", json!({"id": 999999}));
        assert!(e.is_some() || e.is_none());
    }

    #[test]
    fn rpc_returns_none_without_socket() {
        let dir = std::env::temp_dir().join(format!("xget-daemon-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let prev = std::env::var("XGET_RUNTIME_DIR").ok();
        unsafe { std::env::set_var("XGET_RUNTIME_DIR", &dir) };
        assert!(rpc_block("ping", json!({})).is_none());
        assert!(!daemon_active());
        if let Some(v) = prev {
            unsafe { std::env::set_var("XGET_RUNTIME_DIR", v) };
        } else {
            unsafe { std::env::remove_var("XGET_RUNTIME_DIR") };
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
}