lapctl 0.1.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.
- lapctl/__init__.py +3 -0
- lapctl/channels/__init__.py +1 -0
- lapctl/channels/telegram/__init__.py +1 -0
- lapctl/channels/telegram/api.py +336 -0
- lapctl/channels/telegram/auth.py +29 -0
- lapctl/channels/telegram/handlers.py +161 -0
- lapctl/channels/telegram/poller.py +163 -0
- lapctl/channels/telegram/render.py +166 -0
- lapctl/cli.py +527 -0
- lapctl/config.py +163 -0
- lapctl/core/__init__.py +1 -0
- lapctl/core/battery.py +69 -0
- lapctl/core/commands.py +1260 -0
- lapctl/core/confirm.py +68 -0
- lapctl/core/keyboards.py +140 -0
- lapctl/core/paths.py +77 -0
- lapctl/core/ratelimit.py +30 -0
- lapctl/drivers/__init__.py +1 -0
- lapctl/drivers/base.py +163 -0
- lapctl/drivers/linux_hyprland.py +574 -0
- lapctl/main.py +86 -0
- lapctl/registry.py +110 -0
- lapctl/results.py +86 -0
- lapctl-0.1.1.dist-info/METADATA +149 -0
- lapctl-0.1.1.dist-info/RECORD +29 -0
- lapctl-0.1.1.dist-info/WHEEL +5 -0
- lapctl-0.1.1.dist-info/entry_points.txt +2 -0
- lapctl-0.1.1.dist-info/licenses/LICENSE +21 -0
- lapctl-0.1.1.dist-info/top_level.txt +1 -0
lapctl/cli.py
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""Command-line interface for Lapctl."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import socket
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
import tomllib
|
|
14
|
+
import webbrowser
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
|
|
20
|
+
from lapctl import __version__
|
|
21
|
+
from lapctl.channels.telegram.api import TelegramClient
|
|
22
|
+
from lapctl.config import (
|
|
23
|
+
default_config_path,
|
|
24
|
+
get_bot_token,
|
|
25
|
+
get_owner_id,
|
|
26
|
+
write_toml_config,
|
|
27
|
+
)
|
|
28
|
+
from lapctl.drivers.linux_hyprland import LinuxHyprlandDriver
|
|
29
|
+
from lapctl.main import main as run_agent
|
|
30
|
+
|
|
31
|
+
SERVICE_NAME = "lapctl.service"
|
|
32
|
+
|
|
33
|
+
BANNER_PARTS: list[tuple[str, str]] = [
|
|
34
|
+
("░█░░░█▀█░█▀█", "░█▀▀░▀█▀░█░░"),
|
|
35
|
+
("░█░░░█▀█░█▀▀", "░█░░░░█░░█░░"),
|
|
36
|
+
("░▀▀▀░▀░▀░▀░░", "░▀▀▀░░▀░░▀▀▀"),
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def print_banner() -> None:
|
|
41
|
+
"""Clear terminal on TTY and print the Lapctl banner with top spacing."""
|
|
42
|
+
is_tty = sys.stdout.isatty()
|
|
43
|
+
if is_tty:
|
|
44
|
+
print("\033[2J\033[H", end="")
|
|
45
|
+
print("\n")
|
|
46
|
+
use_color = is_tty and not os.environ.get("NO_COLOR")
|
|
47
|
+
gray = "\033[38;2;145;145;152m" if use_color else ""
|
|
48
|
+
white = "\033[38;2;255;255;255m" if use_color else ""
|
|
49
|
+
reset = "\033[0m" if use_color else ""
|
|
50
|
+
for left, right in BANNER_PARTS:
|
|
51
|
+
print(f"{gray}{left}{white}{right}{reset}")
|
|
52
|
+
print()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
DOCTOR_TOOLS: list[tuple[str, str, str]] = [
|
|
56
|
+
("grim", "Screenshot (/ss)", "sudo pacman -S grim | sudo apt install grim"),
|
|
57
|
+
(
|
|
58
|
+
"ffmpeg",
|
|
59
|
+
"Webcam & audio (/cam, /vid, /record)",
|
|
60
|
+
"sudo pacman -S ffmpeg | sudo apt install ffmpeg",
|
|
61
|
+
),
|
|
62
|
+
("wf-recorder", "Rekam layar (/screenrecord)", "sudo pacman -S wf-recorder"),
|
|
63
|
+
("hyprlock", "Kunci layar (/lock)", "sudo pacman -S hyprlock"),
|
|
64
|
+
("hyprctl", "Kontrol Hyprland & kursor", "Bagian dari paket hyprland"),
|
|
65
|
+
(
|
|
66
|
+
"wpctl",
|
|
67
|
+
"Kontrol volume & mute",
|
|
68
|
+
"sudo pacman -S wireplumber | sudo apt install wireplumber",
|
|
69
|
+
),
|
|
70
|
+
(
|
|
71
|
+
"brightnessctl",
|
|
72
|
+
"Kecerahan layar (/brightness)",
|
|
73
|
+
"sudo pacman -S brightnessctl | sudo apt install brightnessctl",
|
|
74
|
+
),
|
|
75
|
+
(
|
|
76
|
+
"playerctl",
|
|
77
|
+
"Kontrol media (/play, /pause, /next)",
|
|
78
|
+
"sudo pacman -S playerctl | sudo apt install playerctl",
|
|
79
|
+
),
|
|
80
|
+
(
|
|
81
|
+
"wl-copy",
|
|
82
|
+
"Clipboard tulis (/setclip)",
|
|
83
|
+
"sudo pacman -S wl-clipboard | sudo apt install wl-clipboard",
|
|
84
|
+
),
|
|
85
|
+
(
|
|
86
|
+
"wl-paste",
|
|
87
|
+
"Clipboard baca (/getclip)",
|
|
88
|
+
"sudo pacman -S wl-clipboard | sudo apt install wl-clipboard",
|
|
89
|
+
),
|
|
90
|
+
("swww", "Wallpaper (/wallpaper)", "sudo pacman -S swww"),
|
|
91
|
+
(
|
|
92
|
+
"notify-send",
|
|
93
|
+
"Notifikasi desktop (/notify)",
|
|
94
|
+
"sudo pacman -S libnotify | sudo apt install libnotify-bin",
|
|
95
|
+
),
|
|
96
|
+
(
|
|
97
|
+
"xdotool",
|
|
98
|
+
"Input mouse/keyboard (/mouse, /keyboard)",
|
|
99
|
+
"sudo pacman -S xdotool | sudo apt install xdotool",
|
|
100
|
+
),
|
|
101
|
+
("mpv", "Pemutar TTS (/say)", "sudo pacman -S mpv | sudo apt install mpv"),
|
|
102
|
+
(
|
|
103
|
+
"paplay",
|
|
104
|
+
"Suara beep (/beep)",
|
|
105
|
+
"sudo pacman -S libpulse | sudo apt install pulseaudio-utils",
|
|
106
|
+
),
|
|
107
|
+
(
|
|
108
|
+
"nmcli",
|
|
109
|
+
"Info WiFi (/status)",
|
|
110
|
+
"sudo pacman -S networkmanager | sudo apt install network-manager",
|
|
111
|
+
),
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _systemd_service_path() -> Path:
|
|
116
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
117
|
+
base = Path(xdg) if xdg else Path.home() / ".config"
|
|
118
|
+
return base / "systemd" / "user" / SERVICE_NAME
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _wait_for_owner_message(
|
|
122
|
+
token: str,
|
|
123
|
+
bot_username: str,
|
|
124
|
+
timeout_seconds: int = 120,
|
|
125
|
+
) -> tuple[int, str] | None:
|
|
126
|
+
"""Poll getUpdates for the first private message to detect owner_id."""
|
|
127
|
+
url = f"https://api.telegram.org/bot{token}/getUpdates"
|
|
128
|
+
deadline = time.monotonic() + timeout_seconds
|
|
129
|
+
offset: int | None = None
|
|
130
|
+
|
|
131
|
+
print(
|
|
132
|
+
f"\nKirim pesan apa saja ke @{bot_username} dari chat privat Telegram sekarang "
|
|
133
|
+
f"(menunggu maksimal {timeout_seconds} detik)..."
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
while time.monotonic() < deadline:
|
|
137
|
+
remaining = max(1, min(15, int(deadline - time.monotonic())))
|
|
138
|
+
params: dict[str, Any] = {"timeout": remaining}
|
|
139
|
+
if offset is not None:
|
|
140
|
+
params["offset"] = offset
|
|
141
|
+
try:
|
|
142
|
+
r = requests.get(url, params=params, timeout=remaining + 5)
|
|
143
|
+
if r.status_code == 409:
|
|
144
|
+
print(
|
|
145
|
+
"\n⚠️ Konflik (HTTP 409): bot ini sedang dipoll proses lain. "
|
|
146
|
+
"Hentikan instance lain terlebih dahulu lalu coba lagi."
|
|
147
|
+
)
|
|
148
|
+
return None
|
|
149
|
+
if r.status_code != 200:
|
|
150
|
+
time.sleep(2)
|
|
151
|
+
continue
|
|
152
|
+
data = r.json()
|
|
153
|
+
for update in data.get("result", []):
|
|
154
|
+
offset = update["update_id"] + 1
|
|
155
|
+
msg = update.get("message")
|
|
156
|
+
if not msg:
|
|
157
|
+
continue
|
|
158
|
+
chat_type = msg.get("chat", {}).get("type")
|
|
159
|
+
if chat_type != "private":
|
|
160
|
+
continue
|
|
161
|
+
sender = msg.get("from", {})
|
|
162
|
+
sender_id = int(sender.get("id", 0))
|
|
163
|
+
username = sender.get("username") or sender.get("first_name") or "Unknown"
|
|
164
|
+
if sender_id > 0:
|
|
165
|
+
return sender_id, str(username)
|
|
166
|
+
except requests.exceptions.RequestException:
|
|
167
|
+
time.sleep(2)
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _install_linux_autostart() -> bool:
|
|
172
|
+
"""Create and enable systemd --user service for lapctl."""
|
|
173
|
+
if not sys.platform.startswith("linux") or shutil.which("systemctl") is None:
|
|
174
|
+
return False
|
|
175
|
+
|
|
176
|
+
exe = shutil.which("lapctl") or f"{sys.executable} -m lapctl.cli"
|
|
177
|
+
exec_start = f"{exe} start" if " " not in exe else f"{sys.executable} -m lapctl.cli start"
|
|
178
|
+
|
|
179
|
+
service_path = _systemd_service_path()
|
|
180
|
+
service_path.parent.mkdir(parents=True, exist_ok=True)
|
|
181
|
+
service_content = (
|
|
182
|
+
"[Unit]\n"
|
|
183
|
+
"Description=Lapctl Remote Laptop Agent\n"
|
|
184
|
+
"After=network-online.target graphical-session.target\n"
|
|
185
|
+
"\n"
|
|
186
|
+
"[Service]\n"
|
|
187
|
+
f"ExecStart={exec_start}\n"
|
|
188
|
+
"Restart=on-failure\n"
|
|
189
|
+
"RestartSec=5\n"
|
|
190
|
+
"\n"
|
|
191
|
+
"[Install]\n"
|
|
192
|
+
"WantedBy=default.target\n"
|
|
193
|
+
)
|
|
194
|
+
service_path.write_text(service_content, encoding="utf-8")
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True, timeout=10)
|
|
198
|
+
subprocess.run(
|
|
199
|
+
["systemctl", "--user", "enable", "--now", SERVICE_NAME], check=True, timeout=10
|
|
200
|
+
)
|
|
201
|
+
return True
|
|
202
|
+
except Exception:
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def cmd_setup() -> int:
|
|
207
|
+
"""Interactive setup wizard for first-time configuration."""
|
|
208
|
+
print_banner()
|
|
209
|
+
print(f"Python: {sys.version.split()[0]} | Platform: {sys.platform}")
|
|
210
|
+
driver_ok = LinuxHyprlandDriver.detect()
|
|
211
|
+
print(
|
|
212
|
+
f"Driver terdeteksi: {'linux_hyprland' if driver_ok else 'belum terdeteksi (mode generik)'}"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
cfg_path = default_config_path()
|
|
216
|
+
if cfg_path.exists():
|
|
217
|
+
ans = input(f"\nKonfigurasi sudah ada di {cfg_path}. Timpa ulang? [y/N]: ").strip().lower()
|
|
218
|
+
if ans not in {"y", "ya", "yes"}:
|
|
219
|
+
print("Setup dibatalkan.")
|
|
220
|
+
return 0
|
|
221
|
+
|
|
222
|
+
print("\nLangkah 1: Buat bot Telegram")
|
|
223
|
+
print("1. Buka https://t.me/BotFather di Telegram")
|
|
224
|
+
print("2. Kirim /newbot dan ikuti petunjuk hingga mendapat Bot Token.\n")
|
|
225
|
+
|
|
226
|
+
open_bf = input("Buka https://t.me/BotFather di browser sekarang? [Y/n]: ").strip().lower()
|
|
227
|
+
if open_bf not in {"n", "no", "tidak"}:
|
|
228
|
+
try:
|
|
229
|
+
if not webbrowser.open("https://t.me/BotFather"):
|
|
230
|
+
print("Silakan buka https://t.me/BotFather secara manual di browser/Telegram.")
|
|
231
|
+
except Exception:
|
|
232
|
+
print("Silakan buka https://t.me/BotFather secara manual di browser/Telegram.")
|
|
233
|
+
|
|
234
|
+
client: TelegramClient | None = None
|
|
235
|
+
bot_info: dict[str, Any] | None = None
|
|
236
|
+
token = ""
|
|
237
|
+
|
|
238
|
+
while True:
|
|
239
|
+
try:
|
|
240
|
+
token = getpass.getpass("Masukkan Bot Token (input disembunyikan): ").strip()
|
|
241
|
+
except (KeyboardInterrupt, EOFError):
|
|
242
|
+
print("\nSetup dibatalkan.")
|
|
243
|
+
return 1
|
|
244
|
+
if not token:
|
|
245
|
+
print("Token tidak boleh kosong.")
|
|
246
|
+
continue
|
|
247
|
+
|
|
248
|
+
candidate = TelegramClient(token)
|
|
249
|
+
info = candidate.get_me()
|
|
250
|
+
if info:
|
|
251
|
+
client = candidate
|
|
252
|
+
bot_info = info
|
|
253
|
+
break
|
|
254
|
+
print("❌ Token tidak valid atau gagal menghubungi api.telegram.org. Coba lagi.")
|
|
255
|
+
|
|
256
|
+
assert client is not None and bot_info is not None
|
|
257
|
+
bot_username = str(bot_info.get("username", "bot"))
|
|
258
|
+
print(f"✅ Terhubung ke bot @{bot_username}")
|
|
259
|
+
|
|
260
|
+
client.delete_webhook(drop_pending_updates=False)
|
|
261
|
+
|
|
262
|
+
detected = _wait_for_owner_message(token, bot_username, timeout_seconds=120)
|
|
263
|
+
if detected is None:
|
|
264
|
+
print("❌ Tidak menerima pesan privat dalam batas waktu atau terjadi konflik.")
|
|
265
|
+
return 1
|
|
266
|
+
|
|
267
|
+
owner_id, owner_username = detected
|
|
268
|
+
confirm = (
|
|
269
|
+
input(f"Terdeteksi @{owner_username} (ID: {owner_id}). Simpan sebagai pemilik? [Y/n]: ")
|
|
270
|
+
.strip()
|
|
271
|
+
.lower()
|
|
272
|
+
)
|
|
273
|
+
if confirm in {"n", "no", "tidak"}:
|
|
274
|
+
print("Setup dibatalkan.")
|
|
275
|
+
return 1
|
|
276
|
+
|
|
277
|
+
print("\nPilih profil izin:")
|
|
278
|
+
print(" 1) aman - Info sistem, media/volume/kecerahan, lock, power (konfirmasi)")
|
|
279
|
+
print(" 2) standar - (Default) Aman + screenshot, kamera, rekam, file allowed_roots")
|
|
280
|
+
print(" 3) lengkap - Standar + mouse/keyboard, upload file, clipboard tulis, /cmd")
|
|
281
|
+
prof_choice = input("Pilih [1/2/3] (default 2): ").strip()
|
|
282
|
+
profile_map = {"1": "aman", "2": "standar", "3": "lengkap"}
|
|
283
|
+
profile = profile_map.get(prof_choice, "standar")
|
|
284
|
+
if profile == "lengkap":
|
|
285
|
+
print("⚠️ Profil 'lengkap' mengaktifkan /cmd dan kontrol input penuh.")
|
|
286
|
+
|
|
287
|
+
lang_choice = input("Bahasa bot [id/en] (default id): ").strip().lower()
|
|
288
|
+
language = lang_choice if lang_choice in {"id", "en"} else "id"
|
|
289
|
+
|
|
290
|
+
default_name = socket.gethostname() or "My Laptop"
|
|
291
|
+
device_name = input(f"Nama perangkat (default '{default_name}'): ").strip() or default_name
|
|
292
|
+
|
|
293
|
+
data: dict[str, Any] = {
|
|
294
|
+
"telegram": {"bot_token": token, "owner_id": owner_id},
|
|
295
|
+
"general": {"device_name": device_name, "language": language, "profile": profile},
|
|
296
|
+
"files": {"allowed_roots": ["~/Downloads", "~/Documents", "~/Desktop", "~/Pictures"]},
|
|
297
|
+
"battery": {"notify_low": 20, "notify_full": True},
|
|
298
|
+
"external": {"tts": False, "geoip": False, "ntfy_topic": ""},
|
|
299
|
+
}
|
|
300
|
+
write_toml_config(cfg_path, data)
|
|
301
|
+
print(f"\n✅ Konfigurasi disimpan ke {cfg_path} (izin owner-only).")
|
|
302
|
+
|
|
303
|
+
install_svc = input("Pasang auto-start systemd user service? [Y/n]: ").strip().lower()
|
|
304
|
+
if install_svc not in {"n", "no", "tidak"}:
|
|
305
|
+
if _install_linux_autostart():
|
|
306
|
+
print(f"✅ Service {SERVICE_NAME} aktif dan berjalan.")
|
|
307
|
+
else:
|
|
308
|
+
print("⚠️ Gagal memasang service otomatis. Jalankan manual dengan: lapctl start")
|
|
309
|
+
|
|
310
|
+
client.send_message(owner_id, "Terhubung ✅")
|
|
311
|
+
print("\nSetup selesai! Kirim /menu ke bot Anda di Telegram.")
|
|
312
|
+
return 0
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def cmd_doctor() -> int:
|
|
316
|
+
"""Check Python, active driver, and system tool dependencies."""
|
|
317
|
+
print(f"Lapctl v{__version__}")
|
|
318
|
+
print(
|
|
319
|
+
f"Python: {sys.version.split()[0]} ({'OK' if sys.version_info >= (3, 11) else 'Perlu >= 3.11'})"
|
|
320
|
+
)
|
|
321
|
+
print(f"Platform: {sys.platform}")
|
|
322
|
+
print(
|
|
323
|
+
f"Driver linux_hyprland: {'terdeteksi' if LinuxHyprlandDriver.detect() else 'tidak terdeteksi'}"
|
|
324
|
+
)
|
|
325
|
+
cfg_path = default_config_path()
|
|
326
|
+
print(
|
|
327
|
+
f"Konfigurasi ({cfg_path}): {'ada' if cfg_path.exists() else 'belum ada (jalankan lapctl setup)'}"
|
|
328
|
+
)
|
|
329
|
+
print("\nPemeriksaan dependensi alat:")
|
|
330
|
+
|
|
331
|
+
missing = 0
|
|
332
|
+
for tool, desc, hint in DOCTOR_TOOLS:
|
|
333
|
+
found = shutil.which(tool) is not None
|
|
334
|
+
status = "OK" if found else "TIDAK ADA"
|
|
335
|
+
print(f" - {tool:<14} [{status:<9}] {desc}")
|
|
336
|
+
if not found:
|
|
337
|
+
missing += 1
|
|
338
|
+
print(f" Saran instalasi: {hint}")
|
|
339
|
+
|
|
340
|
+
if missing == 0:
|
|
341
|
+
print("\nSemua alat tersedia.")
|
|
342
|
+
else:
|
|
343
|
+
print(f"\n{missing} alat opsional/fitur tidak ditemukan.")
|
|
344
|
+
return 0
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _systemctl_user(action: str) -> int:
|
|
348
|
+
if shutil.which("systemctl") is None:
|
|
349
|
+
print("systemctl tidak tersedia di OS ini.")
|
|
350
|
+
return 1
|
|
351
|
+
res = subprocess.run(["systemctl", "--user", action, SERVICE_NAME], timeout=10)
|
|
352
|
+
return res.returncode
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def cmd_status() -> int:
|
|
356
|
+
"""Show service and Telegram connection status."""
|
|
357
|
+
cfg_path = default_config_path()
|
|
358
|
+
if not cfg_path.exists():
|
|
359
|
+
print(f"Konfigurasi belum ada di {cfg_path}. Jalankan 'lapctl setup'.")
|
|
360
|
+
return 1
|
|
361
|
+
|
|
362
|
+
with open(cfg_path, "rb") as f:
|
|
363
|
+
cfg = tomllib.load(f)
|
|
364
|
+
token = get_bot_token(cfg)
|
|
365
|
+
owner_id = get_owner_id(cfg)
|
|
366
|
+
print(f"Konfigurasi: {cfg_path}")
|
|
367
|
+
print(f"Profil : {cfg.get('general', {}).get('profile', 'standar')}")
|
|
368
|
+
print(f"Owner ID : {'terkonfigurasi' if owner_id > 0 else 'kosong (invalid)'}")
|
|
369
|
+
|
|
370
|
+
if shutil.which("systemctl") is not None:
|
|
371
|
+
res = subprocess.run(
|
|
372
|
+
["systemctl", "--user", "is-active", SERVICE_NAME],
|
|
373
|
+
capture_output=True,
|
|
374
|
+
text=True,
|
|
375
|
+
timeout=5,
|
|
376
|
+
)
|
|
377
|
+
print(f"Service : {res.stdout.strip() or 'inactive'}")
|
|
378
|
+
|
|
379
|
+
if token:
|
|
380
|
+
info = TelegramClient(token).get_me()
|
|
381
|
+
if info:
|
|
382
|
+
print(f"Telegram : terhubung (@{info.get('username', 'unknown')})")
|
|
383
|
+
else:
|
|
384
|
+
print("Telegram : gagal terhubung ke api.telegram.org")
|
|
385
|
+
return 0
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def cmd_logs(lines: int = 30) -> int:
|
|
389
|
+
"""Show recent journalctl logs for lapctl.service."""
|
|
390
|
+
if shutil.which("journalctl") is None:
|
|
391
|
+
print("journalctl tidak tersedia di OS ini.")
|
|
392
|
+
return 1
|
|
393
|
+
res = subprocess.run(
|
|
394
|
+
["journalctl", "--user", "-u", SERVICE_NAME, "-n", str(lines), "--no-pager"],
|
|
395
|
+
timeout=10,
|
|
396
|
+
)
|
|
397
|
+
return res.returncode
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def cmd_config(args: argparse.Namespace) -> int:
|
|
401
|
+
"""View or update configuration without ever printing secret tokens."""
|
|
402
|
+
cfg_path = default_config_path()
|
|
403
|
+
if not cfg_path.exists():
|
|
404
|
+
print(f"Konfigurasi belum ada di {cfg_path}. Jalankan 'lapctl setup'.")
|
|
405
|
+
return 1
|
|
406
|
+
|
|
407
|
+
with open(cfg_path, "rb") as f:
|
|
408
|
+
cfg = tomllib.load(f)
|
|
409
|
+
|
|
410
|
+
changed = False
|
|
411
|
+
if args.profile:
|
|
412
|
+
cfg.setdefault("general", {})["profile"] = args.profile
|
|
413
|
+
changed = True
|
|
414
|
+
if args.language:
|
|
415
|
+
cfg.setdefault("general", {})["language"] = args.language
|
|
416
|
+
changed = True
|
|
417
|
+
if args.device_name:
|
|
418
|
+
cfg.setdefault("general", {})["device_name"] = args.device_name
|
|
419
|
+
changed = True
|
|
420
|
+
if args.ntfy_topic is not None:
|
|
421
|
+
cfg.setdefault("external", {})["ntfy_topic"] = args.ntfy_topic
|
|
422
|
+
changed = True
|
|
423
|
+
|
|
424
|
+
if changed:
|
|
425
|
+
write_toml_config(cfg_path, cfg)
|
|
426
|
+
print(f"Konfigurasi diperbarui di {cfg_path}.")
|
|
427
|
+
|
|
428
|
+
gen = cfg.get("general", {})
|
|
429
|
+
ext = cfg.get("external", {})
|
|
430
|
+
print(f"Path : {cfg_path}")
|
|
431
|
+
print("bot_token : [DISEMBUNYIKAN]")
|
|
432
|
+
print(f"owner_id : {'[DISEMBUNYIKAN]' if get_owner_id(cfg) > 0 else '0'}")
|
|
433
|
+
print(f"device_name : {gen.get('device_name', 'My Laptop')}")
|
|
434
|
+
print(f"language : {gen.get('language', 'id')}")
|
|
435
|
+
print(f"profile : {gen.get('profile', 'standar')}")
|
|
436
|
+
print(f"ntfy_topic : {'[DISEMBUNYIKAN]' if ext.get('ntfy_topic') else '(kosong)'}")
|
|
437
|
+
return 0
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def cmd_uninstall() -> int:
|
|
441
|
+
"""Stop/disable user service and remove service + config files."""
|
|
442
|
+
ans = input("Hapus service dan konfigurasi Lapctl? [y/N]: ").strip().lower()
|
|
443
|
+
if ans not in {"y", "ya", "yes"}:
|
|
444
|
+
print("Dibatalkan.")
|
|
445
|
+
return 0
|
|
446
|
+
|
|
447
|
+
if shutil.which("systemctl") is not None:
|
|
448
|
+
subprocess.run(["systemctl", "--user", "disable", "--now", SERVICE_NAME], timeout=10)
|
|
449
|
+
svc_path = _systemd_service_path()
|
|
450
|
+
if svc_path.exists():
|
|
451
|
+
svc_path.unlink()
|
|
452
|
+
subprocess.run(["systemctl", "--user", "daemon-reload"], timeout=10)
|
|
453
|
+
|
|
454
|
+
cfg_path = default_config_path()
|
|
455
|
+
if cfg_path.exists():
|
|
456
|
+
cfg_path.unlink()
|
|
457
|
+
print("✅ Service dan konfigurasi Lapctl telah dihapus.")
|
|
458
|
+
return 0
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
462
|
+
"""Create the CLI argument parser."""
|
|
463
|
+
parser = argparse.ArgumentParser(
|
|
464
|
+
prog="lapctl",
|
|
465
|
+
description="Lapctl — remote laptop control agent via Telegram",
|
|
466
|
+
)
|
|
467
|
+
parser.add_argument(
|
|
468
|
+
"--version",
|
|
469
|
+
action="version",
|
|
470
|
+
version=f"lapctl {__version__}",
|
|
471
|
+
)
|
|
472
|
+
sub = parser.add_subparsers(dest="command")
|
|
473
|
+
|
|
474
|
+
sub.add_parser("setup", help="Wizard pemasangan awal")
|
|
475
|
+
sub.add_parser("start", help="Jalankan agent di foreground")
|
|
476
|
+
sub.add_parser("stop", help="Hentikan service lapctl")
|
|
477
|
+
sub.add_parser("restart", help="Mulai ulang service lapctl")
|
|
478
|
+
sub.add_parser("status", help="Status service dan koneksi Telegram")
|
|
479
|
+
logs_p = sub.add_parser("logs", help="Lihat log terbaru")
|
|
480
|
+
logs_p.add_argument("-n", "--lines", type=int, default=30, help="Jumlah baris log")
|
|
481
|
+
sub.add_parser("doctor", help="Cek dependensi dan kemampuan driver")
|
|
482
|
+
|
|
483
|
+
cfg_p = sub.add_parser("config", help="Lihat atau ubah pengaturan")
|
|
484
|
+
cfg_p.add_argument("--profile", choices=["aman", "standar", "lengkap"])
|
|
485
|
+
cfg_p.add_argument("--language", choices=["id", "en"])
|
|
486
|
+
cfg_p.add_argument("--device-name")
|
|
487
|
+
cfg_p.add_argument("--ntfy-topic")
|
|
488
|
+
|
|
489
|
+
sub.add_parser("uninstall", help="Hapus service dan konfigurasi")
|
|
490
|
+
return parser
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def main(argv: list[str] | None = None) -> int:
|
|
494
|
+
"""CLI entrypoint."""
|
|
495
|
+
parser = build_parser()
|
|
496
|
+
args = parser.parse_args(argv)
|
|
497
|
+
|
|
498
|
+
if args.command is None:
|
|
499
|
+
print_banner()
|
|
500
|
+
parser.print_help()
|
|
501
|
+
return 0
|
|
502
|
+
if args.command == "setup":
|
|
503
|
+
return cmd_setup()
|
|
504
|
+
if args.command == "start":
|
|
505
|
+
run_agent()
|
|
506
|
+
return 0
|
|
507
|
+
if args.command == "stop":
|
|
508
|
+
return _systemctl_user("stop")
|
|
509
|
+
if args.command == "restart":
|
|
510
|
+
return _systemctl_user("restart")
|
|
511
|
+
if args.command == "status":
|
|
512
|
+
return cmd_status()
|
|
513
|
+
if args.command == "logs":
|
|
514
|
+
return cmd_logs(lines=args.lines)
|
|
515
|
+
if args.command == "doctor":
|
|
516
|
+
return cmd_doctor()
|
|
517
|
+
if args.command == "config":
|
|
518
|
+
return cmd_config(args)
|
|
519
|
+
if args.command == "uninstall":
|
|
520
|
+
return cmd_uninstall()
|
|
521
|
+
|
|
522
|
+
parser.print_help()
|
|
523
|
+
return 1
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
if __name__ == "__main__":
|
|
527
|
+
raise SystemExit(main())
|
lapctl/config.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""TOML configuration loading, OS-standard paths, and legacy JSON migration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import tomllib
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_config_dir() -> Path:
|
|
14
|
+
"""Return the OS-standard configuration directory for Lapctl."""
|
|
15
|
+
if os.name == "nt":
|
|
16
|
+
appdata = os.environ.get("APPDATA")
|
|
17
|
+
base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming"
|
|
18
|
+
return base / "lapctl"
|
|
19
|
+
if sys.platform == "darwin":
|
|
20
|
+
return Path.home() / "Library" / "Application Support" / "lapctl"
|
|
21
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
22
|
+
base = Path(xdg) if xdg else Path.home() / ".config"
|
|
23
|
+
return base / "lapctl"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def default_config_path() -> Path:
|
|
27
|
+
"""Return the default TOML config file path."""
|
|
28
|
+
return get_config_dir() / "config.toml"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _toml_escape(value: str) -> str:
|
|
32
|
+
escaped = value.replace("\\", "\\\\").replace("'", "\\'")
|
|
33
|
+
return f"'{escaped}'"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def write_toml_config(toml_path: Path, data: dict[str, Any]) -> None:
|
|
37
|
+
"""Write configuration dictionary to TOML with restricted owner-only permissions."""
|
|
38
|
+
toml_path.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
tg = data.get("telegram", {})
|
|
40
|
+
gen = data.get("general", {})
|
|
41
|
+
files = data.get("files", {})
|
|
42
|
+
bat = data.get("battery", {})
|
|
43
|
+
ext = data.get("external", {})
|
|
44
|
+
|
|
45
|
+
roots = files.get(
|
|
46
|
+
"allowed_roots",
|
|
47
|
+
["~/Downloads", "~/Documents", "~/Desktop", "~/Pictures"],
|
|
48
|
+
)
|
|
49
|
+
roots_literal = ", ".join(_toml_escape(str(r)) for r in roots)
|
|
50
|
+
|
|
51
|
+
lines = [
|
|
52
|
+
"[telegram]",
|
|
53
|
+
f"bot_token = {_toml_escape(str(tg.get('bot_token', '')))}",
|
|
54
|
+
f"owner_id = {int(tg.get('owner_id', 0))}",
|
|
55
|
+
"",
|
|
56
|
+
"[general]",
|
|
57
|
+
f"device_name = {_toml_escape(str(gen.get('device_name', 'My Laptop')))}",
|
|
58
|
+
f"language = {_toml_escape(str(gen.get('language', 'id')))}",
|
|
59
|
+
f"profile = {_toml_escape(str(gen.get('profile', 'standar')))}",
|
|
60
|
+
"",
|
|
61
|
+
"[files]",
|
|
62
|
+
f"allowed_roots = [{roots_literal}]",
|
|
63
|
+
"",
|
|
64
|
+
"[battery]",
|
|
65
|
+
f"notify_low = {int(bat.get('notify_low', 20))}",
|
|
66
|
+
f"notify_full = {'true' if bat.get('notify_full', True) else 'false'}",
|
|
67
|
+
"",
|
|
68
|
+
"[external]",
|
|
69
|
+
f"tts = {'true' if ext.get('tts', False) else 'false'}",
|
|
70
|
+
f"geoip = {'true' if ext.get('geoip', False) else 'false'}",
|
|
71
|
+
f"ntfy_topic = {_toml_escape(str(ext.get('ntfy_topic', '')))}",
|
|
72
|
+
"",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
toml_path.write_text("\n".join(lines), encoding="utf-8")
|
|
76
|
+
if os.name == "posix":
|
|
77
|
+
os.chmod(toml_path, 0o600)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def migrate_legacy_json(json_path: Path, toml_path: Path) -> Path:
|
|
81
|
+
"""Migrate legacy config.json to config.toml without logging or printing secrets."""
|
|
82
|
+
with open(json_path, "r", encoding="utf-8") as f:
|
|
83
|
+
legacy: dict[str, Any] = json.load(f)
|
|
84
|
+
|
|
85
|
+
structured: dict[str, Any] = {
|
|
86
|
+
"telegram": {
|
|
87
|
+
"bot_token": str(legacy.get("bot_token", "")),
|
|
88
|
+
"owner_id": int(legacy.get("allowed_user_id", 0) or 0),
|
|
89
|
+
},
|
|
90
|
+
"general": {
|
|
91
|
+
"device_name": str(legacy.get("device_name", "My Laptop")),
|
|
92
|
+
"language": str(legacy.get("language", "id")),
|
|
93
|
+
"profile": str(legacy.get("profile", "standar")),
|
|
94
|
+
},
|
|
95
|
+
"files": {
|
|
96
|
+
"allowed_roots": legacy.get(
|
|
97
|
+
"allowed_roots",
|
|
98
|
+
["~/Downloads", "~/Documents", "~/Desktop", "~/Pictures"],
|
|
99
|
+
),
|
|
100
|
+
},
|
|
101
|
+
"battery": {
|
|
102
|
+
"notify_low": int(legacy.get("notify_low", 20)),
|
|
103
|
+
"notify_full": bool(legacy.get("notify_full", True)),
|
|
104
|
+
},
|
|
105
|
+
"external": {
|
|
106
|
+
"tts": bool(legacy.get("tts", False)),
|
|
107
|
+
"geoip": bool(legacy.get("geoip", False)),
|
|
108
|
+
"ntfy_topic": str(legacy.get("ntfy_topic", "")),
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
write_toml_config(toml_path, structured)
|
|
112
|
+
print(f"Migrasi konfigurasi dari {json_path.name} ke {toml_path} selesai.")
|
|
113
|
+
return toml_path
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def get_bot_token(config: dict[str, Any]) -> str:
|
|
117
|
+
"""Extract bot_token from TOML or legacy dict."""
|
|
118
|
+
tg = config.get("telegram")
|
|
119
|
+
if isinstance(tg, dict):
|
|
120
|
+
return str(tg.get("bot_token", "")).strip()
|
|
121
|
+
return str(config.get("bot_token", "")).strip()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def get_owner_id(config: dict[str, Any]) -> int:
|
|
125
|
+
"""Extract owner_id from TOML or legacy dict."""
|
|
126
|
+
tg = config.get("telegram")
|
|
127
|
+
if isinstance(tg, dict) and tg.get("owner_id") is not None:
|
|
128
|
+
return int(tg["owner_id"])
|
|
129
|
+
return int(config.get("allowed_user_id", 0) or 0)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def load_config(
|
|
133
|
+
config_path: str | Path | None = None,
|
|
134
|
+
legacy_json_path: str | Path | None = None,
|
|
135
|
+
) -> dict[str, Any]:
|
|
136
|
+
"""Load TOML configuration (migrating legacy config.json if needed) and fail closed."""
|
|
137
|
+
target = Path(config_path) if config_path is not None else default_config_path()
|
|
138
|
+
|
|
139
|
+
if not target.exists():
|
|
140
|
+
legacy = (
|
|
141
|
+
Path(legacy_json_path) if legacy_json_path is not None else Path.cwd() / "config.json"
|
|
142
|
+
)
|
|
143
|
+
if legacy.exists():
|
|
144
|
+
migrate_legacy_json(legacy, target)
|
|
145
|
+
else:
|
|
146
|
+
print(f"Error: file konfigurasi tidak ditemukan di {target}.")
|
|
147
|
+
sys.exit(1)
|
|
148
|
+
|
|
149
|
+
with open(target, "rb") as f:
|
|
150
|
+
data: dict[str, Any] = tomllib.load(f)
|
|
151
|
+
|
|
152
|
+
token = get_bot_token(data)
|
|
153
|
+
owner_id = get_owner_id(data)
|
|
154
|
+
|
|
155
|
+
if not token or token in {"MASUKKAN_TOKEN_BOT_ANDA_DI_SINI", "<diisi oleh setup>"}:
|
|
156
|
+
print("Error: bot_token belum diisi di konfigurasi. Agent menolak start.")
|
|
157
|
+
sys.exit(1)
|
|
158
|
+
|
|
159
|
+
if owner_id <= 0:
|
|
160
|
+
print("Error: owner_id kosong atau 0. Agent menolak start (fail closed).")
|
|
161
|
+
sys.exit(1)
|
|
162
|
+
|
|
163
|
+
return data
|
lapctl/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core command logic and background monitors for Lapctl."""
|