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/core/confirm.py ADDED
@@ -0,0 +1,68 @@
1
+ """Single-use expiring confirmation tokens for destructive power commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ import threading
7
+ import time
8
+ from dataclasses import dataclass
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ConfirmationToken:
13
+ """Pending confirmation bound to a specific owner and action."""
14
+
15
+ owner_id: int
16
+ action: str
17
+ expires_at: float
18
+
19
+
20
+ class ConfirmationManager:
21
+ """Thread-safe store for single-use, expiring confirmation tokens."""
22
+
23
+ def __init__(self, ttl_seconds: float = 30.0) -> None:
24
+ self.ttl_seconds = ttl_seconds
25
+ self._tokens: dict[str, ConfirmationToken] = {}
26
+ self._lock = threading.Lock()
27
+
28
+ def create(self, owner_id: int, action: str) -> str:
29
+ """Issue a new single-use token bound to owner_id and action."""
30
+ token = secrets.token_urlsafe(12)
31
+ expires_at = time.monotonic() + self.ttl_seconds
32
+ with self._lock:
33
+ self._prune_locked()
34
+ self._tokens[token] = ConfirmationToken(
35
+ owner_id=owner_id,
36
+ action=action,
37
+ expires_at=expires_at,
38
+ )
39
+ return token
40
+
41
+ def consume(self, token: str, owner_id: int, action: str) -> tuple[bool, str]:
42
+ """Validate and consume a token. Returns (ok, reason_code)."""
43
+ now = time.monotonic()
44
+ with self._lock:
45
+ entry = self._tokens.get(token)
46
+ if entry is None:
47
+ return False, "invalid"
48
+ if entry.owner_id != owner_id or entry.action != action:
49
+ return False, "mismatch"
50
+ self._tokens.pop(token, None)
51
+ if now > entry.expires_at:
52
+ return False, "expired"
53
+ return True, "ok"
54
+
55
+ def cancel(self, token: str, owner_id: int) -> bool:
56
+ """Cancel a pending token if owned by owner_id."""
57
+ with self._lock:
58
+ entry = self._tokens.get(token)
59
+ if entry is None or entry.owner_id != owner_id:
60
+ return False
61
+ self._tokens.pop(token, None)
62
+ return True
63
+
64
+ def _prune_locked(self) -> None:
65
+ now = time.monotonic()
66
+ expired = [k for k, v in self._tokens.items() if now > v.expires_at]
67
+ for k in expired:
68
+ del self._tokens[k]
@@ -0,0 +1,140 @@
1
+ """Button layout definitions returning Result Button grids."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from lapctl.results import Button
8
+
9
+ if TYPE_CHECKING:
10
+ from lapctl.registry import CommandRegistry
11
+
12
+
13
+ def get_start_buttons() -> list[list[Button]]:
14
+ """Return inline button rows for /start and /help."""
15
+ return [
16
+ [Button(text="🤖 Menu Kontrol", callback_data="/menu")],
17
+ ]
18
+
19
+
20
+ def get_status_buttons() -> list[list[Button]]:
21
+ """Return inline button rows attached to /status output."""
22
+ return [
23
+ [
24
+ Button(text="📸 Screenshot", callback_data="/ss"),
25
+ Button(text="📷 Camera", callback_data="/cam"),
26
+ Button(text="📹 Video Cam", callback_data="/vid"),
27
+ ],
28
+ [
29
+ Button(text="📍 Lokasi", callback_data="/location"),
30
+ Button(text="📱 Cari HP", callback_data="/carihp"),
31
+ Button(text="🔇 Mute", callback_data="/mute"),
32
+ Button(text="🔒 Lock", callback_data="/lock"),
33
+ ],
34
+ [
35
+ Button(text="🔄 Refresh Status", callback_data="/status"),
36
+ ],
37
+ ]
38
+
39
+
40
+ def get_menu_buttons(
41
+ registry: CommandRegistry | None = None,
42
+ config: dict[str, Any] | None = None,
43
+ ) -> list[list[Button]]:
44
+ """Return control menu button rows, optionally filtered by active profile."""
45
+ raw_rows: list[list[Button]] = [
46
+ [Button(text="🖥 SYSTEM", callback_data="/none")],
47
+ [
48
+ Button(text="📊 Status", callback_data="/status"),
49
+ Button(text="🩺 Health", callback_data="/health"),
50
+ ],
51
+ [
52
+ Button(text="⚙️ Processes", callback_data="/ps"),
53
+ Button(text="📜 Logs", callback_data="/logs"),
54
+ ],
55
+ [
56
+ Button(text="💡 Brightness", callback_data="/brightness"),
57
+ Button(text="📍 Location", callback_data="/location"),
58
+ ],
59
+ [Button(text="🎮 CONTROL & AUDIO", callback_data="/none")],
60
+ [
61
+ Button(text="🖱 Mouse", callback_data="/mouse"),
62
+ Button(text="⌨️ Keyboard", callback_data="/keyboard"),
63
+ ],
64
+ [
65
+ Button(text="📋 Clipboard", callback_data="/getclip"),
66
+ Button(text="🔊 Volume", callback_data="/volume"),
67
+ ],
68
+ [
69
+ Button(text="🔇 Mute", callback_data="/mute"),
70
+ Button(text="🗣️ Say TTS", callback_data="/say"),
71
+ ],
72
+ [Button(text="🎵 MEDIA CONTROLS", callback_data="/none")],
73
+ [
74
+ Button(text="⏮️ Prev", callback_data="/prev"),
75
+ Button(text="▶️ Play/Pause", callback_data="/play"),
76
+ Button(text="⏭️ Next", callback_data="/next"),
77
+ ],
78
+ [
79
+ Button(text="📺 YouTube", callback_data="/youtube"),
80
+ Button(text="🔔 Beep", callback_data="/beep"),
81
+ Button(text="📱 Cari HP", callback_data="/carihp"),
82
+ ],
83
+ [Button(text="📁 FILES & UTILS", callback_data="/none")],
84
+ [
85
+ Button(text="📂 Browse", callback_data="/ls"),
86
+ Button(text="🔎 Find", callback_data="/find"),
87
+ ],
88
+ [
89
+ Button(text="⬇️ Download", callback_data="/download"),
90
+ Button(text="⬆️ Upload", callback_data="/upload"),
91
+ ],
92
+ [
93
+ Button(text="🖼️ Wallpaper", callback_data="/wallpaper"),
94
+ Button(text="🐚 Terminal", callback_data="/cmd"),
95
+ ],
96
+ [Button(text="📷 MEDIA CAPTURE", callback_data="/none")],
97
+ [
98
+ Button(text="📸 Screenshot", callback_data="/ss"),
99
+ Button(text="📹 Camera (Foto)", callback_data="/cam"),
100
+ ],
101
+ [
102
+ Button(text="🎥 Cam Video", callback_data="/vid"),
103
+ Button(text="🎙️ Rec Mic", callback_data="/record"),
104
+ ],
105
+ [Button(text="🖥 Screen Record", callback_data="/screenrecord")],
106
+ [Button(text="🌐 NETWORK", callback_data="/none")],
107
+ [
108
+ Button(text="📡 Network", callback_data="/network"),
109
+ Button(text="🌍 Public IP", callback_data="/ip"),
110
+ ],
111
+ [Button(text="⚡ POWER", callback_data="/none")],
112
+ [
113
+ Button(text="🔒 Lock", callback_data="/lock"),
114
+ Button(text="💤 Suspend", callback_data="/suspend"),
115
+ ],
116
+ [
117
+ Button(text="🔄 Reboot", callback_data="/reboot"),
118
+ Button(text="⏻ Shutdown", callback_data="/shutdown"),
119
+ ],
120
+ ]
121
+
122
+ if registry is None or config is None:
123
+ return raw_rows
124
+
125
+ filtered_rows: list[list[Button]] = []
126
+ for row in raw_rows:
127
+ if len(row) == 1 and row[0].callback_data == "/none":
128
+ filtered_rows.append(row)
129
+ continue
130
+ kept: list[Button] = []
131
+ for btn in row:
132
+ if btn.callback_data is None:
133
+ kept.append(btn)
134
+ continue
135
+ cmd = registry.resolve(btn.callback_data.split(maxsplit=1)[0])
136
+ if cmd is not None and registry.is_allowed(cmd, config):
137
+ kept.append(btn)
138
+ if kept:
139
+ filtered_rows.append(kept)
140
+ return filtered_rows
lapctl/core/paths.py ADDED
@@ -0,0 +1,77 @@
1
+ """Path sandboxing and upload filename sanitization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ DEFAULT_ALLOWED_ROOTS: tuple[str, ...] = (
11
+ "~/Downloads",
12
+ "~/Documents",
13
+ "~/Desktop",
14
+ "~/Pictures",
15
+ )
16
+
17
+
18
+ class PathAccessError(ValueError):
19
+ """Raised when a user-supplied path violates the sandbox."""
20
+
21
+
22
+ def resolve_allowed_roots(config: dict[str, Any] | None = None) -> list[Path]:
23
+ """Resolve configured allowed_roots (or defaults) to canonical Paths."""
24
+ raw_roots: list[str] | tuple[str, ...] = DEFAULT_ALLOWED_ROOTS
25
+ if config:
26
+ files_cfg = config.get("files")
27
+ if isinstance(files_cfg, dict) and files_cfg.get("allowed_roots"):
28
+ raw_roots = files_cfg["allowed_roots"]
29
+ elif config.get("allowed_roots"):
30
+ raw_roots = config["allowed_roots"]
31
+
32
+ roots: list[Path] = []
33
+ for entry in raw_roots:
34
+ expanded = os.path.expanduser(str(entry))
35
+ roots.append(Path(expanded).resolve())
36
+ return roots
37
+
38
+
39
+ def validate_path(raw_path: str, allowed_roots: list[Path]) -> Path:
40
+ """Validate that raw_path has no '..' traversal and resolves inside allowed_roots."""
41
+ cleaned = raw_path.strip()
42
+ if not cleaned or "\x00" in cleaned:
43
+ raise PathAccessError("Path tidak valid.")
44
+
45
+ expanded = os.path.expanduser(cleaned)
46
+ raw_parts = Path(expanded).parts
47
+ if ".." in raw_parts:
48
+ raise PathAccessError("Akses ditolak: komponen '..' tidak diizinkan.")
49
+
50
+ resolved = Path(expanded).resolve()
51
+ for root in allowed_roots:
52
+ if resolved == root or resolved.is_relative_to(root):
53
+ return resolved
54
+
55
+ raise PathAccessError("Akses ditolak: path berada di luar folder yang diizinkan.")
56
+
57
+
58
+ def sanitize_upload_filename(filename: str) -> str:
59
+ """Normalize an uploaded filename using basename and character sanitization."""
60
+ # Handle both POSIX and Windows separators before basename.
61
+ base = os.path.basename(filename.replace("\\", "/")).strip()
62
+ base = base.lstrip(".")
63
+ sanitized = re.sub(r"[^A-Za-z0-9._-]", "_", base)
64
+ if not sanitized:
65
+ return "upload"
66
+ return sanitized
67
+
68
+
69
+ def default_upload_dir(allowed_roots: list[Path], subfolder: str = "TelegramBot") -> Path:
70
+ """Return a safe upload directory inside allowed_roots."""
71
+ downloads_candidate = Path(os.path.expanduser("~/Downloads")).resolve()
72
+ for root in allowed_roots:
73
+ if downloads_candidate == root or downloads_candidate.is_relative_to(root):
74
+ return downloads_candidate / subfolder
75
+ if allowed_roots:
76
+ return allowed_roots[0] / subfolder
77
+ return downloads_candidate / subfolder
@@ -0,0 +1,30 @@
1
+ """Simple sliding-window rate limiter per owner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from collections import defaultdict, deque
8
+
9
+
10
+ class RateLimiter:
11
+ """Thread-safe sliding-window rate limiter."""
12
+
13
+ def __init__(self, max_requests: int = 20, window_seconds: float = 60.0) -> None:
14
+ self.max_requests = max_requests
15
+ self.window_seconds = window_seconds
16
+ self._hits: dict[int, deque[float]] = defaultdict(deque)
17
+ self._lock = threading.Lock()
18
+
19
+ def allow(self, owner_id: int) -> bool:
20
+ """Return True if owner_id is within the rate limit, recording the hit."""
21
+ now = time.monotonic()
22
+ cutoff = now - self.window_seconds
23
+ with self._lock:
24
+ bucket = self._hits[owner_id]
25
+ while bucket and bucket[0] < cutoff:
26
+ bucket.popleft()
27
+ if len(bucket) >= self.max_requests:
28
+ return False
29
+ bucket.append(now)
30
+ return True
@@ -0,0 +1 @@
1
+ """OS/desktop environment drivers for Lapctl."""
lapctl/drivers/base.py ADDED
@@ -0,0 +1,163 @@
1
+ """Driver contract and NotSupported error for OS/desktop operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+
10
+ class NotSupported(Exception):
11
+ """Raised when the active driver does not support a requested operation."""
12
+
13
+ def __init__(self, feature: str, reason: str | None = None) -> None:
14
+ self.feature = feature
15
+ self.reason = reason or f"Fitur '{feature}' tidak didukung pada platform/driver ini."
16
+ super().__init__(self.reason)
17
+
18
+
19
+ class BaseDriver(ABC):
20
+ """Abstract contract for all OS and desktop environment operations."""
21
+
22
+ name: str = "base"
23
+ capabilities: frozenset[str] = frozenset()
24
+
25
+ @classmethod
26
+ @abstractmethod
27
+ def detect(cls) -> bool:
28
+ """Return True if this driver matches the current OS and desktop session."""
29
+
30
+ def prepare_env(self) -> None:
31
+ """Refresh GUI/session environment variables if needed."""
32
+
33
+ @abstractmethod
34
+ def get_battery_state(self) -> tuple[int, bool, bool] | None:
35
+ """Return (capacity_pct, is_discharging, is_charging_or_full) or None."""
36
+
37
+ @abstractmethod
38
+ def get_system_status(self) -> str:
39
+ """Return formatted system status summary."""
40
+
41
+ @abstractmethod
42
+ def get_system_health(self) -> tuple[str, str, float, float, float]:
43
+ """Return (uptime_str, temp_str, disk_used_pct, disk_free_gb, disk_total_gb)."""
44
+
45
+ @abstractmethod
46
+ def list_processes(self) -> str:
47
+ """Return top processes output."""
48
+
49
+ @abstractmethod
50
+ def get_logs(self) -> str:
51
+ """Return recent service logs."""
52
+
53
+ @abstractmethod
54
+ def get_network_info(self) -> tuple[str, str]:
55
+ """Return (ping_latency_str, active_interfaces_str)."""
56
+
57
+ @abstractmethod
58
+ def screenshot(self, output_path: str) -> None:
59
+ """Capture a screenshot to output_path."""
60
+
61
+ @abstractmethod
62
+ def webcam_photo(self, output_path: str) -> None:
63
+ """Capture a webcam photo to output_path."""
64
+
65
+ @abstractmethod
66
+ def webcam_video(self, output_path: str, duration: int) -> None:
67
+ """Record webcam video for duration seconds to output_path."""
68
+
69
+ @abstractmethod
70
+ def record_audio(self, output_path: str, duration: int) -> None:
71
+ """Record microphone audio for duration seconds to output_path."""
72
+
73
+ @abstractmethod
74
+ def screenrecord(self, output_path: str, duration: int) -> None:
75
+ """Record the screen for duration seconds to output_path."""
76
+
77
+ @abstractmethod
78
+ def play_audio_url(self, url: str, loop_count: int = 1) -> None:
79
+ """Play an audio stream URL in the background."""
80
+
81
+ @abstractmethod
82
+ def open_url(self, url: str) -> None:
83
+ """Open a URL in the default browser."""
84
+
85
+ @abstractmethod
86
+ def lock_screen(self) -> None:
87
+ """Lock the desktop session."""
88
+
89
+ @abstractmethod
90
+ def power_action(self, action: Literal["suspend", "reboot", "shutdown"]) -> None:
91
+ """Execute a system power action."""
92
+
93
+ @abstractmethod
94
+ def set_volume(self, level: int) -> None:
95
+ """Set default audio sink volume (0-100) and unmute."""
96
+
97
+ @abstractmethod
98
+ def set_mute(self, muted: bool) -> None:
99
+ """Mute or unmute default audio sink."""
100
+
101
+ @abstractmethod
102
+ def step_volume(self, delta: str) -> str:
103
+ """Adjust volume by delta (e.g. '0.05+', '0.05-') and return new reading."""
104
+
105
+ @abstractmethod
106
+ def media_control(self, action: Literal["play", "pause", "next", "previous"]) -> None:
107
+ """Control active media player."""
108
+
109
+ @abstractmethod
110
+ def play_beep(self, sound_type: str) -> None:
111
+ """Play a local notification sound."""
112
+
113
+ @abstractmethod
114
+ def set_brightness(self, level: int) -> None:
115
+ """Set display brightness percentage (0-100)."""
116
+
117
+ @abstractmethod
118
+ def notify(self, title: str, message: str) -> None:
119
+ """Display a desktop notification."""
120
+
121
+ @abstractmethod
122
+ def set_wallpaper(self, path: str) -> None:
123
+ """Set desktop wallpaper from an image file path."""
124
+
125
+ @abstractmethod
126
+ def get_clipboard(self) -> str:
127
+ """Read current text from clipboard."""
128
+
129
+ @abstractmethod
130
+ def set_clipboard(self, text: str) -> int:
131
+ """Write text to clipboard and return exit code."""
132
+
133
+ @abstractmethod
134
+ def get_cursor_pos(self) -> str:
135
+ """Return current cursor coordinates."""
136
+
137
+ @abstractmethod
138
+ def move_cursor(self, x: int, y: int) -> None:
139
+ """Move cursor to (x, y)."""
140
+
141
+ @abstractmethod
142
+ def mouse_click(self) -> None:
143
+ """Perform a left mouse click."""
144
+
145
+ @abstractmethod
146
+ def keyboard_type(self, text: str) -> None:
147
+ """Type text via virtual keyboard."""
148
+
149
+ @abstractmethod
150
+ def keyboard_key(self, key: str) -> None:
151
+ """Press a single key via virtual keyboard."""
152
+
153
+ @abstractmethod
154
+ def find_files(self, query: str, roots: list[Path]) -> str:
155
+ """Search files matching query within allowed roots."""
156
+
157
+ @abstractmethod
158
+ def run_command(self, command: str, timeout: int = 15) -> str:
159
+ """Execute a command (without shell=True) and return combined output."""
160
+
161
+ def compress_video(self, input_path: str, output_path: str, target_mb: int = 45) -> bool:
162
+ """Compress a video file to fit under target_mb. Return True on success."""
163
+ return False