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 ADDED
@@ -0,0 +1,3 @@
1
+ """Lapctl — remote laptop control agent."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1 @@
1
+ """Channel integrations for Lapctl."""
@@ -0,0 +1 @@
1
+ """Telegram channel adapter."""
@@ -0,0 +1,336 @@
1
+ """Telegram Bot API HTTP client with response status checking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import time
8
+ from typing import Any
9
+
10
+ import requests
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ MAX_TELEGRAM_DOWNLOAD_BYTES = 20 * 1024 * 1024
15
+
16
+
17
+ class TelegramAPIError(RuntimeError):
18
+ """Raised or logged when a Telegram Bot API HTTP call fails."""
19
+
20
+
21
+ class TelegramClient:
22
+ """Thin HTTP client for the Telegram Bot API."""
23
+
24
+ def __init__(self, token: str) -> None:
25
+ self.token = token
26
+ self.base_url = f"https://api.telegram.org/bot{token}"
27
+ self.file_base_url = f"https://api.telegram.org/file/bot{token}"
28
+
29
+ @staticmethod
30
+ def _check_response(resp: requests.Response, action: str) -> dict[str, Any] | None:
31
+ if resp.status_code != 200:
32
+ logger.warning("Telegram %s failed with HTTP %s", action, resp.status_code)
33
+ return None
34
+ try:
35
+ data: dict[str, Any] = resp.json()
36
+ except ValueError:
37
+ logger.warning("Telegram %s returned invalid JSON", action)
38
+ return None
39
+ if not data.get("ok"):
40
+ logger.warning(
41
+ "Telegram %s returned ok=false: %s",
42
+ action,
43
+ data.get("description", "unknown error"),
44
+ )
45
+ return None
46
+ return data
47
+
48
+ @staticmethod
49
+ def _post_with_retry(
50
+ url: str,
51
+ *,
52
+ retries: int = 2,
53
+ **kwargs: Any,
54
+ ) -> requests.Response:
55
+ last_exc: Exception | None = None
56
+ for attempt in range(retries):
57
+ try:
58
+ return requests.post(url, **kwargs)
59
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as exc:
60
+ last_exc = exc
61
+ if attempt + 1 < retries:
62
+ time.sleep(0.5)
63
+ assert last_exc is not None
64
+ raise last_exc
65
+
66
+ def get_me(self) -> dict[str, Any] | None:
67
+ """Fetch bot profile metadata via getMe."""
68
+ try:
69
+ r = requests.get(f"{self.base_url}/getMe", timeout=10)
70
+ res = self._check_response(r, "getMe")
71
+ return res.get("result") if res else None
72
+ except Exception as e:
73
+ logger.warning("getMe error: %s", e)
74
+ return None
75
+
76
+ def delete_webhook(self, drop_pending_updates: bool = False) -> bool:
77
+ """Clear any configured webhook so long polling can run."""
78
+ try:
79
+ r = self._post_with_retry(
80
+ f"{self.base_url}/deleteWebhook",
81
+ json={"drop_pending_updates": drop_pending_updates},
82
+ timeout=10,
83
+ )
84
+ return self._check_response(r, "deleteWebhook") is not None
85
+ except Exception as e:
86
+ logger.warning("deleteWebhook error: %s", e)
87
+ return False
88
+
89
+ def set_bot_status_online(self) -> bool:
90
+ """Verify bot identity and update short description to online."""
91
+ try:
92
+ r = requests.get(f"{self.base_url}/getMe", timeout=10)
93
+ res = self._check_response(r, "getMe")
94
+ if not res:
95
+ return False
96
+
97
+ bot_name = res["result"]["first_name"]
98
+ if bot_name.startswith("🟢") or bot_name.startswith("🔴"):
99
+ clean_name = bot_name.lstrip("🟢 ").lstrip("🔴 ")
100
+ r_name = self._post_with_retry(
101
+ f"{self.base_url}/setMyName",
102
+ json={"name": clean_name},
103
+ timeout=10,
104
+ )
105
+ self._check_response(r_name, "setMyName")
106
+
107
+ short_desc = f"Bot Aktif (Online) 🟢\nTerakhir aktif: {time.strftime('%H:%M:%S')}"
108
+ r_desc = self._post_with_retry(
109
+ f"{self.base_url}/setMyShortDescription",
110
+ json={"short_description": short_desc},
111
+ timeout=10,
112
+ )
113
+ return self._check_response(r_desc, "setMyShortDescription") is not None
114
+ except Exception as e:
115
+ logger.warning("Failed to set bot status online: %s", e)
116
+ return False
117
+
118
+ def set_bot_status_offline(self) -> None:
119
+ """Update bot short description to offline."""
120
+ try:
121
+ short_desc = (
122
+ f"Bot Nonaktif (Offline) 🔴\nTerakhir aktif: {time.strftime('%d-%m-%Y %H:%M:%S')}"
123
+ )
124
+ r_desc = requests.post(
125
+ f"{self.base_url}/setMyShortDescription",
126
+ json={"short_description": short_desc},
127
+ timeout=10,
128
+ )
129
+ self._check_response(r_desc, "setMyShortDescription(offline)")
130
+ except Exception as e:
131
+ logger.warning("Failed to set bot status offline: %s", e)
132
+
133
+ def send_message(
134
+ self,
135
+ chat_id: int | str,
136
+ text: str,
137
+ reply_markup: dict[str, Any] | None = None,
138
+ ) -> dict[str, Any] | None:
139
+ """Send a Markdown text message."""
140
+ payload: dict[str, Any] = {
141
+ "chat_id": chat_id,
142
+ "text": text,
143
+ "parse_mode": "Markdown",
144
+ }
145
+ if reply_markup:
146
+ payload["reply_markup"] = reply_markup
147
+ try:
148
+ r = self._post_with_retry(f"{self.base_url}/sendMessage", json=payload, timeout=10)
149
+ return self._check_response(r, "sendMessage")
150
+ except Exception as e:
151
+ logger.warning("sendMessage error: %s", e)
152
+ return None
153
+
154
+ def delete_message(self, chat_id: int | str, message_id: int) -> bool:
155
+ """Delete a message by ID."""
156
+ payload = {"chat_id": chat_id, "message_id": message_id}
157
+ try:
158
+ r = requests.post(f"{self.base_url}/deleteMessage", json=payload, timeout=10)
159
+ return self._check_response(r, "deleteMessage") is not None
160
+ except Exception as e:
161
+ logger.warning("deleteMessage error: %s", e)
162
+ return False
163
+
164
+ def send_photo(
165
+ self,
166
+ chat_id: int | str,
167
+ photo_path: str,
168
+ caption: str | None = None,
169
+ ) -> bool:
170
+ """Upload and send a photo file."""
171
+ try:
172
+ with open(photo_path, "rb") as photo:
173
+ payload: dict[str, Any] = {"chat_id": chat_id}
174
+ if caption:
175
+ payload["caption"] = caption
176
+ r = requests.post(
177
+ f"{self.base_url}/sendPhoto",
178
+ data=payload,
179
+ files={"photo": photo},
180
+ timeout=20,
181
+ )
182
+ return self._check_response(r, "sendPhoto") is not None
183
+ except Exception as e:
184
+ logger.warning("sendPhoto error: %s", e)
185
+ return False
186
+
187
+ def send_video(
188
+ self,
189
+ chat_id: int | str,
190
+ video_path: str,
191
+ caption: str | None = None,
192
+ ) -> bool:
193
+ """Upload and send a video file."""
194
+ try:
195
+ with open(video_path, "rb") as video:
196
+ payload: dict[str, Any] = {"chat_id": chat_id}
197
+ if caption:
198
+ payload["caption"] = caption
199
+ r = requests.post(
200
+ f"{self.base_url}/sendVideo",
201
+ data=payload,
202
+ files={"video": video},
203
+ timeout=40,
204
+ )
205
+ return self._check_response(r, "sendVideo") is not None
206
+ except Exception as e:
207
+ logger.warning("sendVideo error: %s", e)
208
+ return False
209
+
210
+ def send_document(
211
+ self,
212
+ chat_id: int | str,
213
+ document_path: str,
214
+ caption: str | None = None,
215
+ ) -> bool:
216
+ """Upload and send a document file."""
217
+ try:
218
+ with open(document_path, "rb") as doc:
219
+ payload: dict[str, Any] = {"chat_id": chat_id}
220
+ if caption:
221
+ payload["caption"] = caption
222
+ r = requests.post(
223
+ f"{self.base_url}/sendDocument",
224
+ data=payload,
225
+ files={"document": doc},
226
+ timeout=30,
227
+ )
228
+ return self._check_response(r, "sendDocument") is not None
229
+ except Exception as e:
230
+ logger.warning("sendDocument error: %s", e)
231
+ return False
232
+
233
+ def send_voice(
234
+ self,
235
+ chat_id: int | str,
236
+ voice_path: str,
237
+ caption: str | None = None,
238
+ ) -> bool:
239
+ """Upload and send a voice note."""
240
+ try:
241
+ with open(voice_path, "rb") as voice:
242
+ payload: dict[str, Any] = {"chat_id": chat_id}
243
+ if caption:
244
+ payload["caption"] = caption
245
+ r = requests.post(
246
+ f"{self.base_url}/sendVoice",
247
+ data=payload,
248
+ files={"voice": voice},
249
+ timeout=30,
250
+ )
251
+ return self._check_response(r, "sendVoice") is not None
252
+ except Exception as e:
253
+ logger.warning("sendVoice error: %s", e)
254
+ return False
255
+
256
+ def send_location(self, chat_id: int | str, lat: float, lon: float) -> bool:
257
+ """Send map coordinates."""
258
+ payload = {"chat_id": chat_id, "latitude": lat, "longitude": lon}
259
+ try:
260
+ r = requests.post(f"{self.base_url}/sendLocation", json=payload, timeout=10)
261
+ return self._check_response(r, "sendLocation") is not None
262
+ except Exception as e:
263
+ logger.warning("sendLocation error: %s", e)
264
+ return False
265
+
266
+ def answer_callback_query(
267
+ self,
268
+ callback_query_id: str,
269
+ text: str | None = None,
270
+ ) -> bool:
271
+ """Acknowledge an inline keyboard callback query."""
272
+ payload: dict[str, Any] = {"callback_query_id": callback_query_id}
273
+ if text:
274
+ payload["text"] = text
275
+ try:
276
+ r = requests.post(f"{self.base_url}/answerCallbackQuery", json=payload, timeout=10)
277
+ return self._check_response(r, "answerCallbackQuery") is not None
278
+ except Exception as e:
279
+ logger.warning("answerCallbackQuery error: %s", e)
280
+ return False
281
+
282
+ def download_file(self, file_id: str, dest_path: str) -> bool:
283
+ """Fetch file metadata via getFile and stream-download it to dest_path."""
284
+ try:
285
+ r = requests.get(f"{self.base_url}/getFile", params={"file_id": file_id}, timeout=10)
286
+ res = self._check_response(r, "getFile")
287
+ if not res:
288
+ return False
289
+ result = res.get("result", {})
290
+ file_size = result.get("file_size", 0)
291
+ if isinstance(file_size, int) and file_size > MAX_TELEGRAM_DOWNLOAD_BYTES:
292
+ logger.warning("Telegram file exceeds 20 MB download limit (%s bytes)", file_size)
293
+ return False
294
+ file_path = result.get("file_path")
295
+ if not file_path:
296
+ return False
297
+
298
+ download_url = f"{self.file_base_url}/{file_path}"
299
+ r_file = requests.get(download_url, stream=True, timeout=30)
300
+ if r_file.status_code != 200:
301
+ logger.warning("File download failed with HTTP %s", r_file.status_code)
302
+ return False
303
+
304
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
305
+ with open(dest_path, "wb") as f:
306
+ for chunk in r_file.iter_content(chunk_size=8192):
307
+ f.write(chunk)
308
+ return True
309
+ except Exception as e:
310
+ logger.warning("download_file error: %s", e)
311
+ return False
312
+
313
+ def get_updates(
314
+ self,
315
+ offset: int | None = None,
316
+ timeout: int = 30,
317
+ ) -> dict[str, Any] | None:
318
+ """Long-poll updates from Telegram."""
319
+ params: dict[str, Any] = {"timeout": timeout}
320
+ if offset is not None:
321
+ params["offset"] = offset
322
+ r = requests.get(f"{self.base_url}/getUpdates", params=params, timeout=timeout + 5)
323
+ return self._check_response(r, "getUpdates")
324
+
325
+ def set_my_commands(self, commands: list[dict[str, str]]) -> bool:
326
+ """Register bot command list via Telegram setMyCommands."""
327
+ try:
328
+ r = requests.post(
329
+ f"{self.base_url}/setMyCommands",
330
+ json={"commands": commands},
331
+ timeout=10,
332
+ )
333
+ return self._check_response(r, "setMyCommands") is not None
334
+ except Exception as e:
335
+ logger.warning("setMyCommands error: %s", e)
336
+ return False
@@ -0,0 +1,29 @@
1
+ """Owner and private-chat authorization helpers for Telegram updates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ def is_authorized(
11
+ sender_id: int,
12
+ owner_id: int,
13
+ chat_type: str = "private",
14
+ ) -> bool:
15
+ """Fail-closed check: only private chats from the configured non-zero owner_id."""
16
+ if owner_id <= 0:
17
+ return False
18
+ if chat_type != "private":
19
+ return False
20
+ return sender_id == owner_id
21
+
22
+
23
+ def log_ignored_update(sender_id: int | None, chat_type: str | None) -> None:
24
+ """Log ignored sender ID and chat type without any message content."""
25
+ logger.warning(
26
+ "Ignored unauthorized/non-private update (sender_id=%s, chat_type=%s)",
27
+ sender_id,
28
+ chat_type,
29
+ )
@@ -0,0 +1,161 @@
1
+ """Telegram update handlers bridging TelegramPoller, Registry, Core, Driver, and Render."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from typing import Any
8
+
9
+ from lapctl.channels.telegram.api import TelegramClient
10
+ from lapctl.channels.telegram.render import render_output
11
+ from lapctl.core.commands import build_default_registry, dispatch_command
12
+ from lapctl.core.confirm import ConfirmationManager
13
+ from lapctl.core.paths import (
14
+ default_upload_dir,
15
+ resolve_allowed_roots,
16
+ sanitize_upload_filename,
17
+ )
18
+ from lapctl.core.ratelimit import RateLimiter
19
+ from lapctl.drivers.base import BaseDriver, NotSupported
20
+ from lapctl.registry import CommandRegistry, get_active_profile
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class TelegramHandlers:
26
+ """Handles authorized Telegram text, upload, and callback events."""
27
+
28
+ def __init__(
29
+ self,
30
+ client: TelegramClient,
31
+ config: dict[str, Any],
32
+ driver: BaseDriver,
33
+ registry: CommandRegistry | None = None,
34
+ confirmations: ConfirmationManager | None = None,
35
+ rate_limiter: RateLimiter | None = None,
36
+ ) -> None:
37
+ self.client = client
38
+ self.config = config
39
+ self.driver = driver
40
+ self.registry = registry or build_default_registry()
41
+ self.confirmations = confirmations or ConfirmationManager(ttl_seconds=30.0)
42
+ self.rate_limiter = rate_limiter or RateLimiter(max_requests=20, window_seconds=60.0)
43
+
44
+ def _run_and_render(self, chat_id: int | str, text: str, owner_id: int) -> None:
45
+ output = dispatch_command(
46
+ self.registry,
47
+ self.config,
48
+ self.driver,
49
+ chat_id,
50
+ text,
51
+ owner_id=owner_id,
52
+ confirmations=self.confirmations,
53
+ rate_limiter=self.rate_limiter,
54
+ )
55
+ render_output(self.client, chat_id, output, driver=self.driver)
56
+
57
+ def on_text(
58
+ self,
59
+ chat_id: int | str,
60
+ text: str,
61
+ message_id: int | None,
62
+ username: str,
63
+ owner_id: int = 0,
64
+ ) -> None:
65
+ """Dispatch incoming text command."""
66
+ logger.info("Command from owner_id=%s", owner_id)
67
+ self._run_and_render(chat_id, text, owner_id=owner_id)
68
+
69
+ def on_document(
70
+ self,
71
+ chat_id: int | str,
72
+ file_id: str,
73
+ file_name: str,
74
+ username: str,
75
+ owner_id: int = 0,
76
+ ) -> None:
77
+ """Save uploaded document into sanitized path inside allowed_roots."""
78
+ if not self.rate_limiter.allow(owner_id):
79
+ self.client.send_message(
80
+ chat_id, "⏳ Terlalu banyak perintah dalam waktu singkat. Coba lagi sebentar."
81
+ )
82
+ return
83
+ if get_active_profile(self.config) != "lengkap":
84
+ self.client.send_message(
85
+ chat_id, "🔒 Upload file dinonaktifkan pada profil izin saat ini."
86
+ )
87
+ return
88
+
89
+ safe_name = sanitize_upload_filename(file_name)
90
+ roots = resolve_allowed_roots(self.config)
91
+ dest_dir = default_upload_dir(roots, "TelegramBot")
92
+ dest_path = str(dest_dir / safe_name)
93
+
94
+ self.client.send_message(chat_id, f"📥 Menerima file `{safe_name}`...")
95
+ if self.client.download_file(file_id, dest_path):
96
+ self.client.send_message(chat_id, f"✅ File berhasil disimpan ke:\n`{dest_path}`")
97
+ else:
98
+ self.client.send_message(chat_id, f"❌ Gagal mengunduh file `{safe_name}`.")
99
+
100
+ def on_photo(
101
+ self,
102
+ chat_id: int | str,
103
+ file_id: str,
104
+ caption: str,
105
+ username: str,
106
+ owner_id: int = 0,
107
+ ) -> None:
108
+ """Save uploaded photo, or apply it as wallpaper when caption is /wallpaper."""
109
+ if not self.rate_limiter.allow(owner_id):
110
+ self.client.send_message(
111
+ chat_id, "⏳ Terlalu banyak perintah dalam waktu singkat. Coba lagi sebentar."
112
+ )
113
+ return
114
+
115
+ roots = resolve_allowed_roots(self.config)
116
+ if caption == "/wallpaper":
117
+ if get_active_profile(self.config) == "aman":
118
+ self.client.send_message(
119
+ chat_id, "🔒 Ubah wallpaper dinonaktifkan pada profil aman."
120
+ )
121
+ return
122
+ pictures_dir = default_upload_dir(roots, "wallpapers")
123
+ dest_path = str(pictures_dir / "telegram_wallpaper.jpg")
124
+ self.client.send_message(chat_id, "📥 Mengunduh dan menerapkan wallpaper baru...")
125
+ if self.client.download_file(file_id, dest_path):
126
+ try:
127
+ self.driver.set_wallpaper(dest_path)
128
+ self.client.send_message(
129
+ chat_id,
130
+ f"✅ Wallpaper berhasil diubah dan disimpan ke:\n`{dest_path}`",
131
+ )
132
+ except NotSupported as exc:
133
+ self.client.send_message(chat_id, f"⚠️ {exc.reason}")
134
+ except Exception as e:
135
+ self.client.send_message(chat_id, f"⚠️ Gagal menerapkan wallpaper: {e}")
136
+ else:
137
+ self.client.send_message(chat_id, "❌ Gagal mengunduh foto.")
138
+ else:
139
+ if get_active_profile(self.config) != "lengkap":
140
+ self.client.send_message(
141
+ chat_id, "🔒 Upload foto dinonaktifkan pada profil izin saat ini."
142
+ )
143
+ return
144
+ file_name = sanitize_upload_filename(f"photo_{int(time.time())}.jpg")
145
+ dest_dir = default_upload_dir(roots, "TelegramBot")
146
+ dest_path = str(dest_dir / file_name)
147
+ self.client.send_message(chat_id, "📥 Menerima foto...")
148
+ if self.client.download_file(file_id, dest_path):
149
+ self.client.send_message(chat_id, f"✅ Foto berhasil disimpan ke:\n`{dest_path}`")
150
+ else:
151
+ self.client.send_message(chat_id, "❌ Gagal mengunduh foto.")
152
+
153
+ def on_callback(
154
+ self,
155
+ chat_id: int | str,
156
+ cb_data: str,
157
+ username: str,
158
+ owner_id: int = 0,
159
+ ) -> None:
160
+ """Dispatch inline keyboard callback as a command."""
161
+ self._run_and_render(chat_id, cb_data, owner_id=owner_id)