codis 1.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.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
@@ -0,0 +1,178 @@
1
+ """Mattermost API v4: REST + WebSocket de eventos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from src.chat.adapters.base import AdapterFatal
9
+ from src.chat.adapters.http import HTTPFailure, request_json
10
+ from src.chat.adapters.ws import HAS_WS, AsyncAdapter, ws_connect
11
+ from src.chat.util import split_chars
12
+
13
+
14
+ class MattermostAdapter(AsyncAdapter):
15
+ learn_nicks = True
16
+
17
+ def __init__(self, *a: Any, **k: Any) -> None:
18
+ super().__init__(*a, **k)
19
+ self._token = ""
20
+ self._me = ""
21
+ self._me_name = ""
22
+ self._team = ""
23
+ self._label: dict[str, str] = {}
24
+ self._id: dict[str, str] = {}
25
+ self._users: dict[str, str] = {}
26
+
27
+ def _base(self) -> str:
28
+ p = self.p
29
+ o = p.x("api_base")
30
+ if o:
31
+ return o.rstrip("/")
32
+ return f"{'https' if p.tls or p.port == 443 else 'http'}://{p.host}:{p.port}"
33
+
34
+ def _api(self, method: str, path: str, body=None, params=None, headers=False):
35
+ hdr = {"Authorization": f"Bearer {self._token}"} if self._token else {}
36
+ return request_json(method, self._base() + "/api/v4" + path, headers=hdr, body=body, params=params,
37
+ verify=self.p.verify_tls, with_headers=headers)
38
+
39
+ def _session_once(self) -> None:
40
+ if not HAS_WS:
41
+ raise AdapterFatal("Instale: pip install websockets")
42
+ p = self.p
43
+ self._token = p.decoded_token()
44
+ if not self._token:
45
+ code, user, hdr = self._api("POST", "/users/login",
46
+ {"login_id": p.jid or p.user, "password": p.decoded_password()}, headers=True)
47
+ if code in (401, 403):
48
+ raise AdapterFatal(f"Mattermost: login falhou ({user.get('message', code)})")
49
+ if code != 200:
50
+ raise HTTPFailure(code, str(user.get("message", "servidor indisponível")))
51
+ self._token = next((v for k, v in hdr.items() if k.lower() == "token"), "")
52
+ if not self._token:
53
+ raise AdapterFatal("Mattermost: o servidor não devolveu token de sessão.")
54
+ code, me = self._api("GET", "/users/me")
55
+ if code in (401, 403):
56
+ raise AdapterFatal("Mattermost: token inválido ou expirado.")
57
+ if code != 200:
58
+ raise HTTPFailure(code, "falha em /users/me")
59
+ self._me, self._me_name = me["id"], me.get("username", "")
60
+ self._users[self._me] = self._me_name
61
+ _, teams = self._api("GET", "/users/me/teams")
62
+ want = p.x("team")
63
+ teams = teams if isinstance(teams, list) else []
64
+ pick = next((t for t in teams if want and want in (t.get("name"), t.get("display_name"))), None) or (
65
+ teams[0] if teams else {})
66
+ self._team = pick.get("id", "")
67
+ self._label.clear()
68
+ self._id.clear()
69
+ if self._team:
70
+ _, chs = self._api("GET", f"/users/me/teams/{self._team}/channels")
71
+ for ch in chs if isinstance(chs, list) else []:
72
+ self._learn_channel(ch)
73
+ super()._session_once()
74
+
75
+ def _learn_channel(self, ch: dict) -> str:
76
+ cid, typ = ch.get("id", ""), ch.get("type", "O")
77
+ if typ == "D":
78
+ other = next((u for u in ch.get("name", "").split("__") if u and u != self._me), self._me)
79
+ label = "@" + self._username(other)
80
+ elif typ == "G":
81
+ label = ch.get("display_name") or ch.get("name", cid)
82
+ else:
83
+ label = ch.get("name") or ch.get("display_name") or cid
84
+ self._label[cid] = label
85
+ self._id[label] = cid
86
+ if ch.get("display_name"):
87
+ self._id.setdefault(ch["display_name"], cid)
88
+ return label
89
+
90
+ def _username(self, uid: str) -> str:
91
+ if uid not in self._users:
92
+ code, u = self._api("GET", f"/users/{uid}")
93
+ self._users[uid] = u.get("username", uid[:8]) if code == 200 and isinstance(u, dict) else uid[:8]
94
+ return self._users[uid]
95
+
96
+ def _chan_label(self, cid: str) -> str:
97
+ if cid not in self._label:
98
+ code, ch = self._api("GET", f"/channels/{cid}")
99
+ if code == 200 and isinstance(ch, dict):
100
+ return self._learn_channel(ch)
101
+ self._label[cid] = cid
102
+ return self._label[cid]
103
+
104
+ async def _aio(self) -> None:
105
+ base = self._base()
106
+ url = self.p.x("ws_url") or (
107
+ ("wss" if base.startswith("https") else "ws") + base[base.index("://"):] + "/api/v4/websocket")
108
+ kw: dict[str, Any] = {"open_timeout": 10}
109
+ if url.startswith("wss"):
110
+ from src.chat.util import ssl_context
111
+ kw["ssl"] = ssl_context(self.p.verify_tls)
112
+ async with ws_connect(url, **kw) as ws:
113
+ self._ws = ws
114
+ await ws.send(json.dumps({"seq": 1, "action": "authentication_challenge", "data": {"token": self._token}}))
115
+ async for raw in ws:
116
+ try:
117
+ ev = json.loads(raw)
118
+ except ValueError:
119
+ continue
120
+ if ev.get("status") == "FAIL":
121
+ raise AdapterFatal("Mattermost: autenticação do WebSocket recusada.")
122
+ if ev.get("event") == "hello" or (ev.get("status") == "OK" and not self._connected):
123
+ if not self._connected:
124
+ self._mark_up(f"Mattermost: conectado como {self._me_name}")
125
+ for name in self.p.channels:
126
+ self.join(name)
127
+ elif ev.get("event") == "posted":
128
+ self._on_posted(ev)
129
+
130
+ def _on_posted(self, ev: dict) -> None:
131
+ data = ev.get("data", {})
132
+ try:
133
+ post = json.loads(data.get("post", "{}"))
134
+ except ValueError:
135
+ return
136
+ if post.get("user_id") == self._me or str(post.get("type", "")).startswith("system_"):
137
+ return
138
+ label = self._chan_label(post.get("channel_id", ""))
139
+ sender = (data.get("sender_name") or "").lstrip("@") or self._username(post.get("user_id", "?"))
140
+ text = post.get("message", "")
141
+ self.ev.message(label, sender, text, "msg", post["create_at"] / 1000 if post.get("create_at") else None)
142
+
143
+ def join(self, channel: str, key: str = "") -> None:
144
+ cid = self._id.get(channel) or self._id.get(channel.lstrip("#"))
145
+ if not cid and self._team:
146
+ code, ch = self._api("GET", f"/teams/{self._team}/channels/name/{channel.lstrip('#')}")
147
+ if code == 200:
148
+ cid = ch["id"]
149
+ self._api("POST", f"/channels/{cid}/members", {"user_id": self._me})
150
+ self._learn_channel(ch)
151
+ if not cid:
152
+ self.ev.error(f"Mattermost: canal '{channel}' não encontrado.")
153
+ return
154
+ label = self._label.get(cid, channel)
155
+ self.ev.join(label, self._me_name)
156
+ code, users = self._api("GET", "/users", params={"in_channel": cid, "per_page": 200})
157
+ if code == 200 and isinstance(users, list):
158
+ self.ev.names(label, [u.get("username", "") for u in users])
159
+
160
+ def part(self, channel: str, reason: str = "") -> None:
161
+ cid = self._id.get(channel)
162
+ if cid and not channel.startswith("@"):
163
+ self._api("DELETE", f"/channels/{cid}/members/{self._me}")
164
+ self.ev.part(channel, self._me_name, "")
165
+
166
+ def _deliver(self, target: str, text: str) -> None:
167
+ cid = self._id.get(target) or target
168
+ for part in split_chars(text, 15000):
169
+ code, resp = self._api("POST", "/posts", {"channel_id": cid, "message": part})
170
+ if code not in (200, 201):
171
+ raise HTTPFailure(code, str(resp.get("message", "falha ao enviar")))
172
+
173
+ @property
174
+ def current_nick(self) -> str:
175
+ return self._me_name or self.p.jid or self.p.nick
176
+
177
+ def is_dm(self, name: str) -> bool:
178
+ return name.startswith("@")
@@ -0,0 +1,165 @@
1
+ """Cliente MQTT 3.1.1 (stdlib): keepalive, remaining-length completo, auth, wildcards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import secrets
8
+ import socket
9
+ import threading
10
+ import time
11
+
12
+ from src.chat.adapters.base import Adapter, AdapterFatal
13
+ from src.chat.util import mqtt_decode_len, mqtt_encode_len, ssl_context
14
+
15
+ KEEPALIVE_S = 30
16
+ _CONNACK_ERR = {1: "versão do protocolo recusada", 2: "client_id recusado",
17
+ 3: "broker indisponível", 4: "usuário/senha inválidos", 5: "não autorizado"}
18
+
19
+
20
+ def _s(text: str) -> bytes:
21
+ b = text.encode("utf-8")
22
+ return len(b).to_bytes(2, "big") + b
23
+
24
+
25
+ class MQTTAdapter(Adapter):
26
+ echoes_self = True
27
+ learn_nicks = False
28
+
29
+ def __init__(self, *a, **k) -> None:
30
+ super().__init__(*a, **k)
31
+ self._sock: socket.socket | None = None
32
+ self._lock = threading.Lock()
33
+ self._pid = 0
34
+ self._topics: list[str] = []
35
+ self._client_id = ""
36
+
37
+ def _write(self, data: bytes) -> None:
38
+ s = self._sock
39
+ if not s:
40
+ raise ConnectionError("sem conexão")
41
+ with self._lock:
42
+ s.sendall(data)
43
+
44
+ def _packet(self, first: int, body: bytes) -> bytes:
45
+ return bytes([first]) + mqtt_encode_len(len(body)) + body
46
+
47
+ def _next_pid(self) -> int:
48
+ self._pid = self._pid % 65535 + 1
49
+ return self._pid
50
+
51
+ def _session_once(self) -> None:
52
+ p = self.p
53
+ try:
54
+ raw = socket.create_connection((p.host, p.port), timeout=15)
55
+ if p.tls:
56
+ raw = ssl_context(p.verify_tls).wrap_socket(raw, server_hostname=p.host)
57
+ except OSError as exc:
58
+ raise ConnectionError(f"MQTT: {exc}") from exc
59
+ self._sock = raw
60
+ raw.settimeout(KEEPALIVE_S / 2)
61
+ user, pw = p.jid or "", p.decoded_password()
62
+ self._client_id = f"{(p.nick or 'Codis')[:16]}-{secrets.token_hex(3)}"
63
+ flags = 0x02 | (0x80 if user else 0) | (0x40 if (user and pw) else 0)
64
+ body = _s("MQTT") + bytes([4, flags]) + KEEPALIVE_S.to_bytes(2, "big") + _s(self._client_id)
65
+ if user:
66
+ body += _s(user)
67
+ if pw:
68
+ body += _s(pw)
69
+ self._write(self._packet(0x10, body))
70
+
71
+ buf = b""
72
+ acked = False
73
+ last_tx = time.monotonic()
74
+ try:
75
+ while not self._stop.is_set():
76
+ with contextlib.suppress(TimeoutError):
77
+ chunk = raw.recv(8192)
78
+ if not chunk:
79
+ raise ConnectionError("broker fechou a conexão")
80
+ buf += chunk
81
+ buf, acked = self._parse(buf, acked)
82
+ if acked and time.monotonic() - last_tx >= KEEPALIVE_S / 2:
83
+ self._write(b"\xc0\x00")
84
+ last_tx = time.monotonic()
85
+ finally:
86
+ with contextlib.suppress(OSError):
87
+ raw.close()
88
+ self._sock = None
89
+
90
+ def _parse(self, buf: bytes, acked: bool) -> tuple[bytes, bool]:
91
+ while len(buf) >= 2:
92
+ dec = mqtt_decode_len(buf, 1)
93
+ if dec is None:
94
+ break
95
+ rem, start = dec
96
+ if len(buf) < start + rem:
97
+ break
98
+ first, body, buf = buf[0], buf[start:start + rem], buf[start + rem:]
99
+ ptype = first >> 4
100
+ if ptype == 2:
101
+ rc = body[1] if len(body) >= 2 else 255
102
+ if rc != 0:
103
+ raise AdapterFatal(f"MQTT: {_CONNACK_ERR.get(rc, f'CONNACK rc={rc}')}")
104
+ acked = True
105
+ self._mark_up(f"MQTT: conectado a {self.p.host}")
106
+ self._topics = []
107
+ for t in self.p.channels:
108
+ self.join(t)
109
+ elif ptype == 3:
110
+ self._on_publish(first, body)
111
+ elif ptype == 9 and body[2:] and body[2] == 0x80:
112
+ self.ev.error("MQTT: assinatura recusada pelo broker.")
113
+ return buf, acked
114
+
115
+ def _on_publish(self, first: int, body: bytes) -> None:
116
+ qos = (first >> 1) & 3
117
+ if len(body) < 2:
118
+ return
119
+ tlen = int.from_bytes(body[:2], "big")
120
+ topic = body[2:2 + tlen].decode("utf-8", errors="replace")
121
+ pos = 2 + tlen
122
+ if qos:
123
+ pid = body[pos:pos + 2]
124
+ pos += 2
125
+ self._write(self._packet(0x40 if qos == 1 else 0x50, pid))
126
+ payload = body[pos:].decode(self.p.encoding or "utf-8", errors="replace")
127
+ nick, text = "mqtt", payload
128
+ if payload.startswith("{"):
129
+ with contextlib.suppress(ValueError):
130
+ d = json.loads(payload)
131
+ if isinstance(d, dict) and "msg" in d:
132
+ nick, text = str(d.get("user") or "mqtt"), str(d["msg"])
133
+ self.ev.message(topic, nick, text, "msg", None)
134
+
135
+ def _close(self) -> None:
136
+ s = self._sock
137
+ if s:
138
+ with contextlib.suppress(OSError):
139
+ s.sendall(b"\xe0\x00")
140
+ with contextlib.suppress(OSError):
141
+ s.shutdown(socket.SHUT_RDWR)
142
+
143
+ def join(self, channel: str, key: str = "") -> None:
144
+ self._write(self._packet(0x82, self._next_pid().to_bytes(2, "big") + _s(channel) + b"\x00"))
145
+ self._topics.append(channel)
146
+ self.ev.join(channel, self.p.nick)
147
+
148
+ def part(self, channel: str, reason: str = "") -> None:
149
+ with contextlib.suppress(Exception):
150
+ self._write(self._packet(0xA2, self._next_pid().to_bytes(2, "big") + _s(channel)))
151
+ self.ev.part(channel, self.current_nick, "")
152
+
153
+ def _deliver(self, target: str, text: str) -> None:
154
+ if "+" in target or "#" in target:
155
+ raise ValueError("não é possível publicar em tópico com curinga (+ ou #)")
156
+ payload = (json.dumps({"user": self.p.nick, "msg": text}, ensure_ascii=False)
157
+ if self.p.x("mqtt_format", "plain") == "json" else text)
158
+ self._write(self._packet(0x30, _s(target) + payload.encode("utf-8")))
159
+
160
+ @property
161
+ def current_nick(self) -> str:
162
+ return self.p.nick
163
+
164
+ def is_dm(self, name: str) -> bool:
165
+ return False
@@ -0,0 +1,204 @@
1
+ """Slack: Socket Mode (xapp-), RTM (apps clássicos) ou polling (fallback universal)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import time
8
+ from typing import Any
9
+
10
+ from src.chat.adapters.base import AdapterFatal
11
+ from src.chat.adapters.http import HTTPFailure, request_json
12
+ from src.chat.adapters.ws import HAS_WS, AsyncAdapter, ws_connect
13
+ from src.chat.util import split_chars
14
+
15
+ _FATAL = {"invalid_auth", "not_authed", "token_revoked", "account_inactive", "token_expired", "invalid_token"}
16
+ _SHOW_SUBTYPES = {None, "me_message", "bot_message", "thread_broadcast", "file_share"}
17
+
18
+
19
+ def slack_unescape(text: str, user_name=lambda uid: uid) -> str:
20
+ text = re.sub(r"<@([UW][A-Z0-9]+)(?:\|[^>]*)?>", lambda m: "@" + user_name(m.group(1)), text)
21
+ text = re.sub(r"<#[A-Z0-9]+\|([^>]+)>", r"#\1", text)
22
+ text = re.sub(r"<!(here|channel|everyone)[^>]*>", r"@\1", text)
23
+ text = re.sub(r"<(https?://[^|>]+)\|([^>]+)>", r"\2 (\1)", text)
24
+ text = re.sub(r"<((?:https?|mailto):[^>]+)>", r"\1", text)
25
+ return text.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
26
+
27
+
28
+ class SlackAdapter(AsyncAdapter):
29
+ learn_nicks = True
30
+
31
+ def __init__(self, *a: Any, **k: Any) -> None:
32
+ super().__init__(*a, **k)
33
+ self._uid = ""
34
+ self._me = ""
35
+ self._chan_name: dict[str, str] = {}
36
+ self._chan_id: dict[str, str] = {}
37
+ self._users: dict[str, str] = {}
38
+ self.poll_interval = 4.0
39
+
40
+ def _base(self) -> str:
41
+ return self.p.x("api_base", "https://slack.com").rstrip("/")
42
+
43
+ def _api(self, method: str, params: dict | None = None, token: str | None = None) -> dict:
44
+ status, data = request_json("POST", f"{self._base()}/api/{method}",
45
+ headers={"Authorization": f"Bearer {token or self.p.decoded_token()}"},
46
+ body=params or {}, verify=self.p.verify_tls)
47
+ if not isinstance(data, dict) or status >= 500 or status == -1:
48
+ raise HTTPFailure(status, f"Slack {method}")
49
+ return data
50
+
51
+ def _check(self, data: dict, what: str) -> dict:
52
+ if not data.get("ok"):
53
+ err = data.get("error", "erro")
54
+ if err in _FATAL:
55
+ raise AdapterFatal(f"Slack: {err} ({what}) - confira o token.")
56
+ raise HTTPFailure(0, f"Slack {what}: {err}")
57
+ return data
58
+
59
+ def _session_once(self) -> None:
60
+ auth = self._check(self._api("auth.test"), "auth.test")
61
+ self._uid, self._me = auth.get("user_id", ""), auth.get("user", "")
62
+ self._users[self._uid] = self._me
63
+ self._chan_name.clear()
64
+ self._chan_id.clear()
65
+ cursor = ""
66
+ while True:
67
+ data = self._api("conversations.list", {"types": "public_channel,private_channel",
68
+ "limit": 200, "exclude_archived": True, "cursor": cursor})
69
+ if not data.get("ok"):
70
+ break
71
+ for c in data.get("channels", []):
72
+ self._remember(c["id"], c.get("name", c["id"]))
73
+ cursor = data.get("response_metadata", {}).get("next_cursor", "")
74
+ if not cursor:
75
+ break
76
+ self._mark_up(f"Slack: conectado como {self._me}")
77
+ for ch in self.p.channels:
78
+ self.join(ch)
79
+ app = self.p.x("app_token")
80
+ url, enveloped = "", False
81
+ if app:
82
+ d = self._check(self._api("apps.connections.open", token=app), "apps.connections.open")
83
+ url, enveloped = d["url"], True
84
+ else:
85
+ d = self._api("rtm.connect")
86
+ if d.get("ok"):
87
+ url = d["url"]
88
+ else:
89
+ self.ev.info("*server*", f"Slack: RTM indisponível ({d.get('error')}); usando polling a cada "
90
+ f"{int(self.poll_interval)}s. Para tempo real use um App Token (xapp-).")
91
+ if url and HAS_WS:
92
+ self._url, self._env = url, enveloped
93
+ super()._session_once()
94
+ else:
95
+ self._poll()
96
+
97
+ def _remember(self, cid: str, name: str) -> None:
98
+ self._chan_name[cid] = name
99
+ self._chan_id[name] = cid
100
+ self._chan_id[cid] = cid
101
+
102
+ def _label(self, cid: str) -> str:
103
+ if cid not in self._chan_name:
104
+ d = self._api("conversations.info", {"channel": cid})
105
+ ch = d.get("channel", {}) if d.get("ok") else {}
106
+ if ch.get("is_im"):
107
+ name = "@" + self._user(ch.get("user", cid))
108
+ else:
109
+ name = ch.get("name", cid)
110
+ self._remember(cid, name)
111
+ return self._chan_name[cid]
112
+
113
+ def _user(self, uid: str) -> str:
114
+ if uid not in self._users:
115
+ d = self._api("users.info", {"user": uid})
116
+ u = d.get("user", {}) if d.get("ok") else {}
117
+ prof = u.get("profile", {})
118
+ self._users[uid] = prof.get("display_name") or u.get("name") or uid
119
+ return self._users[uid]
120
+
121
+ async def _aio(self) -> None:
122
+ async with ws_connect(self._url, open_timeout=10) as ws:
123
+ self._ws = ws
124
+ async for raw in ws:
125
+ try:
126
+ ev = json.loads(raw)
127
+ except ValueError:
128
+ continue
129
+ if self._env:
130
+ if ev.get("envelope_id"):
131
+ await ws.send(json.dumps({"envelope_id": ev["envelope_id"]}))
132
+ if ev.get("type") == "disconnect":
133
+ raise ConnectionError("Slack pediu reconexão")
134
+ ev = ev.get("payload", {}).get("event", {}) if ev.get("type") == "events_api" else {}
135
+ self._on_event(ev)
136
+
137
+ def _on_event(self, ev: dict) -> None:
138
+ if ev.get("type") != "message" or ev.get("subtype") not in _SHOW_SUBTYPES:
139
+ return
140
+ uid = ev.get("user", "")
141
+ if uid == self._uid or not ev.get("text"):
142
+ return
143
+ cid = ev.get("channel", "")
144
+ nick = self._user(uid) if uid else ev.get("username", ev.get("bot_profile", {}).get("name", "bot"))
145
+ text = slack_unescape(ev["text"], self._user)
146
+ kind = "action" if ev.get("subtype") == "me_message" else "msg"
147
+ try:
148
+ ts = float(ev.get("ts", ""))
149
+ except ValueError:
150
+ ts = None
151
+ self.ev.message(self._label(cid), nick, text, kind, ts)
152
+
153
+ def _poll(self) -> None:
154
+ last: dict[str, str] = {}
155
+ start = f"{time.time():.6f}"
156
+ while not self._stop.is_set():
157
+ ids = [self._chan_id[c.lstrip("#")] for c in self.p.channels if c.lstrip("#") in self._chan_id]
158
+ for ch in ids:
159
+ d = self._api("conversations.history", {"channel": ch, "oldest": last.get(ch, start), "limit": 50})
160
+ if not d.get("ok"):
161
+ if d.get("error") in _FATAL:
162
+ raise AdapterFatal(f"Slack: {d['error']}")
163
+ continue
164
+ for m in reversed(d.get("messages", [])):
165
+ last[ch] = max(last.get(ch, "0"), m.get("ts", "0"))
166
+ m["channel"] = ch
167
+ m.setdefault("type", "message")
168
+ self._on_event(m)
169
+ self._stop.wait(self.poll_interval)
170
+
171
+ def join(self, channel: str, key: str = "") -> None:
172
+ name = channel.lstrip("#")
173
+ cid = self._chan_id.get(name)
174
+ if not cid:
175
+ self.ev.error(f"Slack: canal '{channel}' não encontrado.")
176
+ return
177
+ self._api("conversations.join", {"channel": cid})
178
+ self.ev.join(name, self._me)
179
+
180
+ def part(self, channel: str, reason: str = "") -> None:
181
+ cid = self._chan_id.get(channel.lstrip("#"))
182
+ if cid and not channel.startswith("@"):
183
+ self._api("conversations.leave", {"channel": cid})
184
+ self.ev.part(channel, self._me, "")
185
+
186
+ def _post(self, method: str, target: str, text: str) -> None:
187
+ cid = self._chan_id.get(target.lstrip("#")) or target
188
+ d = self._api(method, {"channel": cid, "text": text})
189
+ if not d.get("ok"):
190
+ raise HTTPFailure(0, f"Slack: {d.get('error', 'falha ao enviar')}")
191
+
192
+ def _deliver(self, target: str, text: str) -> None:
193
+ for part in split_chars(text, 3900):
194
+ self._post("chat.postMessage", target, part)
195
+
196
+ def _deliver_action(self, target: str, text: str) -> None:
197
+ self._post("chat.meMessage", target, text)
198
+
199
+ @property
200
+ def current_nick(self) -> str:
201
+ return self._me or self.p.nick
202
+
203
+ def is_dm(self, name: str) -> bool:
204
+ return name.startswith("@")
@@ -0,0 +1,117 @@
1
+ """Telegram Bot API (long-polling)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+
7
+ from src.chat.adapters.base import Adapter, AdapterFatal
8
+ from src.chat.adapters.http import HTTPFailure, request_json
9
+ from src.chat.util import split_chars
10
+
11
+ API = "https://api.telegram.org"
12
+
13
+
14
+ class TelegramAdapter(Adapter):
15
+ learn_nicks = True
16
+ max_bytes = 0
17
+
18
+ def __init__(self, *a, **k) -> None:
19
+ super().__init__(*a, **k)
20
+ self._offset = 0
21
+ self._chats: dict[str, str] = {}
22
+ self._bot = "bot"
23
+
24
+ def _call(self, method: str, params: dict | None = None, timeout: float = 15) -> dict:
25
+ base = self.p.x("api_base", API).rstrip("/")
26
+ status, data = request_json("POST", f"{base}/bot{self.p.decoded_token()}/{method}",
27
+ body=params or {}, timeout=timeout, verify=self.p.verify_tls)
28
+ if not isinstance(data, dict) or not data.get("ok"):
29
+ desc = (data or {}).get("description", f"HTTP {status}") if isinstance(data, dict) else f"HTTP {status}"
30
+ if status in (401, 404):
31
+ raise AdapterFatal(f"Telegram: token inválido ({desc})")
32
+ if status == 409:
33
+ raise AdapterFatal("Telegram: outro cliente/webhook está usando este bot (409).")
34
+ raise HTTPFailure(status, desc)
35
+ return data
36
+
37
+ @staticmethod
38
+ def _name_of(chat: dict) -> str:
39
+ if chat.get("username"):
40
+ return "@" + chat["username"]
41
+ return (chat.get("title") or " ".join(x for x in (chat.get("first_name"), chat.get("last_name")) if x)
42
+ or str(chat.get("id", "?")))
43
+
44
+ def _register(self, chat: dict) -> str:
45
+ name = self._name_of(chat)
46
+ cid = str(chat["id"])
47
+ if self._chats.get(name, cid) != cid:
48
+ name = f"{name} ({cid})"
49
+ self._chats[name] = cid
50
+ return name
51
+
52
+ def _session_once(self) -> None:
53
+ me = self._call("getMe")
54
+ self._bot = me["result"].get("username", "bot")
55
+ self._chats.clear()
56
+ self._mark_up(f"Telegram: conectado como @{self._bot}")
57
+ for ch in self.p.channels:
58
+ self.join(ch)
59
+ while not self._stop.is_set():
60
+ try:
61
+ data = self._call("getUpdates", {"offset": self._offset, "timeout": 25,
62
+ "allowed_updates": ["message", "channel_post"]}, timeout=40)
63
+ except HTTPFailure as exc:
64
+ if exc.status == 429:
65
+ time.sleep(2)
66
+ continue
67
+ raise
68
+ for upd in data.get("result", []):
69
+ self._offset = upd["update_id"] + 1
70
+ msg = upd.get("message") or upd.get("channel_post")
71
+ if msg:
72
+ self._on_message(msg)
73
+
74
+ def _on_message(self, msg: dict) -> None:
75
+ chat = msg.get("chat", {})
76
+ if "id" not in chat:
77
+ return
78
+ frm = msg.get("from") or {}
79
+ sender = (("@" + frm["username"]) if frm.get("username") else
80
+ " ".join(x for x in (frm.get("first_name"), frm.get("last_name")) if x)
81
+ or msg.get("author_signature") or chat.get("title") or "?")
82
+ sender = sender.lstrip("@")
83
+ text = msg.get("text") or msg.get("caption") or ""
84
+ for key, label in (("photo", "[foto]"), ("document", "[arquivo]"), ("voice", "[áudio]"),
85
+ ("video", "[vídeo]"), ("sticker", "[figurinha]"), ("location", "[localização]")):
86
+ if key in msg:
87
+ extra = msg[key].get("file_name", "") if isinstance(msg[key], dict) else ""
88
+ text = f"{label} {extra} {text}".strip()
89
+ break
90
+ if not text:
91
+ return
92
+ ch = self._register(chat)
93
+ kind = "msg"
94
+ ts = float(msg["date"]) if "date" in msg else None
95
+ self.ev.message(ch, sender, text, kind, ts)
96
+
97
+ def join(self, channel: str, key: str = "") -> None:
98
+ cid = channel if channel.lstrip("-").isdigit() else ("@" + channel.lstrip("@"))
99
+ try:
100
+ chat = self._call("getChat", {"chat_id": cid})["result"]
101
+ except HTTPFailure as exc:
102
+ self.ev.error(f"Telegram: não achei {channel} ({exc})")
103
+ return
104
+ name = self._register(chat)
105
+ self.ev.join(name, self._bot)
106
+
107
+ def _deliver(self, target: str, text: str) -> None:
108
+ cid = self._chats.get(target) or (target if target.lstrip("-").isdigit() else "@" + target.lstrip("@"))
109
+ for part in split_chars(text, 4096):
110
+ self._call("sendMessage", {"chat_id": cid, "text": part, "disable_web_page_preview": False})
111
+
112
+ @property
113
+ def current_nick(self) -> str:
114
+ return self._bot
115
+
116
+ def part(self, channel: str, reason: str = "") -> None:
117
+ self.ev.part(channel, self._bot, "")