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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/chat/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Codis Chat - núcleo de mensageria multi-protocolo (sem dependência de Tk)."""
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Adaptadores de protocolo do Chat."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from src.chat.adapters.base import SERVER_TAB, Adapter, AdapterFatal, Backoff, Events
|
|
6
|
+
from src.chat.models import ChatProfile, ChatProtocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_adapter(profile: ChatProfile, events: Events | None = None) -> Adapter:
|
|
10
|
+
"""Instancia o adaptador do protocolo do perfil (import tardio: carrega só o necessário)."""
|
|
11
|
+
proto = profile.proto
|
|
12
|
+
if proto in (ChatProtocol.IRC, ChatProtocol.IRCS):
|
|
13
|
+
from src.chat.adapters.irc import IRCAdapter as cls
|
|
14
|
+
elif proto in (ChatProtocol.XMPP, ChatProtocol.XMPPS):
|
|
15
|
+
from src.chat.adapters.xmpp import XMPPAdapter as cls
|
|
16
|
+
elif proto == ChatProtocol.MATRIX:
|
|
17
|
+
from src.chat.adapters.matrix import MatrixAdapter as cls
|
|
18
|
+
elif proto == ChatProtocol.SLACK:
|
|
19
|
+
from src.chat.adapters.slack import SlackAdapter as cls
|
|
20
|
+
elif proto == ChatProtocol.DISCORD:
|
|
21
|
+
from src.chat.adapters.discord import DiscordAdapter as cls
|
|
22
|
+
elif proto == ChatProtocol.TELEGRAM:
|
|
23
|
+
from src.chat.adapters.telegram import TelegramAdapter as cls
|
|
24
|
+
elif proto == ChatProtocol.MATTERMOST:
|
|
25
|
+
from src.chat.adapters.mattermost import MattermostAdapter as cls
|
|
26
|
+
elif proto == ChatProtocol.MQTT:
|
|
27
|
+
from src.chat.adapters.mqtt import MQTTAdapter as cls
|
|
28
|
+
else:
|
|
29
|
+
from src.chat.adapters.ws import WSAdapter as cls
|
|
30
|
+
return cls(profile, events)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
__all__ = ["SERVER_TAB", "Adapter", "AdapterFatal", "Backoff", "Events", "make_adapter"]
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Base dos adaptadores: ciclo de vida com reconexão, fila de envio e eventos."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import queue
|
|
7
|
+
import random
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from src.chat.models import ChatProfile
|
|
14
|
+
from src.chat.util import clean_line, split_utf8
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("Codis.Chat")
|
|
17
|
+
|
|
18
|
+
SERVER_TAB = "*server*"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _noop(*_a: Any, **_k: Any) -> None:
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Events:
|
|
27
|
+
"""Callbacks que o adaptador dispara (de qualquer thread). Todos são opcionais."""
|
|
28
|
+
|
|
29
|
+
message: Callable[..., None] = _noop
|
|
30
|
+
own: Callable[..., None] = _noop
|
|
31
|
+
join: Callable[..., None] = _noop
|
|
32
|
+
part: Callable[..., None] = _noop
|
|
33
|
+
nick: Callable[..., None] = _noop
|
|
34
|
+
topic: Callable[..., None] = _noop
|
|
35
|
+
names: Callable[..., None] = _noop
|
|
36
|
+
connect: Callable[..., None] = _noop
|
|
37
|
+
error: Callable[..., None] = _noop
|
|
38
|
+
info: Callable[..., None] = _noop
|
|
39
|
+
disconnect: Callable[..., None] = _noop
|
|
40
|
+
reconnecting: Callable[..., None] = _noop
|
|
41
|
+
raw: Callable[..., None] = _noop
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AdapterFatal(Exception):
|
|
45
|
+
"""Erro que não adianta repetir (senha errada, token inválido): não reconecta."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Backoff:
|
|
50
|
+
base: float = 1.0
|
|
51
|
+
cap: float = 60.0
|
|
52
|
+
attempt: int = 0
|
|
53
|
+
_rng: random.Random = field(default_factory=random.Random, repr=False)
|
|
54
|
+
|
|
55
|
+
def next(self) -> float:
|
|
56
|
+
d = min(self.cap, self.base * (2**self.attempt))
|
|
57
|
+
self.attempt += 1
|
|
58
|
+
return d * (0.85 + self._rng.random() * 0.3)
|
|
59
|
+
|
|
60
|
+
def reset(self) -> None:
|
|
61
|
+
self.attempt = 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Adapter:
|
|
65
|
+
"""Interface comum. Subclasses implementam ``_session_once`` e ``_deliver``.
|
|
66
|
+
|
|
67
|
+
* ``_session_once`` bloqueia enquanto a conexão viver; retorna/levanta ao cair.
|
|
68
|
+
* ``_deliver`` envia UMA linha (já saneada/dividida) e levanta em caso de falha.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
max_bytes = 0
|
|
72
|
+
echoes_self = False
|
|
73
|
+
multiline = True
|
|
74
|
+
learn_nicks = False
|
|
75
|
+
backoff_base = 1.0
|
|
76
|
+
|
|
77
|
+
def __init__(self, profile: ChatProfile, events: Events | None = None) -> None:
|
|
78
|
+
self.p = profile
|
|
79
|
+
self.ev = events or Events()
|
|
80
|
+
self._stop = threading.Event()
|
|
81
|
+
self._connected = False
|
|
82
|
+
self._was_up = False
|
|
83
|
+
self._outq: queue.Queue[tuple[str, str, str] | None] = queue.Queue()
|
|
84
|
+
self._thread: threading.Thread | None = None
|
|
85
|
+
self._worker: threading.Thread | None = None
|
|
86
|
+
|
|
87
|
+
def connect(self) -> None:
|
|
88
|
+
if self._thread and self._thread.is_alive():
|
|
89
|
+
return
|
|
90
|
+
self._stop.clear()
|
|
91
|
+
self._thread = threading.Thread(target=self._supervise, daemon=True,
|
|
92
|
+
name=f"Codis-{type(self).__name__}")
|
|
93
|
+
self._thread.start()
|
|
94
|
+
self._worker = threading.Thread(target=self._send_loop, daemon=True,
|
|
95
|
+
name=f"Codis-{type(self).__name__}-tx")
|
|
96
|
+
self._worker.start()
|
|
97
|
+
|
|
98
|
+
def _supervise(self) -> None:
|
|
99
|
+
backoff = Backoff(base=self.backoff_base)
|
|
100
|
+
while not self._stop.is_set():
|
|
101
|
+
self._was_up = False
|
|
102
|
+
reason = ""
|
|
103
|
+
try:
|
|
104
|
+
self._session_once()
|
|
105
|
+
except AdapterFatal as exc:
|
|
106
|
+
self._connected = False
|
|
107
|
+
self.ev.error(str(exc))
|
|
108
|
+
break
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
if not self._stop.is_set():
|
|
111
|
+
logger.debug("%s caiu", type(self).__name__, exc_info=True)
|
|
112
|
+
reason = str(exc) or type(exc).__name__
|
|
113
|
+
self._connected = False
|
|
114
|
+
if self._stop.is_set():
|
|
115
|
+
break
|
|
116
|
+
if self._was_up:
|
|
117
|
+
backoff.reset()
|
|
118
|
+
self.ev.disconnect(reason or "conexão encerrada")
|
|
119
|
+
if not self.p.auto_reconnect:
|
|
120
|
+
break
|
|
121
|
+
delay = backoff.next()
|
|
122
|
+
self.ev.reconnecting(delay)
|
|
123
|
+
if self._stop.wait(delay):
|
|
124
|
+
break
|
|
125
|
+
self._connected = False
|
|
126
|
+
|
|
127
|
+
def _mark_up(self, msg: str) -> None:
|
|
128
|
+
self._connected = True
|
|
129
|
+
self._was_up = True
|
|
130
|
+
self.ev.connect(msg)
|
|
131
|
+
|
|
132
|
+
def _session_once(self) -> None:
|
|
133
|
+
raise NotImplementedError
|
|
134
|
+
|
|
135
|
+
def _close(self) -> None:
|
|
136
|
+
"""Interrompe a I/O bloqueante da sessão atual (fecha socket, loop...)."""
|
|
137
|
+
|
|
138
|
+
def quit(self, reason: str = "Codis") -> None:
|
|
139
|
+
self._stop.set()
|
|
140
|
+
self._connected = False
|
|
141
|
+
self._outq.put(None)
|
|
142
|
+
try:
|
|
143
|
+
self._close()
|
|
144
|
+
except Exception:
|
|
145
|
+
logger.debug("falha ao fechar", exc_info=True)
|
|
146
|
+
|
|
147
|
+
def send(self, target: str, text: str) -> None:
|
|
148
|
+
self._enqueue(target, text, "msg")
|
|
149
|
+
|
|
150
|
+
def send_action(self, target: str, text: str) -> None:
|
|
151
|
+
self._enqueue(target, text, "action")
|
|
152
|
+
|
|
153
|
+
def _enqueue(self, target: str, text: str, kind: str) -> None:
|
|
154
|
+
if not self._connected:
|
|
155
|
+
self.ev.error("Não conectado: mensagem não enviada.")
|
|
156
|
+
return
|
|
157
|
+
chunks = text.split("\n") if not self.multiline else [text]
|
|
158
|
+
for chunk in chunks:
|
|
159
|
+
chunk = clean_line(chunk) if not self.multiline else chunk.replace("\x00", "")
|
|
160
|
+
if not chunk.strip():
|
|
161
|
+
continue
|
|
162
|
+
parts = (split_utf8(chunk, max(16, self.max_bytes - len(target.encode())))
|
|
163
|
+
if self.max_bytes else [chunk])
|
|
164
|
+
for part in parts:
|
|
165
|
+
self._outq.put((target, part, kind))
|
|
166
|
+
|
|
167
|
+
def _send_loop(self) -> None:
|
|
168
|
+
while True:
|
|
169
|
+
item = self._outq.get()
|
|
170
|
+
if item is None or self._stop.is_set():
|
|
171
|
+
return
|
|
172
|
+
target, text, kind = item
|
|
173
|
+
try:
|
|
174
|
+
if kind == "action":
|
|
175
|
+
self._deliver_action(target, text)
|
|
176
|
+
else:
|
|
177
|
+
self._deliver(target, text)
|
|
178
|
+
except Exception as exc:
|
|
179
|
+
self.ev.error(f"Falha ao enviar para {target}: {exc}")
|
|
180
|
+
|
|
181
|
+
def _deliver(self, target: str, text: str) -> None:
|
|
182
|
+
raise NotImplementedError
|
|
183
|
+
|
|
184
|
+
def _deliver_action(self, target: str, text: str) -> None:
|
|
185
|
+
self._deliver(target, f"_{self.current_nick} {text}_")
|
|
186
|
+
|
|
187
|
+
def join(self, channel: str, key: str = "") -> None:
|
|
188
|
+
self.ev.join(channel, self.current_nick)
|
|
189
|
+
|
|
190
|
+
def part(self, channel: str, reason: str = "") -> None:
|
|
191
|
+
self.ev.part(channel, self.current_nick, reason)
|
|
192
|
+
|
|
193
|
+
def handle_command(self, cmd: str, rest: str, active: str) -> bool:
|
|
194
|
+
"""True se ``/cmd rest`` foi tratado pelo adaptador (``cmd`` em MAIÚSCULAS)."""
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
def commands(self) -> list[str]:
|
|
198
|
+
return []
|
|
199
|
+
|
|
200
|
+
def is_dm(self, name: str) -> bool:
|
|
201
|
+
return name.startswith("@")
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def connected(self) -> bool:
|
|
205
|
+
return self._connected
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def current_nick(self) -> str:
|
|
209
|
+
return self.p.nick
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Discord Gateway v10 (heartbeat com ACK, intents corretos) + REST."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from src.chat.adapters.base import AdapterFatal
|
|
12
|
+
from src.chat.adapters.http import HTTPFailure, request_json
|
|
13
|
+
from src.chat.adapters.ws import AsyncAdapter, ws_connect
|
|
14
|
+
from src.chat.util import split_chars
|
|
15
|
+
|
|
16
|
+
GATEWAY = "wss://gateway.discord.gg/?v=10&encoding=json"
|
|
17
|
+
API = "https://discord.com/api/v10"
|
|
18
|
+
INTENTS = 1 | (1 << 9) | (1 << 12) | (1 << 15)
|
|
19
|
+
_FATAL_CLOSE = {
|
|
20
|
+
4004: "token inválido",
|
|
21
|
+
4010: "shard inválido", 4011: "sharding obrigatório", 4012: "versão da API inválida",
|
|
22
|
+
4013: "intents inválidas",
|
|
23
|
+
4014: "intent privilegiada não habilitada: ative 'Message Content Intent' no Developer Portal",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DiscordAdapter(AsyncAdapter):
|
|
28
|
+
learn_nicks = True
|
|
29
|
+
|
|
30
|
+
def __init__(self, *a: Any, **k: Any) -> None:
|
|
31
|
+
super().__init__(*a, **k)
|
|
32
|
+
self._seq: int | None = None
|
|
33
|
+
self._uid = ""
|
|
34
|
+
self._me = ""
|
|
35
|
+
self._label: dict[str, str] = {}
|
|
36
|
+
self._dm_ids: dict[str, str] = {}
|
|
37
|
+
self._user_ids: dict[str, str] = {}
|
|
38
|
+
|
|
39
|
+
def _headers(self) -> dict[str, str]:
|
|
40
|
+
tok = self.p.decoded_token()
|
|
41
|
+
return {"Authorization": tok if self.p.x("token_kind", "bot") == "user" else f"Bot {tok}"}
|
|
42
|
+
|
|
43
|
+
def _rest(self, method: str, path: str, body: Any = None) -> tuple[int, Any]:
|
|
44
|
+
return request_json(method, self.p.x("api_base", API).rstrip("/") + path, headers=self._headers(),
|
|
45
|
+
body=body, verify=self.p.verify_tls)
|
|
46
|
+
|
|
47
|
+
def _visible(self, cid: str) -> bool:
|
|
48
|
+
wanted = self.p.channels
|
|
49
|
+
if not wanted:
|
|
50
|
+
return True
|
|
51
|
+
label = self._label.get(cid, "")
|
|
52
|
+
return any(w == cid or w.lstrip("#").casefold() == label.lstrip("#").split(" ")[0].casefold()
|
|
53
|
+
for w in wanted)
|
|
54
|
+
|
|
55
|
+
async def _aio(self) -> None:
|
|
56
|
+
self._seq = None
|
|
57
|
+
async with ws_connect(self.p.x("gateway_url", GATEWAY), open_timeout=10, max_size=8 * 1024 * 1024) as ws:
|
|
58
|
+
self._ws = ws
|
|
59
|
+
hello = json.loads(await asyncio.wait_for(ws.recv(), 15))
|
|
60
|
+
interval = hello["d"]["heartbeat_interval"] / 1000
|
|
61
|
+
acked = {"v": True}
|
|
62
|
+
hb = asyncio.ensure_future(self._heartbeat(ws, interval, acked))
|
|
63
|
+
await ws.send(json.dumps({"op": 2, "d": {
|
|
64
|
+
"token": self.p.decoded_token(), "intents": INTENTS,
|
|
65
|
+
"properties": {"os": "linux", "browser": "Codis", "device": "Codis"}}}))
|
|
66
|
+
try:
|
|
67
|
+
async for raw in ws:
|
|
68
|
+
ev = json.loads(raw)
|
|
69
|
+
op, t, d = ev.get("op"), ev.get("t"), ev.get("d") or {}
|
|
70
|
+
if ev.get("s") is not None:
|
|
71
|
+
self._seq = ev["s"]
|
|
72
|
+
if op == 11:
|
|
73
|
+
acked["v"] = True
|
|
74
|
+
elif op == 1:
|
|
75
|
+
await ws.send(json.dumps({"op": 1, "d": self._seq}))
|
|
76
|
+
elif op in (7, 9):
|
|
77
|
+
raise ConnectionError("Discord pediu para reconectar")
|
|
78
|
+
elif op == 0:
|
|
79
|
+
self._dispatch(t, d)
|
|
80
|
+
except Exception as exc:
|
|
81
|
+
code = getattr(getattr(exc, "rcvd", None), "code", None)
|
|
82
|
+
if code in _FATAL_CLOSE:
|
|
83
|
+
raise AdapterFatal(f"Discord: {_FATAL_CLOSE[code]} (código {code})") from exc
|
|
84
|
+
raise
|
|
85
|
+
finally:
|
|
86
|
+
hb.cancel()
|
|
87
|
+
|
|
88
|
+
async def _heartbeat(self, ws: Any, interval: float, acked: dict) -> None:
|
|
89
|
+
await asyncio.sleep(interval * random.random())
|
|
90
|
+
while True:
|
|
91
|
+
if not acked["v"]:
|
|
92
|
+
await ws.close(code=4000, reason="sem ACK do heartbeat")
|
|
93
|
+
return
|
|
94
|
+
acked["v"] = False
|
|
95
|
+
await ws.send(json.dumps({"op": 1, "d": self._seq}))
|
|
96
|
+
await asyncio.sleep(interval)
|
|
97
|
+
|
|
98
|
+
def _add_channels(self, d: dict) -> None:
|
|
99
|
+
guild = d.get("name", "")
|
|
100
|
+
for ch in d.get("channels", []):
|
|
101
|
+
if ch.get("type") in (0, 5, 15):
|
|
102
|
+
self._register(ch["id"], ch["name"], guild)
|
|
103
|
+
|
|
104
|
+
def _register(self, cid: str, name: str, guild: str) -> None:
|
|
105
|
+
label = f"#{name}"
|
|
106
|
+
if label in self._label.values() and self._label.get(cid) != label:
|
|
107
|
+
label = f"#{name} ({guild})" if guild else f"#{name}-{cid[-4:]}"
|
|
108
|
+
self._label[cid] = label
|
|
109
|
+
|
|
110
|
+
def _dispatch(self, t: str, d: dict) -> None:
|
|
111
|
+
if t == "READY":
|
|
112
|
+
u = d.get("user", {})
|
|
113
|
+
self._uid, self._me = u.get("id", ""), u.get("username", "")
|
|
114
|
+
self._mark_up(f"Discord: conectado como {self._me}")
|
|
115
|
+
elif t in ("GUILD_CREATE", "CHANNEL_CREATE", "THREAD_CREATE"):
|
|
116
|
+
if t == "GUILD_CREATE":
|
|
117
|
+
self._add_channels(d)
|
|
118
|
+
for ch in d.get("channels", []):
|
|
119
|
+
if ch["id"] in self._label and self.p.channels and self._visible(ch["id"]):
|
|
120
|
+
self.ev.join(self._label[ch["id"]], self._me)
|
|
121
|
+
elif d.get("name"):
|
|
122
|
+
self._register(d["id"], d["name"], "")
|
|
123
|
+
elif t == "MESSAGE_CREATE":
|
|
124
|
+
self._on_message(d)
|
|
125
|
+
|
|
126
|
+
def _on_message(self, d: dict) -> None:
|
|
127
|
+
author = d.get("author", {})
|
|
128
|
+
if author.get("id") == self._uid:
|
|
129
|
+
return
|
|
130
|
+
cid = d.get("channel_id", "")
|
|
131
|
+
name = author.get("global_name") or author.get("username", "?")
|
|
132
|
+
if d.get("guild_id"):
|
|
133
|
+
if cid not in self._label:
|
|
134
|
+
self._label[cid] = f"#{cid}"
|
|
135
|
+
if not self._visible(cid):
|
|
136
|
+
return
|
|
137
|
+
label = self._label[cid]
|
|
138
|
+
else:
|
|
139
|
+
label = "@" + author.get("username", cid)
|
|
140
|
+
self._dm_ids[label] = cid
|
|
141
|
+
self._user_ids[label] = author.get("id", "")
|
|
142
|
+
text = d.get("content", "")
|
|
143
|
+
for m in d.get("mentions", []):
|
|
144
|
+
text = text.replace(f"<@{m['id']}>", "@" + m.get("username", "?")).replace(
|
|
145
|
+
f"<@!{m['id']}>", "@" + m.get("username", "?"))
|
|
146
|
+
text = re.sub(r"<#(\d+)>", lambda m: self._label.get(m.group(1), "#canal"), text)
|
|
147
|
+
for att in d.get("attachments", []):
|
|
148
|
+
text = f"{text} {att.get('url', '')}".strip()
|
|
149
|
+
if not text:
|
|
150
|
+
return
|
|
151
|
+
self.ev.message(label, name, text, "msg", None)
|
|
152
|
+
|
|
153
|
+
def _channel_id(self, target: str) -> str:
|
|
154
|
+
if target in self._dm_ids:
|
|
155
|
+
return self._dm_ids[target]
|
|
156
|
+
for cid, label in self._label.items():
|
|
157
|
+
if target in (label, cid) or target.lstrip("#") == label.lstrip("#"):
|
|
158
|
+
return cid
|
|
159
|
+
return target
|
|
160
|
+
|
|
161
|
+
def _deliver(self, target: str, text: str) -> None:
|
|
162
|
+
cid = self._channel_id(target)
|
|
163
|
+
if target.startswith("@") and cid == target:
|
|
164
|
+
uid = self._user_ids.get(target)
|
|
165
|
+
if not uid:
|
|
166
|
+
raise HTTPFailure(0, "responda a uma DM recebida primeiro (ID do usuário desconhecido)")
|
|
167
|
+
code, ch = self._rest("POST", "/users/@me/channels", {"recipient_id": uid})
|
|
168
|
+
cid = ch.get("id", "") if code == 200 else ""
|
|
169
|
+
self._dm_ids[target] = cid
|
|
170
|
+
for part in split_chars(text, 1990):
|
|
171
|
+
code, resp = self._rest("POST", f"/channels/{cid}/messages",
|
|
172
|
+
{"content": part, "allowed_mentions": {"parse": []}})
|
|
173
|
+
if code not in (200, 201):
|
|
174
|
+
raise HTTPFailure(code, str(resp.get("message", "falha ao enviar")) if isinstance(resp, dict) else "")
|
|
175
|
+
|
|
176
|
+
def _deliver_action(self, target: str, text: str) -> None:
|
|
177
|
+
self._deliver(target, f"_{self._me or self.p.nick} {text}_")
|
|
178
|
+
|
|
179
|
+
def join(self, channel: str, key: str = "") -> None:
|
|
180
|
+
self.ev.join(self._label.get(channel, channel), self._me)
|
|
181
|
+
|
|
182
|
+
def part(self, channel: str, reason: str = "") -> None:
|
|
183
|
+
self.ev.part(channel, self._me, "")
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def current_nick(self) -> str:
|
|
187
|
+
return self._me or self.p.nick
|
|
188
|
+
|
|
189
|
+
def is_dm(self, name: str) -> bool:
|
|
190
|
+
return name.startswith("@")
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Cliente HTTP/JSON mínimo (urllib) com tratamento de 429 e TLS configurável."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from src.chat.util import ssl_context
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class HTTPFailure(ConnectionError):
|
|
17
|
+
def __init__(self, status: int, message: str) -> None:
|
|
18
|
+
super().__init__(f"HTTP {status}: {message}" if status > 0 else message)
|
|
19
|
+
self.status = status
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def request_json(
|
|
23
|
+
method: str,
|
|
24
|
+
url: str,
|
|
25
|
+
*,
|
|
26
|
+
headers: dict[str, str] | None = None,
|
|
27
|
+
body: Any = None,
|
|
28
|
+
params: dict[str, Any] | None = None,
|
|
29
|
+
timeout: float = 15,
|
|
30
|
+
verify: bool = True,
|
|
31
|
+
retry_429: bool = True,
|
|
32
|
+
with_headers: bool = False,
|
|
33
|
+
) -> tuple:
|
|
34
|
+
"""Faz a requisição; devolve ``(status, json)`` (json vazio se a resposta não for JSON).
|
|
35
|
+
|
|
36
|
+
Erros de rede viram :class:`HTTPFailure` com status ``-1``; respostas HTTP de erro
|
|
37
|
+
(4xx/5xx) são *devolvidas* (não levantam) para o chamador decidir.
|
|
38
|
+
"""
|
|
39
|
+
if params:
|
|
40
|
+
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
|
41
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
42
|
+
hdrs = {"Accept": "application/json", "User-Agent": "Codis-Chat"}
|
|
43
|
+
if data is not None:
|
|
44
|
+
hdrs["Content-Type"] = "application/json"
|
|
45
|
+
hdrs.update(headers or {})
|
|
46
|
+
ctx = ssl_context(verify) if url.startswith("https") else None
|
|
47
|
+
for attempt in (0, 1):
|
|
48
|
+
req = urllib.request.Request(url, data=data, method=method, headers=hdrs)
|
|
49
|
+
try:
|
|
50
|
+
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
|
|
51
|
+
raw, status, rh = resp.read(), resp.status, dict(resp.headers)
|
|
52
|
+
except urllib.error.HTTPError as exc:
|
|
53
|
+
raw, status, rh = exc.read(), exc.code, dict(exc.headers)
|
|
54
|
+
if status == 429 and retry_429 and attempt == 0:
|
|
55
|
+
wait = _retry_after(exc.headers.get("Retry-After"), raw)
|
|
56
|
+
time.sleep(min(wait, 30))
|
|
57
|
+
continue
|
|
58
|
+
except (urllib.error.URLError, OSError, TimeoutError) as exc:
|
|
59
|
+
reason = getattr(exc, "reason", exc)
|
|
60
|
+
raise HTTPFailure(-1, str(reason)) from exc
|
|
61
|
+
try:
|
|
62
|
+
obj = json.loads(raw) if raw else {}
|
|
63
|
+
except ValueError:
|
|
64
|
+
obj = {}
|
|
65
|
+
return (status, obj, rh) if with_headers else (status, obj)
|
|
66
|
+
return (429, {}, {}) if with_headers else (429, {})
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _retry_after(header: str | None, raw: bytes) -> float:
|
|
70
|
+
for cand in (header,):
|
|
71
|
+
if cand:
|
|
72
|
+
with contextlib.suppress(ValueError):
|
|
73
|
+
return float(cand)
|
|
74
|
+
try:
|
|
75
|
+
d = json.loads(raw)
|
|
76
|
+
return float(d.get("retry_after") or d.get("parameters", {}).get("retry_after") or 1)
|
|
77
|
+
except (ValueError, AttributeError, TypeError):
|
|
78
|
+
return 1.0
|