|
| 1 | +"""Platform-specific scheduler backends for auto-sync.""" |
| 2 | + |
| 3 | +import abc |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import textwrap |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
| 9 | + |
| 10 | + |
| 11 | +class Scheduler(abc.ABC): |
| 12 | + """Abstract base for OS-level periodic job schedulers.""" |
| 13 | + |
| 14 | + @abc.abstractmethod |
| 15 | + def install(self, config: dict[str, Any]) -> None: |
| 16 | + """Register the periodic sync job.""" |
| 17 | + |
| 18 | + @abc.abstractmethod |
| 19 | + def uninstall(self) -> None: |
| 20 | + """Remove the periodic sync job.""" |
| 21 | + |
| 22 | + @abc.abstractmethod |
| 23 | + def is_active(self) -> bool: |
| 24 | + """Return True if the job is currently registered.""" |
| 25 | + |
| 26 | + |
| 27 | +# --------------------------------------------------------------------------- |
| 28 | +# macOS launchd |
| 29 | +# --------------------------------------------------------------------------- |
| 30 | + |
| 31 | +PLIST_PATH = Path.home() / "Library" / "LaunchAgents" / "io.drdroid.droidctx.auto-sync.plist" |
| 32 | + |
| 33 | +_PLIST_TEMPLATE = textwrap.dedent("""\ |
| 34 | + <?xml version="1.0" encoding="UTF-8"?> |
| 35 | + <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" |
| 36 | + "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 37 | + <plist version="1.0"> |
| 38 | + <dict> |
| 39 | + <key>Label</key> |
| 40 | + <string>io.drdroid.droidctx.auto-sync</string> |
| 41 | + <key>ProgramArguments</key> |
| 42 | + <array> |
| 43 | + <string>{droidctx_bin}</string> |
| 44 | + <string>sync</string> |
| 45 | + <string>--keyfile</string> |
| 46 | + <string>{keyfile}</string> |
| 47 | + <string>--path</string> |
| 48 | + <string>{output_dir}</string> |
| 49 | + </array> |
| 50 | + <key>StartInterval</key> |
| 51 | + <integer>{interval_seconds}</integer> |
| 52 | + <key>StandardOutPath</key> |
| 53 | + <string>{log_file}</string> |
| 54 | + <key>StandardErrorPath</key> |
| 55 | + <string>{log_file}</string> |
| 56 | + </dict> |
| 57 | + </plist> |
| 58 | +""") |
| 59 | + |
| 60 | + |
| 61 | +class LaunchdScheduler(Scheduler): |
| 62 | + """macOS launchd backend.""" |
| 63 | + |
| 64 | + def install(self, config: dict[str, Any]) -> None: |
| 65 | + from droidctx.auto_sync import LOG_FILE |
| 66 | + |
| 67 | + plist_content = _PLIST_TEMPLATE.format( |
| 68 | + droidctx_bin=config["droidctx_bin"], |
| 69 | + keyfile=config["keyfile"], |
| 70 | + output_dir=config["output_dir"], |
| 71 | + interval_seconds=config["interval_minutes"] * 60, |
| 72 | + log_file=str(LOG_FILE), |
| 73 | + ) |
| 74 | + PLIST_PATH.parent.mkdir(parents=True, exist_ok=True) |
| 75 | + PLIST_PATH.write_text(plist_content) |
| 76 | + subprocess.run( |
| 77 | + ["launchctl", "load", str(PLIST_PATH)], |
| 78 | + check=True, |
| 79 | + capture_output=True, |
| 80 | + ) |
| 81 | + |
| 82 | + def uninstall(self) -> None: |
| 83 | + if PLIST_PATH.exists(): |
| 84 | + subprocess.run( |
| 85 | + ["launchctl", "unload", str(PLIST_PATH)], |
| 86 | + check=True, |
| 87 | + capture_output=True, |
| 88 | + ) |
| 89 | + PLIST_PATH.unlink() |
| 90 | + |
| 91 | + def is_active(self) -> bool: |
| 92 | + return PLIST_PATH.exists() |
| 93 | + |
| 94 | + |
| 95 | +# --------------------------------------------------------------------------- |
| 96 | +# Linux cron |
| 97 | +# --------------------------------------------------------------------------- |
| 98 | + |
| 99 | +CRON_MARKER = "# droidctx-auto-sync" |
| 100 | + |
| 101 | + |
| 102 | +class CronScheduler(Scheduler): |
| 103 | + """Linux crontab backend.""" |
| 104 | + |
| 105 | + def _read_crontab(self) -> str: |
| 106 | + result = subprocess.run( |
| 107 | + ["crontab", "-l"], |
| 108 | + capture_output=True, |
| 109 | + text=True, |
| 110 | + ) |
| 111 | + if result.returncode != 0: |
| 112 | + return "" |
| 113 | + return result.stdout |
| 114 | + |
| 115 | + def _write_crontab(self, content: str) -> None: |
| 116 | + subprocess.run( |
| 117 | + ["crontab", "-"], |
| 118 | + input=content, |
| 119 | + check=True, |
| 120 | + text=True, |
| 121 | + capture_output=True, |
| 122 | + ) |
| 123 | + |
| 124 | + def install(self, config: dict[str, Any]) -> None: |
| 125 | + from droidctx.auto_sync import LOG_FILE |
| 126 | + |
| 127 | + # Remove old entry first |
| 128 | + existing = self._read_crontab() |
| 129 | + lines = [l for l in existing.splitlines() if CRON_MARKER not in l] |
| 130 | + |
| 131 | + cmd = ( |
| 132 | + f"{config['droidctx_bin']} sync " |
| 133 | + f"--keyfile {config['keyfile']} " |
| 134 | + f"--path {config['output_dir']}" |
| 135 | + ) |
| 136 | + cron_line = f"*/{config['interval_minutes']} * * * * {cmd} >> {LOG_FILE} 2>&1 {CRON_MARKER}" |
| 137 | + lines.append(cron_line) |
| 138 | + |
| 139 | + self._write_crontab("\n".join(lines) + "\n") |
| 140 | + |
| 141 | + def uninstall(self) -> None: |
| 142 | + existing = self._read_crontab() |
| 143 | + lines = [l for l in existing.splitlines() if CRON_MARKER not in l] |
| 144 | + self._write_crontab("\n".join(lines) + "\n" if lines else "") |
| 145 | + |
| 146 | + def is_active(self) -> bool: |
| 147 | + return CRON_MARKER in self._read_crontab() |
| 148 | + |
| 149 | + |
| 150 | +# --------------------------------------------------------------------------- |
| 151 | +# Factory |
| 152 | +# --------------------------------------------------------------------------- |
| 153 | + |
| 154 | +def get_scheduler() -> Scheduler: |
| 155 | + """Return the appropriate scheduler for the current platform.""" |
| 156 | + if sys.platform == "darwin": |
| 157 | + return LaunchdScheduler() |
| 158 | + elif sys.platform.startswith("linux"): |
| 159 | + return CronScheduler() |
| 160 | + else: |
| 161 | + raise NotImplementedError(f"Auto-sync is not supported on {sys.platform}") |
0 commit comments