yandexdisk 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
yandexdisk/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """yandexdisk — a system tray control center for the Yandex Disk console client on Linux."""
2
+
3
+ __version__ = "0.0.1"
yandexdisk/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
yandexdisk/app.py ADDED
@@ -0,0 +1,363 @@
1
+ """Application controller: owns the daemon, tray, window and shared state."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import os
6
+ import sys
7
+ import time
8
+ from logging.handlers import RotatingFileHandler
9
+ from pathlib import Path
10
+
11
+ from PySide6.QtCore import QObject, Qt, QTimer, QUrl, Signal
12
+ from PySide6.QtGui import QDesktopServices, QGuiApplication
13
+ from PySide6.QtNetwork import QLocalServer, QLocalSocket
14
+ from PySide6.QtWidgets import QApplication, QMessageBox, QSystemTrayIcon
15
+
16
+ from . import __version__, icons, theme, ydconfig
17
+ from . import status as S
18
+ from .daemon import Daemon
19
+ from .settings import LOG_FILE, History, Published, Settings
20
+
21
+ SERVER_NAME = f"yandexdisk-{os.getuid() if hasattr(os, 'getuid') else 'user'}"
22
+
23
+
24
+ def send_to_running(message: str, timeout: int = 800) -> bool:
25
+ sock = QLocalSocket()
26
+ sock.connectToServer(SERVER_NAME)
27
+ if not sock.waitForConnected(timeout):
28
+ return False
29
+ sock.write(message.encode())
30
+ sock.flush()
31
+ sock.waitForBytesWritten(timeout)
32
+ sock.disconnectFromServer()
33
+ return True
34
+
35
+
36
+ class Context(QObject):
37
+ historyChanged = Signal()
38
+ publishedChanged = Signal()
39
+ themeChanged = Signal(dict)
40
+ logAdded = Signal(tuple)
41
+ accountChanged = Signal()
42
+ diagnosticsDone = Signal(int, int)
43
+
44
+ def __init__(self, app: QApplication):
45
+ super().__init__()
46
+ self.app = app
47
+ self.settings = Settings()
48
+ self.history = History(limit=int(self.settings["history_limit"]))
49
+ self.published = Published()
50
+ self.logs: list[tuple] = []
51
+ self._file_log = self._make_file_logger()
52
+ self.colors = theme.apply(app, self.settings["theme"])
53
+ self.daemon = Daemon(self.settings, self)
54
+ self.daemon.logged.connect(self.log)
55
+ self.daemon.statusChanged.connect(self._on_status)
56
+ self.daemon.stateChanged.connect(self._on_state)
57
+ self.daemon.commandFinished.connect(self._on_command)
58
+ self.window = None
59
+ self.tray = None
60
+ self._new_this_sync: list[dict] = []
61
+ self._last_error_notified = ""
62
+
63
+ # ------------------------------------------------------------------ setup
64
+ def _make_file_logger(self):
65
+ lg = logging.getLogger("yandexdisk")
66
+ lg.setLevel(logging.INFO)
67
+ try:
68
+ LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
69
+ h = RotatingFileHandler(LOG_FILE, maxBytes=1_000_000, backupCount=3, encoding="utf-8")
70
+ h.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
71
+ lg.addHandler(h)
72
+ except OSError:
73
+ pass
74
+ return lg
75
+
76
+ def start(self, hidden: bool, page: str | None):
77
+ from .ui.tray import Tray
78
+ from .ui.window import ControlCenter
79
+ self.window = ControlCenter(self)
80
+ self.tray = Tray(self)
81
+ if QSystemTrayIcon.isSystemTrayAvailable():
82
+ self.tray.show()
83
+ else:
84
+ self.log("warn", "No system tray found. Install an AppIndicator/StatusNotifier extension "
85
+ "(GNOME) or use KDE, XFCE, Cinnamon. The control center stays open instead.")
86
+ hidden = False
87
+ self.log("info", f"yandexdisk {__version__} started")
88
+ self.daemon.start_polling()
89
+ if self.settings["start_daemon_on_launch"]:
90
+ QTimer.singleShot(1500, self._autostart_daemon)
91
+ if not hidden or page:
92
+ self.show_page(page)
93
+ self.app.aboutToQuit.connect(self._about_to_quit)
94
+
95
+ def _autostart_daemon(self):
96
+ st = self.daemon.status.state
97
+ if st == S.STOPPED and self.signed_in() and self.load_ydconfig().exists:
98
+ self.log("info", "Starting the daemon (start sync when the app opens is on)")
99
+ self.daemon.start()
100
+
101
+ # ------------------------------------------------------------------- log
102
+ def log(self, level: str, msg: str):
103
+ entry = (time.time(), level, msg)
104
+ self.logs.append(entry)
105
+ del self.logs[:-5000]
106
+ getattr(self._file_log, {"warn": "warning"}.get(level, level), self._file_log.info)(msg)
107
+ self.logAdded.emit(entry)
108
+
109
+ # ----------------------------------------------------------- notifications
110
+ def notify(self, title: str, msg: str, kind: str = "info", force: bool = False):
111
+ if not force and self.settings["do_not_disturb"]:
112
+ return
113
+ if self.tray is None or not self.tray.isVisible():
114
+ return
115
+ icon = {"error": QSystemTrayIcon.Critical, "warn": QSystemTrayIcon.Warning}.get(
116
+ kind, QSystemTrayIcon.Information)
117
+ self.tray.showMessage(title, msg, icon, 6000)
118
+
119
+ # --------------------------------------------------------------- daemon
120
+ def _on_status(self, st: S.DaemonStatus):
121
+ new = self.history.record(st.last_items)
122
+ if new:
123
+ self._new_this_sync += new
124
+ self.historyChanged.emit()
125
+ if st.errors and self.settings["notify_errors"]:
126
+ err = st.errors[-1]
127
+ if err != self._last_error_notified:
128
+ self._last_error_notified = err
129
+ self.notify("Yandex Disk error", err, "error")
130
+ self.log("error", f"Daemon error: {err}")
131
+ elif not st.errors:
132
+ self._last_error_notified = ""
133
+
134
+ def _on_state(self, old: str, new: str):
135
+ self.log("info", f"State: {S.STATE_TITLES.get(old, old)} → {S.STATE_TITLES.get(new, new)}")
136
+ s = self.settings
137
+ if new == S.IDLE and old in (S.BUSY, S.INDEX):
138
+ items = self._new_this_sync
139
+ if s["notify_new_files"] and items:
140
+ names = ", ".join(os.path.basename(i["path"]) for i in items[:3])
141
+ more = f" and {len(items) - 3} more" if len(items) > 3 else ""
142
+ self.notify("New in Yandex Disk", names + more)
143
+ elif s["notify_sync_done"]:
144
+ self.notify("Yandex Disk", "Sync finished. Everything is up to date.")
145
+ self._new_this_sync = []
146
+ elif new == S.NO_NET and s["notify_errors"]:
147
+ self.notify("Yandex Disk", "No connection to Yandex. Sync will resume on its own.", "warn")
148
+ if s["notify_start_stop"]:
149
+ if new == S.STOPPED and old in S.ACTIVE_STATES:
150
+ self.notify("Yandex Disk", "Sync stopped.")
151
+ elif old in (S.STOPPED, S.STARTING) and new in (S.IDLE, S.BUSY, S.INDEX):
152
+ self.notify("Yandex Disk", "Sync started.")
153
+
154
+ def _on_command(self, name: str, code: int, out: str):
155
+ if code != 0 and name in ("start", "stop", "sync") and self.settings["notify_errors"]:
156
+ self.notify(f"Could not {name} sync", (out.splitlines() or ["Unknown error"])[-1], "error")
157
+
158
+ def toggle_daemon(self):
159
+ st = self.daemon.status.state
160
+ if st in S.ACTIVE_STATES or st == S.STARTING:
161
+ self.daemon.stop()
162
+ else:
163
+ if not self.signed_in():
164
+ self.login()
165
+ return
166
+ self.daemon.start()
167
+
168
+ # ---------------------------------------------------------------- config
169
+ def load_ydconfig(self) -> ydconfig.YDConfig:
170
+ return ydconfig.load(os.path.expanduser(self.settings["config_path"]))
171
+
172
+ def save_ydconfig(self, cfg: ydconfig.YDConfig, ask_restart: bool = True):
173
+ path = ydconfig.save(cfg)
174
+ self.log("info", f"Saved daemon config {path}")
175
+ self.accountChanged.emit()
176
+ if ask_restart and self.daemon.status.running:
177
+ r = QMessageBox.question(self.window, "Restart sync",
178
+ "The daemon reads its settings when it starts. Restart it now?")
179
+ if r == QMessageBox.Yes:
180
+ self.daemon.restart()
181
+
182
+ def sync_dir(self) -> str:
183
+ if self.daemon.status.path:
184
+ return self.daemon.status.path
185
+ return os.path.expanduser(self.load_ydconfig().dir)
186
+
187
+ def signed_in(self) -> bool:
188
+ auth = Path(self.load_ydconfig().auth).expanduser()
189
+ return auth.is_file() and auth.stat().st_size > 0
190
+
191
+ def login(self):
192
+ from .ui.login import LoginDialog
193
+ cfg = self.load_ydconfig()
194
+ if not cfg.exists:
195
+ # create a minimal config so the daemon knows where to sync
196
+ Path(cfg.dir).expanduser().mkdir(parents=True, exist_ok=True)
197
+ ydconfig.save(cfg)
198
+ self.log("info", f"Created daemon config {cfg.path}")
199
+ dlg = LoginDialog(self, self.window if self.window and self.window.isVisible() else None)
200
+ dlg.exec()
201
+
202
+ def after_login(self):
203
+ self.accountChanged.emit()
204
+ self.notify("Yandex Disk", "Signed in. Starting sync.", force=True)
205
+ self.daemon.start()
206
+
207
+ def logout(self):
208
+ def remove(*_):
209
+ auth = Path(self.load_ydconfig().auth).expanduser()
210
+ try:
211
+ auth.unlink()
212
+ self.log("info", f"Signed out, removed {auth}")
213
+ except OSError as e:
214
+ self.log("error", f"Could not remove {auth}: {e}")
215
+ self.accountChanged.emit()
216
+ if self.daemon.status.running:
217
+ self.daemon.stop(remove)
218
+ else:
219
+ remove()
220
+
221
+ # ------------------------------------------------------------- shell ops
222
+ def open_url(self, url: str):
223
+ QDesktopServices.openUrl(QUrl(url))
224
+
225
+ def open_item(self, path: str):
226
+ if path and os.path.exists(path):
227
+ QDesktopServices.openUrl(QUrl.fromLocalFile(path))
228
+ else:
229
+ self.log("warn", f"Not found on this computer: {path}")
230
+ self.notify("Yandex Disk", f"Not found on this computer: {os.path.basename(path)}", "warn", force=True)
231
+
232
+ def reveal(self, path: str):
233
+ import shutil
234
+ import subprocess
235
+ if shutil.which("dbus-send"):
236
+ uri = QUrl.fromLocalFile(path).toString()
237
+ r = subprocess.run(["dbus-send", "--session", "--print-reply", "--dest=org.freedesktop.FileManager1",
238
+ "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1.ShowItems",
239
+ f"array:string:{uri}", "string:"], capture_output=True)
240
+ if r.returncode == 0:
241
+ return
242
+ self.open_item(os.path.dirname(path) or path)
243
+
244
+ def open_sync_folder(self):
245
+ self.open_item(self.sync_dir())
246
+
247
+ def copy(self, text: str, toast: str = ""):
248
+ QGuiApplication.clipboard().setText(text)
249
+ if toast:
250
+ self.log("info", f"{toast}: {text}")
251
+
252
+ def publish_path(self, path: str):
253
+ def done(code, out, url):
254
+ if code == 0 and url:
255
+ self.published.add(path, url)
256
+ self.publishedChanged.emit()
257
+ self.copy(url)
258
+ self.log("info", f"Public link for {path}: {url}")
259
+ if self.settings["notify_publish"]:
260
+ self.notify("Link copied", f"{os.path.basename(path)}\n{url}")
261
+ else:
262
+ self.notify("Could not share", (out.splitlines() or ["Unknown error"])[-1], "error", force=True)
263
+ self.daemon.publish(path, done)
264
+
265
+ def unpublish_path(self, path: str):
266
+ def done(code, out):
267
+ if code == 0:
268
+ self.published.remove(path)
269
+ self.publishedChanged.emit()
270
+ self.notify("Link removed", os.path.basename(path))
271
+ else:
272
+ self.notify("Could not remove link", (out.splitlines() or ["Unknown error"])[-1], "error",
273
+ force=True)
274
+ self.daemon.unpublish(path, done)
275
+
276
+ # ------------------------------------------------------------- window
277
+ def show_page(self, page: str | None):
278
+ w = self.window
279
+ if page:
280
+ w.show_page(page)
281
+ w.show()
282
+ w.setWindowState(w.windowState() & ~Qt.WindowMinimized)
283
+ w.raise_()
284
+ w.activateWindow()
285
+
286
+ def toggle_window(self):
287
+ if self.window.isVisible() and self.window.isActiveWindow():
288
+ self.window.close()
289
+ else:
290
+ self.show_page(None)
291
+
292
+ def set_theme(self, mode: str):
293
+ self.settings.set("theme", mode)
294
+ self.colors = theme.apply(self.app, mode)
295
+ self.themeChanged.emit(self.colors)
296
+ if self.tray:
297
+ self.tray.rebuild()
298
+
299
+ def set_tray_style(self, style: str):
300
+ self.settings.set("tray_style", style)
301
+ if self.tray:
302
+ self.tray.rebuild()
303
+
304
+ def handle_message(self, msg: str):
305
+ cmd, _, arg = msg.partition(":")
306
+ if cmd == "show":
307
+ self.show_page(arg or None)
308
+ elif cmd == "quit":
309
+ self.quit(stop_daemon=arg == "stop")
310
+ elif cmd == "sync":
311
+ self.daemon.sync()
312
+
313
+ def quit(self, stop_daemon: bool | None = None):
314
+ if self.settings["confirm_quit"]:
315
+ if QMessageBox.question(None, "Quit Yandex Disk",
316
+ "Quit the tray app? The daemon keeps its current state.") != QMessageBox.Yes:
317
+ return
318
+ stop = self.settings["stop_daemon_on_quit"] if stop_daemon is None else stop_daemon
319
+ if stop and self.daemon.status.running:
320
+ self.daemon.stop(lambda *_: self.app.quit())
321
+ QTimer.singleShot(5000, self.app.quit)
322
+ else:
323
+ self.app.quit()
324
+
325
+ def _about_to_quit(self):
326
+ if self.window:
327
+ self.settings.set("window_geometry", bytes(self.window.saveGeometry().toBase64()).decode())
328
+ self.daemon.stop_polling()
329
+ if self.tray:
330
+ self.tray.hide()
331
+
332
+
333
+ def run_gui(hidden: bool = False, page: str | None = None) -> int:
334
+ app = QApplication.instance() or QApplication(sys.argv[:1])
335
+ app.setApplicationName("yandexdisk")
336
+ app.setApplicationDisplayName("Yandex Disk")
337
+ app.setDesktopFileName("yandexdisk")
338
+ app.setQuitOnLastWindowClosed(False)
339
+ app.setWindowIcon(icons.app_icon())
340
+ theme.apply_font(app)
341
+
342
+ if send_to_running(f"show:{page or ''}" if (page or not hidden) else "noop"):
343
+ return 0
344
+ QLocalServer.removeServer(SERVER_NAME)
345
+ server = QLocalServer()
346
+ server.listen(SERVER_NAME)
347
+
348
+ ctx = Context(app)
349
+
350
+ def on_conn():
351
+ sock = server.nextPendingConnection()
352
+ if sock is None:
353
+ return
354
+
355
+ def read():
356
+ ctx.handle_message(bytes(sock.readAll()).decode(errors="replace"))
357
+ sock.readyRead.connect(read)
358
+ sock.disconnected.connect(sock.deleteLater)
359
+ server.newConnection.connect(on_conn)
360
+
361
+ ctx.start(hidden=hidden, page=page)
362
+ app._yd_ctx = ctx # keep alive
363
+ return app.exec()
@@ -0,0 +1,64 @@
1
+ """XDG autostart and application-menu entries."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .icons import app_icon_svg
10
+
11
+ CONFIG_HOME = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
12
+ DATA_HOME = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
13
+ AUTOSTART = CONFIG_HOME / "autostart" / "yandexdisk.desktop"
14
+ MENU = DATA_HOME / "applications" / "yandexdisk.desktop"
15
+ ICON = DATA_HOME / "icons" / "hicolor" / "scalable" / "apps" / "yandexdisk.svg"
16
+
17
+
18
+ def _exec() -> str:
19
+ exe = shutil.which("yandexdisk")
20
+ return exe if exe else f"{sys.executable} -m yandexdisk"
21
+
22
+
23
+ def _desktop(hidden: bool) -> str:
24
+ return "\n".join([
25
+ "[Desktop Entry]",
26
+ "Type=Application",
27
+ "Name=Yandex Disk",
28
+ "GenericName=Cloud sync",
29
+ "Comment=Tray control center for the Yandex Disk sync daemon",
30
+ f"Exec={_exec()}" + (" --hidden" if hidden else ""),
31
+ "Icon=yandexdisk",
32
+ "Terminal=false",
33
+ "Categories=Network;FileTransfer;Utility;",
34
+ "Keywords=yandex;disk;cloud;sync;",
35
+ "StartupNotify=false",
36
+ "X-GNOME-Autostart-enabled=true",
37
+ "X-GNOME-Autostart-Delay=5",
38
+ "",
39
+ ])
40
+
41
+
42
+ def _install_icon() -> None:
43
+ ICON.parent.mkdir(parents=True, exist_ok=True)
44
+ ICON.write_text(app_icon_svg(), encoding="utf-8")
45
+
46
+
47
+ def is_enabled() -> bool:
48
+ return AUTOSTART.is_file()
49
+
50
+
51
+ def set_enabled(on: bool) -> None:
52
+ if on:
53
+ _install_icon()
54
+ AUTOSTART.parent.mkdir(parents=True, exist_ok=True)
55
+ AUTOSTART.write_text(_desktop(hidden=True), encoding="utf-8")
56
+ elif AUTOSTART.exists():
57
+ AUTOSTART.unlink()
58
+
59
+
60
+ def install_menu_entry() -> Path:
61
+ _install_icon()
62
+ MENU.parent.mkdir(parents=True, exist_ok=True)
63
+ MENU.write_text(_desktop(hidden=False), encoding="utf-8")
64
+ return MENU
yandexdisk/cli.py ADDED
@@ -0,0 +1,243 @@
1
+ """Command line: `yandexdisk` (or `yd`). With no command it starts the tray app."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import __version__
12
+
13
+ VERSION_FLAGS = {"-v", "-V", "--version", "--Version", "-version", "--VERSION", "version"}
14
+
15
+ PAGES = ["overview", "activity", "published", "general", "account", "folders", "exclusions", "network",
16
+ "notifications", "appearance", "diagnostics", "console", "about"]
17
+
18
+
19
+ def _settings():
20
+ from .settings import Settings
21
+ return Settings()
22
+
23
+
24
+ def _binary() -> str | None:
25
+ from .daemon import find_binary
26
+ return find_binary(_settings()["binary"])
27
+
28
+
29
+ def _cfg_args() -> list[str]:
30
+ p = Path(os.path.expanduser(_settings()["config_path"]))
31
+ return ["-c", str(p)] if p.is_file() else []
32
+
33
+
34
+ def _daemon(args: list[str], capture: bool = False) -> tuple[int, str]:
35
+ binary = _binary()
36
+ if not binary:
37
+ from .diagnostics import install_hint
38
+ print("yandex-disk is not installed. Install it with:\n " + install_hint(), file=sys.stderr)
39
+ return 127, ""
40
+ env = dict(os.environ, LC_ALL="C", LANG="C")
41
+ if capture:
42
+ p = subprocess.run([binary, *args], capture_output=True, text=True, env=env)
43
+ return p.returncode, (p.stdout + p.stderr).strip()
44
+ return subprocess.call([binary, *args], env=env), ""
45
+
46
+
47
+ def _send(msg: str) -> bool:
48
+ from PySide6.QtCore import QCoreApplication
49
+ from .app import send_to_running
50
+ _app = QCoreApplication.instance() or QCoreApplication([])
51
+ return send_to_running(msg)
52
+
53
+
54
+ def cmd_status(a) -> int:
55
+ from .status import format_size, parse_status
56
+ code, out = _daemon(["status", *_cfg_args()], capture=True)
57
+ if code == 127:
58
+ return code
59
+ st = parse_status(out, code)
60
+ if a.json:
61
+ print(json.dumps({k: v for k, v in st.__dict__.items() if k != "raw"}, indent=2))
62
+ return 0
63
+ if a.raw:
64
+ print(out)
65
+ return 0
66
+ print(f"State {st.title}" + (f" ({st.raw_state})" if st.raw_state else ""))
67
+ if st.path:
68
+ print(f"Folder {st.path}")
69
+ if st.total:
70
+ print(f"Used {format_size(st.used)} of {format_size(st.total)}, {format_size(st.available)} free")
71
+ if st.trash is not None:
72
+ print(f"Trash {format_size(st.trash)}")
73
+ if st.progress_total:
74
+ print(f"Progress {format_size(st.progress_done)} of {format_size(st.progress_total)} "
75
+ f"({st.progress_pct or 0:.0f}%)")
76
+ for e in st.errors:
77
+ print(f"Error {e}")
78
+ if st.last_items:
79
+ print("Recently synced")
80
+ for kind, path in st.last_items:
81
+ print(f" {'dir ' if kind == 'dir' else 'file'} {path}")
82
+ return 0 if st.state != "stopped" else 3
83
+
84
+
85
+ def cmd_simple(name: str):
86
+ def run(a) -> int:
87
+ args = [name] + (_cfg_args() if name == "start" else [])
88
+ code, _ = _daemon(args)
89
+ return code
90
+ return run
91
+
92
+
93
+ def cmd_restart(a) -> int:
94
+ _daemon(["stop"])
95
+ return _daemon(["start", *_cfg_args()])[0]
96
+
97
+
98
+ def cmd_publish(a) -> int:
99
+ code, out = _daemon(["publish", *(["--overwrite"] if a.overwrite else []), a.path], capture=True)
100
+ print(out)
101
+ if code == 0:
102
+ from .daemon import URL_RE
103
+ from .settings import Published
104
+ m = URL_RE.search(out)
105
+ if m:
106
+ Published().add(os.path.abspath(a.path), m.group(0))
107
+ return code
108
+
109
+
110
+ def cmd_unpublish(a) -> int:
111
+ code, out = _daemon(["unpublish", a.path], capture=True)
112
+ print(out)
113
+ if code == 0:
114
+ from .settings import Published
115
+ Published().remove(os.path.abspath(a.path))
116
+ return code
117
+
118
+
119
+ def cmd_login(a) -> int:
120
+ from . import ydconfig
121
+ cfg = ydconfig.load(os.path.expanduser(_settings()["config_path"]))
122
+ if not cfg.exists:
123
+ Path(cfg.dir).expanduser().mkdir(parents=True, exist_ok=True)
124
+ ydconfig.save(cfg)
125
+ print(f"Created {cfg.path}")
126
+ Path(cfg.auth).expanduser().parent.mkdir(parents=True, exist_ok=True)
127
+ return _daemon(["token", str(Path(cfg.auth).expanduser())])[0]
128
+
129
+
130
+ def cmd_doctor(a) -> int:
131
+ from .diagnostics import FAIL, report, run_checks
132
+ checks = run_checks(_settings())
133
+ print(report(checks))
134
+ return 1 if any(c.level == FAIL for c in checks) else 0
135
+
136
+
137
+ def cmd_open(a) -> int:
138
+ from . import ydconfig
139
+ folder = os.path.expanduser(ydconfig.load(os.path.expanduser(_settings()["config_path"])).dir)
140
+ return subprocess.call(["xdg-open", folder])
141
+
142
+
143
+ def cmd_web(a) -> int:
144
+ return subprocess.call(["xdg-open", "https://disk.yandex.com/client/disk"])
145
+
146
+
147
+ def cmd_settings(a) -> int:
148
+ page = a.page or "general"
149
+ if _send(f"show:{page}"):
150
+ return 0
151
+ from .app import run_gui
152
+ return run_gui(page=page)
153
+
154
+
155
+ def cmd_quit(a) -> int:
156
+ if _send("quit:stop" if a.stop else "quit:"):
157
+ return 0
158
+ print("The tray app is not running.")
159
+ return 1
160
+
161
+
162
+ def cmd_autostart(a) -> int:
163
+ from . import autostart
164
+ if a.state == "status":
165
+ print("on" if autostart.is_enabled() else "off")
166
+ else:
167
+ autostart.set_enabled(a.state == "on")
168
+ print(f"Autostart {a.state}: {autostart.AUTOSTART}")
169
+ return 0
170
+
171
+
172
+ def cmd_install_desktop(a) -> int:
173
+ from . import autostart
174
+ print(f"Added {autostart.install_menu_entry()}")
175
+ return 0
176
+
177
+
178
+ def cmd_update(a) -> int:
179
+ base = [sys.executable, "-m", "pip", "install", "--upgrade", "yandexdisk"]
180
+ p = subprocess.run(base, capture_output=True, text=True)
181
+ if p.returncode != 0 and "externally-managed-environment" in (p.stdout + p.stderr):
182
+ p = subprocess.run(base + ["--break-system-packages"], capture_output=True, text=True)
183
+ print((p.stdout + p.stderr).strip())
184
+ return p.returncode
185
+
186
+
187
+ def build_parser() -> argparse.ArgumentParser:
188
+ ap = argparse.ArgumentParser(
189
+ prog="yandexdisk",
190
+ description="Tray control center for the Yandex Disk console client. Run with no command to start "
191
+ "the tray app.")
192
+ ap.add_argument("--hidden", action="store_true", help="start in the tray without opening the window")
193
+ ap.add_argument("--page", choices=PAGES, help="open the control center on this page")
194
+ sub = ap.add_subparsers(dest="command", metavar="command")
195
+
196
+ p = sub.add_parser("status", help="show the daemon status")
197
+ p.add_argument("--json", action="store_true", help="print parsed status as JSON")
198
+ p.add_argument("--raw", action="store_true", help="print the daemon output as is")
199
+ p.set_defaults(func=cmd_status)
200
+ for name, text in [("start", "start the sync daemon"), ("stop", "stop the sync daemon"),
201
+ ("sync", "ask the daemon to sync now")]:
202
+ sub.add_parser(name, help=text).set_defaults(func=cmd_simple(name))
203
+ sub.add_parser("restart", help="stop and start the daemon").set_defaults(func=cmd_restart)
204
+ p = sub.add_parser("publish", help="share a file or folder and print its public link")
205
+ p.add_argument("path")
206
+ p.add_argument("--overwrite", action="store_true", help="replace a file with the same name on Disk")
207
+ p.set_defaults(func=cmd_publish)
208
+ p = sub.add_parser("unpublish", help="remove the public link of a file or folder")
209
+ p.add_argument("path")
210
+ p.set_defaults(func=cmd_unpublish)
211
+ sub.add_parser("login", help="sign in to Yandex in this terminal").set_defaults(func=cmd_login)
212
+ sub.add_parser("doctor", help="run diagnostics and print a report").set_defaults(func=cmd_doctor)
213
+ sub.add_parser("open", help="open the Yandex Disk folder").set_defaults(func=cmd_open)
214
+ sub.add_parser("web", help="open Yandex Disk in the browser").set_defaults(func=cmd_web)
215
+ p = sub.add_parser("settings", help="open the control center on a page")
216
+ p.add_argument("page", nargs="?", choices=PAGES)
217
+ p.set_defaults(func=cmd_settings)
218
+ p = sub.add_parser("quit", help="quit the running tray app")
219
+ p.add_argument("--stop", action="store_true", help="also stop the sync daemon")
220
+ p.set_defaults(func=cmd_quit)
221
+ p = sub.add_parser("autostart", help="open the tray app at login")
222
+ p.add_argument("state", choices=["on", "off", "status"])
223
+ p.set_defaults(func=cmd_autostart)
224
+ sub.add_parser("install-desktop", help="add Yandex Disk to the application menu").set_defaults(
225
+ func=cmd_install_desktop)
226
+ sub.add_parser("update", help="upgrade yandexdisk from PyPI").set_defaults(func=cmd_update)
227
+ return ap
228
+
229
+
230
+ def main(argv: list[str] | None = None) -> int:
231
+ argv = list(sys.argv[1:] if argv is None else argv)
232
+ if argv and argv[0] in VERSION_FLAGS:
233
+ print(f"yandexdisk {__version__}")
234
+ return 0
235
+ a = build_parser().parse_args(argv)
236
+ if getattr(a, "func", None):
237
+ return int(a.func(a) or 0)
238
+ from .app import run_gui
239
+ return run_gui(hidden=a.hidden, page=a.page)
240
+
241
+
242
+ if __name__ == "__main__":
243
+ sys.exit(main())