Skip to main content

macfly_core/
schedule.rs

1use std::fs;
2use std::path::PathBuf;
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::MacflyError;
7
8const LABEL_PREFIX: &str = "com.casoon.macfly.";
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct ScheduleJobInfo {
12    pub name: String,
13    pub label: String,
14    pub plist_path: String,
15}
16
17pub fn launch_agents_dir() -> Result<PathBuf, MacflyError> {
18    let home = dirs::home_dir().ok_or_else(|| {
19        MacflyError::ScriptError("Home-Verzeichnis konnte nicht ermittelt werden".to_string())
20    })?;
21    Ok(home.join("Library").join("LaunchAgents"))
22}
23
24pub fn job_label(name: &str) -> String {
25    let clean: String = name
26        .chars()
27        .map(|c| {
28            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
29                c.to_ascii_lowercase()
30            } else {
31                '-'
32            }
33        })
34        .collect();
35    format!("{LABEL_PREFIX}{clean}")
36}
37
38/// Erzeugt eine valide macOS `launchd` `.plist`-XML-Datei für zeitgesteuerte lokale MacFly-Routinen.
39pub fn render_launchd_plist(
40    label: &str,
41    macfly_bin: &str,
42    args: &[String],
43    hour: u8,
44    minute: u8,
45    log_dir: &str,
46) -> String {
47    let mut prog_args = format!("    <string>{}</string>\n", escape_xml(macfly_bin));
48    for a in args {
49        prog_args.push_str(&format!("    <string>{}</string>\n", escape_xml(a)));
50    }
51
52    format!(
53        r#"<?xml version="1.0" encoding="UTF-8"?>
54<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
55<plist version="1.0">
56<dict>
57  <key>Label</key>
58  <string>{label}</string>
59  <key>ProgramArguments</key>
60  <array>
61{prog_args}  </array>
62  <key>StartCalendarInterval</key>
63  <dict>
64    <key>Hour</key>
65    <integer>{hour}</integer>
66    <key>Minute</key>
67    <integer>{minute}</integer>
68  </dict>
69  <key>StandardOutPath</key>
70  <string>{log_dir}/{label}.out.log</string>
71  <key>StandardErrorPath</key>
72  <string>{log_dir}/{label}.err.log</string>
73  <key>RunAtLoad</key>
74  <false/>
75</dict>
76</plist>
77"#
78    )
79}
80
81pub fn list_installed_jobs() -> Result<Vec<ScheduleJobInfo>, MacflyError> {
82    let dir = launch_agents_dir()?;
83    if !dir.exists() {
84        return Ok(Vec::new());
85    }
86    let mut jobs = Vec::new();
87    for entry in fs::read_dir(&dir)? {
88        let entry = entry?;
89        let path = entry.path();
90        if let Some(fname) = path.file_name().and_then(|s| s.to_str())
91            && let Some(rest) = fname.strip_prefix(LABEL_PREFIX)
92            && let Some(name) = rest.strip_suffix(".plist")
93        {
94            jobs.push(ScheduleJobInfo {
95                name: name.to_string(),
96                label: format!("{LABEL_PREFIX}{name}"),
97                plist_path: path.display().to_string(),
98            });
99        }
100    }
101    jobs.sort_by(|a, b| a.name.cmp(&b.name));
102    Ok(jobs)
103}
104
105fn escape_xml(s: &str) -> String {
106    s.replace('&', "&amp;")
107        .replace('<', "&lt;")
108        .replace('>', "&gt;")
109        .replace('"', "&quot;")
110        .replace('\'', "&apos;")
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn generates_valid_launchd_plist() {
119        let label = job_label("morning-brief");
120        assert_eq!(label, "com.casoon.macfly.morning-brief");
121        let xml = render_launchd_plist(
122            &label,
123            "/Users/test/.cargo/bin/macfly",
124            &["context".to_string(), "daily-brief".to_string()],
125            7,
126            30,
127            "/Users/test/.local/share/macfly/logs",
128        );
129        assert!(xml.contains("<string>com.casoon.macfly.morning-brief</string>"));
130        assert!(xml.contains("<integer>7</integer>"));
131        assert!(xml.contains("<integer>30</integer>"));
132    }
133}