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,1398 @@
1
+ """Codis - adaptadores de acesso remoto (SSH/SFTP, FTP/FTPS, HTTP, WebDAV).
2
+
3
+ Camada sem Tkinter usada pelo Navegador Remoto. Cada protocolo implementa
4
+ :class:`RemoteAdapter` com a mesma interface, o que permite testar tudo contra
5
+ servidores reais (sshd, pyftpdlib, wsgidav) sem abrir janela.
6
+
7
+ Convenções:
8
+ * caminhos remotos são sempre POSIX (``/``), mesmo quando o Codis roda no
9
+ Windows - por isso usamos ``posixpath`` e nunca ``pathlib.Path`` para eles;
10
+ * operações devolvem ``(ok, mensagem)``; ``listdir`` devolve
11
+ ``(entradas, erro)`` e o erro NUNCA é engolido (pasta vazia e pasta ilegível
12
+ são coisas diferentes);
13
+ * os adaptadores são thread-safe: o painel os usa a partir de threads.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import contextlib
20
+ import ftplib
21
+ import html.parser
22
+ import logging
23
+ import os
24
+ import posixpath
25
+ import re
26
+ import shlex
27
+ import shutil
28
+ import socket
29
+ import ssl
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ import threading
34
+ import time
35
+ import urllib.error
36
+ import urllib.parse
37
+ import urllib.request
38
+ import xml.etree.ElementTree as ET
39
+ from collections.abc import Callable
40
+ from dataclasses import dataclass, field
41
+ from enum import StrEnum
42
+ from pathlib import Path
43
+ from uuid import uuid4
44
+
45
+ from src import proc_registry
46
+ from src.constants import CONFIG_DIR
47
+ from src.i18n import _t
48
+ from src.textfmt import format_size
49
+ from src.ui._persistence_utils import load_dataclass_list, save_dataclass_list
50
+
51
+ logger = logging.getLogger("Codis.RemoteAdapters")
52
+
53
+ try:
54
+ from defusedxml import ElementTree as _SafeET # type: ignore[import-untyped]
55
+
56
+ _XML_FROMSTRING = _SafeET.fromstring
57
+ except ImportError: # pragma: no cover
58
+ _XML_FROMSTRING = ET.fromstring
59
+
60
+ ProgressCb = Callable[[int, "int | None"], None]
61
+ Result = tuple[bool, str]
62
+
63
+ PROFILES_FILE = CONFIG_DIR / "remote_browser_profiles.json"
64
+ MAX_LISTING_BYTES = 8 * 1024 * 1024
65
+ _LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")
66
+ _NULL_FILE = "NUL" if sys.platform == "win32" else "/dev/null"
67
+
68
+ _TEXT_EXTS: frozenset[str] = frozenset(
69
+ [".py", ".pyw", ".pyi", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".html", ".htm", ".vue", ".svelte", ".css", ".scss", ".less", ".json", ".jsonc", ".json5", ".md", ".mdx", ".markdown", ".yml", ".yaml", ".xml", ".svg", ".xhtml", ".sql", ".pgsql", ".toml", ".ini", ".cfg", ".env", ".conf", ".txt", ".log", ".sh", ".bash", ".zsh", ".fish", ".ksh", ".csh", ".tcsh", ".ps1", ".psm1", ".bat", ".cmd", ".rs", ".go", ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".java", ".swift", ".kt", ".rb", ".erb", ".php", ".pl", ".pm", ".r", ".jl", ".hs", ".lua", ".ex", ".exs", ".erl", ".dart", ".scala", ".vb", ".cs", ".fs", ".asm", ".s", ".tf", ".proto", ".graphql", ".mk", ".gradle", ".properties", ".lock", ".service", ".rst", ".tex", ".gitignore", ".gitattributes", ".editorconfig", ".dockerignore", ".npmrc", ".htaccess"]
70
+ )
71
+ _TEXT_NAMES: frozenset[str] = frozenset(
72
+ ["makefile", "dockerfile", "gemfile", "rakefile", "procfile", "vagrantfile", "jenkinsfile", "readme", "license", "licence", "changelog", "authors", "contributors", "notice", "codeowners", "cmakelists.txt", "requirements.txt", ".bashrc", ".zshrc", ".profile", ".bash_profile", ".vimrc", ".gitconfig", ".env"]
73
+ )
74
+ _IMAGE_EXTS: frozenset[str] = frozenset(
75
+ {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".ico", ".tiff"}
76
+ )
77
+ _BINARY_EXTS: frozenset[str] = frozenset(
78
+ [".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".class", ".jar", ".pyc", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".mp3", ".mp4", ".mkv", ".avi", ".mov", ".wav", ".flac", ".ogg", ".iso", ".img", ".dmg", ".woff", ".woff2", ".ttf", ".otf", ".sqlite", ".db"]
79
+ )
80
+ _SPECIAL_EXTS = {".ipynb": "notebook", ".csv": "csv", ".tsv": "csv"}
81
+
82
+
83
+ def classify(name: str) -> str:
84
+ """Classifica pelo nome: ``text``, ``image``, ``notebook``, ``csv``,
85
+ ``binary`` (conhecido) ou ``unknown`` (decidir após inspecionar o conteúdo).
86
+ """
87
+ base = posixpath.basename(name).lower()
88
+ suffix = posixpath.splitext(base)[1]
89
+ if base in _TEXT_NAMES or base in _TEXT_EXTS or suffix in _TEXT_EXTS:
90
+ return "text"
91
+ if suffix in _IMAGE_EXTS:
92
+ return "image"
93
+ if suffix in _SPECIAL_EXTS:
94
+ return _SPECIAL_EXTS[suffix]
95
+ if suffix in _BINARY_EXTS:
96
+ return "binary"
97
+ return "unknown"
98
+
99
+
100
+ def looks_binary(path: Path, sample: int = 8192) -> bool:
101
+ """``True`` se o início do arquivo contém byte nulo (heurística clássica)."""
102
+ try:
103
+ with open(path, "rb") as fh:
104
+ return b"\x00" in fh.read(sample)
105
+ except OSError:
106
+ return True
107
+
108
+
109
+ def file_icon(name: str, is_dir: bool = False) -> str:
110
+ """Ícone (emoji) para a lista de arquivos."""
111
+ if is_dir:
112
+ return "📁"
113
+ suffix = posixpath.splitext(name.lower())[1]
114
+ table = {
115
+ "🖼": _IMAGE_EXTS,
116
+ "🐍": {".py", ".pyw", ".pyi"},
117
+ "📜": {".js", ".mjs", ".ts", ".jsx", ".tsx"},
118
+ "⚙": {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env"},
119
+ "📝": {".md", ".mdx", ".txt", ".rst"},
120
+ "🌐": {".html", ".htm", ".vue", ".css", ".scss"},
121
+ "🗄": {".sql", ".db", ".sqlite"},
122
+ "📊": {".csv", ".tsv", ".xlsx", ".xls"},
123
+ "📓": {".ipynb"},
124
+ "📦": {".zip", ".tar", ".gz", ".tgz", ".7z", ".bz2", ".xz", ".rar"},
125
+ "▶": {".sh", ".bash", ".zsh", ".bat", ".cmd", ".ps1", ".exe"},
126
+ }
127
+ for icon, exts in table.items():
128
+ if suffix in exts:
129
+ return icon
130
+ return "📄"
131
+
132
+
133
+ def parse_human_size(text: str) -> int | None:
134
+ """Converte ``1.2K``/``340``/``-`` em bytes (``None`` se não for tamanho)."""
135
+ text = text.strip()
136
+ m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([KMGT]?)i?B?", text, re.IGNORECASE)
137
+ if not m:
138
+ return None
139
+ mult = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4}
140
+ return int(float(m.group(1)) * mult[m.group(2).upper()])
141
+
142
+
143
+ class Protocol(StrEnum):
144
+ SSH = "ssh"
145
+ SFTP = "sftp"
146
+ FTP = "ftp"
147
+ FTPS = "ftps"
148
+ HTTP = "http"
149
+ HTTPS = "https"
150
+ WEBDAV = "webdav"
151
+ WEBDAVS = "webdavs"
152
+
153
+ @classmethod
154
+ def _missing_(cls, value: object) -> Protocol:
155
+ return cls.SSH
156
+
157
+
158
+ PROTO_DEFAULTS: dict[str, int] = {
159
+ "ssh": 22,
160
+ "sftp": 22,
161
+ "ftp": 21,
162
+ "ftps": 21,
163
+ "http": 80,
164
+ "https": 443,
165
+ "webdav": 80,
166
+ "webdavs": 443,
167
+ }
168
+
169
+ _UNSAFE_TARGET_CHARS = re.compile(r"[\s\x00-\x1f\x7f]")
170
+
171
+
172
+ @dataclass
173
+ class RemoteProfile:
174
+ name: str
175
+ protocol: str = "ssh"
176
+ host: str = ""
177
+ port: int = 22
178
+ user: str = ""
179
+ password: str = ""
180
+ key_path: str = ""
181
+ remote_root: str = "~"
182
+ passive_ftp: bool = True
183
+ jump_host: str = ""
184
+ timeout: int = 15
185
+ tags: list[str] = field(default_factory=list)
186
+ verify_tls: bool = True
187
+ uid: str = field(default_factory=lambda: uuid4().hex[:10])
188
+
189
+ def __post_init__(self) -> None:
190
+ """Recusa host/usuário/jump que o ssh interpretaria como opção.
191
+
192
+ Perfis podem vir de arquivos importados; ``-oProxyCommand=...`` viraria
193
+ execução de comando ao ser passado ao ssh.
194
+
195
+ Raises:
196
+ ValueError: se algum campo for inseguro.
197
+ """
198
+ for label, value in (
199
+ ("host", self.host),
200
+ ("user", self.user),
201
+ ("jump_host", self.jump_host),
202
+ ):
203
+ if value.startswith("-") or _UNSAFE_TARGET_CHARS.search(value):
204
+ raise ValueError(f"Valor inválido em '{label}': {value!r}")
205
+
206
+ @property
207
+ def proto(self) -> Protocol:
208
+ return Protocol(self.protocol)
209
+
210
+ def decoded_password(self) -> str:
211
+ if not self.password:
212
+ return ""
213
+ try:
214
+ return base64.b64decode(self.password.encode(), validate=True).decode()
215
+ except (ValueError, UnicodeDecodeError):
216
+ return self.password
217
+
218
+ @staticmethod
219
+ def encode_password(raw: str) -> str:
220
+ return base64.b64encode(raw.encode()).decode() if raw else ""
221
+
222
+
223
+ def load_profiles() -> list[RemoteProfile]:
224
+ return load_dataclass_list(PROFILES_FILE, RemoteProfile, logger=logger)
225
+
226
+
227
+ def save_profiles(profiles: list[RemoteProfile]) -> None:
228
+ save_dataclass_list(PROFILES_FILE, profiles, chmod_600=True)
229
+
230
+
231
+ _URL_SCHEMES = {"dav": "webdav", "davs": "webdavs", "sftp": "sftp", "ssh": "ssh"}
232
+
233
+
234
+ def parse_remote_url(url: str) -> dict[str, object] | None:
235
+ """Decompõe ``sftp://user:senha@host:22/caminho`` em campos de perfil.
236
+
237
+ Retorna ``None`` se não for uma URL de protocolo suportado.
238
+ """
239
+ parsed = urllib.parse.urlparse(url.strip())
240
+ scheme = _URL_SCHEMES.get(parsed.scheme.lower(), parsed.scheme.lower())
241
+ if scheme not in PROTO_DEFAULTS or not parsed.hostname:
242
+ return None
243
+ path = urllib.parse.unquote(parsed.path) or "~"
244
+ if scheme in ("ssh", "sftp") and path.startswith("/~"):
245
+ path = path[1:]
246
+ return {
247
+ "protocol": scheme,
248
+ "host": parsed.hostname,
249
+ "port": parsed.port or PROTO_DEFAULTS[scheme],
250
+ "user": urllib.parse.unquote(parsed.username or ""),
251
+ "password": urllib.parse.unquote(parsed.password or ""),
252
+ "remote_root": path,
253
+ }
254
+
255
+
256
+ @dataclass
257
+ class RemoteEntry:
258
+ name: str
259
+ is_dir: bool
260
+ size: int | None = None
261
+ modified: str = ""
262
+ is_link: bool = False
263
+ link_target: str = ""
264
+ broken: bool = False
265
+ mode: str = ""
266
+
267
+ @property
268
+ def size_text(self) -> str:
269
+ return "" if self.is_dir else format_size(self.size)
270
+
271
+
272
+ def join_path(base: str, name: str) -> str:
273
+ """Junta caminho remoto POSIX sem duplicar barras."""
274
+ return posixpath.join(base or "/", name)
275
+
276
+
277
+ def parent_path(path: str) -> str:
278
+ """Pai de um caminho remoto POSIX (``/`` é o próprio pai)."""
279
+ if path in ("", "/", "~"):
280
+ return path or "/"
281
+ return posixpath.dirname(path.rstrip("/")) or "/"
282
+
283
+
284
+ def _temp_part(local: Path) -> Path:
285
+ return local.with_name(local.name + ".codis-part")
286
+
287
+
288
+ class RemoteAdapter:
289
+ """Contrato comum a todos os protocolos."""
290
+
291
+ read_only = False
292
+
293
+ def __init__(self, profile: RemoteProfile) -> None:
294
+ self._p = profile
295
+ self.home = "/"
296
+
297
+ def connect(self) -> Result:
298
+ raise NotImplementedError
299
+
300
+ def listdir(self, path: str) -> tuple[list[RemoteEntry], str]:
301
+ raise NotImplementedError
302
+
303
+ def download(
304
+ self, remote: str, local: Path, progress: ProgressCb | None = None
305
+ ) -> Result:
306
+ raise NotImplementedError
307
+
308
+ def upload(
309
+ self, local: Path, remote: str, progress: ProgressCb | None = None
310
+ ) -> Result:
311
+ raise NotImplementedError
312
+
313
+ def mkdir(self, path: str) -> Result:
314
+ return False, _t("rbrowser.op_unsupported", "Operação não suportada por este protocolo.")
315
+
316
+ def remove(self, path: str, is_dir: bool = False) -> Result:
317
+ return False, _t("rbrowser.op_unsupported", "Operação não suportada por este protocolo.")
318
+
319
+ def rename(self, src: str, dst: str) -> Result:
320
+ return False, _t("rbrowser.op_unsupported", "Operação não suportada por este protocolo.")
321
+
322
+ def stat(self, path: str) -> RemoteEntry | None:
323
+ """Metadados de ``path`` (via listagem do diretório pai)."""
324
+ entries, err = self.listdir(parent_path(path))
325
+ if err:
326
+ return None
327
+ name = posixpath.basename(path.rstrip("/"))
328
+ return next((e for e in entries if e.name == name), None)
329
+
330
+ def close(self) -> None:
331
+ return None
332
+
333
+
334
+ def _make_ssl_context(verify: bool) -> ssl.SSLContext:
335
+ ctx = ssl.create_default_context()
336
+ if not verify:
337
+ ctx.check_hostname = False
338
+ ctx.verify_mode = ssl.CERT_NONE
339
+ return ctx
340
+
341
+
342
+ _LS_RE = re.compile(
343
+ r"^(?P<mode>[-dlbcpsDC?][rwxsStTl-]{9}[+.@]?)\s+\d+\s+\S+\s+\S+\s+"
344
+ r"(?P<size>\d+(?:,\s*\d+)?)\s+"
345
+ r"(?P<date>\d{4}-\d{2}-\d{2}(?:\s+\d{2}:\d{2}(?::\d{2}(?:\.\d+)?(?:\s+[+-]\d{4})?)?)?"
346
+ r"|[A-Za-z]{3}\s+\d{1,2}\s+(?:\d{2}:\d{2}|\d{4}))\s+"
347
+ r"(?P<name>.+)$"
348
+ )
349
+
350
+
351
+ def parse_ls_output(text: str) -> list[RemoteEntry]:
352
+ """Interpreta a saída de ``ls -la`` (GNU long-iso, GNU padrão, BSD, BusyBox).
353
+
354
+ Independe do estilo de data: ancora no tamanho e reconhece a data pelos
355
+ dois formatos possíveis, de modo que o nome (com espaços) é o resto da linha.
356
+ """
357
+ entries: list[RemoteEntry] = []
358
+ for line in text.splitlines():
359
+ m = _LS_RE.match(line.rstrip("\r"))
360
+ if not m:
361
+ continue
362
+ name = m["name"]
363
+ mode = m["mode"]
364
+ is_link = mode[0] == "l"
365
+ target = ""
366
+ if is_link and " -> " in name:
367
+ name, _, target = name.partition(" -> ")
368
+ if name in (".", ".."):
369
+ continue
370
+ size_txt = m["size"]
371
+ size = None if "," in size_txt else int(size_txt)
372
+ entries.append(
373
+ RemoteEntry(
374
+ name=name,
375
+ is_dir=mode[0] == "d",
376
+ size=size,
377
+ modified=re.sub(r"\s+", " ", m["date"]),
378
+ is_link=is_link,
379
+ link_target=target,
380
+ mode=mode,
381
+ )
382
+ )
383
+ return entries
384
+
385
+
386
+ def _find_binary(name: str) -> str | None:
387
+ found = shutil.which(name)
388
+ if found or sys.platform != "win32":
389
+ return found
390
+ for base in (
391
+ Path(r"C:\Windows\System32\OpenSSH"),
392
+ Path(r"C:\Program Files\Git\usr\bin"),
393
+ Path(r"C:\Program Files\OpenSSH"),
394
+ ):
395
+ candidate = base / f"{name}.exe"
396
+ if candidate.exists():
397
+ return str(candidate)
398
+ return None
399
+
400
+
401
+ class SSHAdapter(RemoteAdapter):
402
+ """SSH/SFTP usando os binários ``ssh``/``sftp``/``scp`` do sistema.
403
+
404
+ * Autenticação: chave > senha (``sshpass`` ou ``SSH_ASKPASS``, funcionando
405
+ também no Windows) > ssh-agent. A senha NUNCA vai em argumento de processo.
406
+ * Em sistemas POSIX reutiliza uma conexão (ControlMaster): uma única
407
+ autenticação para listar, baixar e enviar.
408
+ """
409
+
410
+ def __init__(self, profile: RemoteProfile) -> None:
411
+ super().__init__(profile)
412
+ self._ssh = _find_binary("ssh")
413
+ self._sftp = _find_binary("sftp")
414
+ self._scp = _find_binary("scp")
415
+ self._sshpass = None if sys.platform == "win32" else shutil.which("sshpass")
416
+ self._mux = sys.platform != "win32" and not os.environ.get("CODIS_SSH_NOMUX")
417
+ self._ctl_dir: str | None = None
418
+ self._askpass_dir: str | None = None
419
+ self._lock = threading.Lock()
420
+ self.home = "~"
421
+
422
+ def _password(self) -> str:
423
+ return self._p.decoded_password()
424
+
425
+ def _auth(self) -> str:
426
+ p = self._p
427
+ if p.key_path and Path(p.key_path).expanduser().exists():
428
+ return "key"
429
+ if self._password():
430
+ return "sshpass" if self._sshpass else "askpass"
431
+ if os.environ.get("SSH_AUTH_SOCK") or os.environ.get("SSH_AGENT_PID"):
432
+ return "agent"
433
+ return "none"
434
+
435
+ def _uses_askpass(self) -> bool:
436
+ auth = self._auth()
437
+ return auth == "askpass" or (auth == "key" and bool(self._password()))
438
+
439
+ def _ensure_askpass(self) -> str:
440
+ with self._lock:
441
+ if self._askpass_dir is None:
442
+ self._askpass_dir = tempfile.mkdtemp(prefix="codis-ap-")
443
+ if sys.platform == "win32":
444
+ script = Path(self._askpass_dir) / "askpass.cmd"
445
+ script.write_text(
446
+ "@powershell -NoProfile -NonInteractive -Command "
447
+ '"[Console]::Out.Write($env:CODIS_SSH_PW)"\r\n',
448
+ encoding="ascii",
449
+ )
450
+ else:
451
+ script = Path(self._askpass_dir) / "askpass.sh"
452
+ script.write_text('#!/bin/sh\nprintf \'%s\\n\' "$CODIS_SSH_PW"\n')
453
+ script.chmod(0o700)
454
+ return str(next(Path(self._askpass_dir).iterdir()))
455
+
456
+ def _control_path(self) -> str | None:
457
+ if not self._mux:
458
+ return None
459
+ with self._lock:
460
+ if self._ctl_dir is None:
461
+ self._ctl_dir = tempfile.mkdtemp(prefix="cx")
462
+ return os.path.join(self._ctl_dir, "%C")
463
+
464
+ def _target(self) -> str:
465
+ p = self._p
466
+ return f"{p.user}@{p.host}" if p.user else p.host
467
+
468
+ def _common_opts(self, *, mux: bool = True) -> list[str]:
469
+ p, auth = self._p, self._auth()
470
+ opts = [
471
+ "-o", f"ConnectTimeout={p.timeout}",
472
+ "-o", "ServerAliveInterval=30",
473
+ "-o", "ServerAliveCountMax=3",
474
+ "-o", "LogLevel=ERROR",
475
+ ] # fmt: skip
476
+ is_local = p.host.lower() in _LOCAL_HOSTS
477
+ opts += ["-o", f"StrictHostKeyChecking={'no' if is_local else 'accept-new'}"]
478
+ if is_local:
479
+ opts += ["-o", f"UserKnownHostsFile={_NULL_FILE}"]
480
+ if auth == "key":
481
+ opts += [
482
+ "-i", str(Path(p.key_path).expanduser()),
483
+ "-o", "IdentitiesOnly=yes",
484
+ "-o", "PreferredAuthentications=publickey",
485
+ ] # fmt: skip
486
+ if not self._password():
487
+ opts += ["-o", "BatchMode=yes"]
488
+ elif auth in ("sshpass", "askpass"):
489
+ opts += [
490
+ "-o", "IdentitiesOnly=yes",
491
+ "-o", f"IdentityFile={_NULL_FILE}",
492
+ "-o", "PreferredAuthentications=password,keyboard-interactive",
493
+ "-o", "NumberOfPasswordPrompts=1",
494
+ ] # fmt: skip
495
+ else:
496
+ opts += ["-o", "BatchMode=yes"]
497
+ if auth == "agent":
498
+ opts += ["-o", "PreferredAuthentications=publickey"]
499
+ if p.jump_host:
500
+ opts += ["-o", f"ProxyJump={p.jump_host}"]
501
+ ctl = self._control_path() if mux else None
502
+ if ctl:
503
+ opts += [
504
+ "-o", "ControlMaster=auto",
505
+ "-o", f"ControlPath={ctl}",
506
+ "-o", "ControlPersist=120",
507
+ ] # fmt: skip
508
+ return opts
509
+
510
+ def _argv(self, tool: str, extra: list[str] | None = None, *, mux: bool = True) -> list[str]:
511
+ binary = {"ssh": self._ssh, "sftp": self._sftp, "scp": self._scp}[tool]
512
+ port_flag = "-p" if tool == "ssh" else "-P"
513
+ argv = [binary or tool]
514
+ if self._p.port != 22:
515
+ argv += [port_flag, str(self._p.port)]
516
+ argv += self._common_opts(mux=mux) + (extra or [])
517
+ return argv
518
+
519
+ def _wrap(self, argv: list[str]) -> list[str]:
520
+ if self._auth() == "sshpass" and self._sshpass:
521
+ return [self._sshpass, "-e", *argv]
522
+ return argv
523
+
524
+ def _env(self) -> dict[str, str]:
525
+ env = os.environ.copy()
526
+ if self._auth() == "sshpass":
527
+ env["SSHPASS"] = self._password()
528
+ elif self._uses_askpass():
529
+ env["SSH_ASKPASS"] = self._ensure_askpass()
530
+ env["SSH_ASKPASS_REQUIRE"] = "force"
531
+ env["CODIS_SSH_PW"] = self._password()
532
+ env.setdefault("DISPLAY", ":0")
533
+ return env
534
+
535
+ def _popen_kwargs(self) -> dict[str, object]:
536
+ kw: dict[str, object] = {"env": self._env()}
537
+ if self._uses_askpass() and sys.platform != "win32":
538
+ kw["start_new_session"] = True
539
+ return kw
540
+
541
+ def _exec(
542
+ self, argv: list[str], *, timeout: float | None, stdin_text: str | None = None
543
+ ) -> tuple[int, str, str]:
544
+ try:
545
+ r = subprocess.run(
546
+ self._wrap(argv),
547
+ capture_output=True,
548
+ text=True,
549
+ input=stdin_text,
550
+ stdin=None if stdin_text is not None else subprocess.DEVNULL,
551
+ timeout=timeout,
552
+ check=False,
553
+ **self._popen_kwargs(),
554
+ )
555
+ return r.returncode, r.stdout, r.stderr
556
+ except subprocess.TimeoutExpired:
557
+ return -1, "", _t("rbrowser.timeout", "Timeout na conexão.")
558
+ except (OSError, subprocess.SubprocessError) as exc:
559
+ return -1, "", str(exc)
560
+
561
+ def _run(self, remote_cmd: str, timeout: float = 30) -> tuple[int, str, str]:
562
+ if not self._ssh:
563
+ return -1, "", self._no_ssh_msg()
564
+ argv = self._argv("ssh") + [self._target(), remote_cmd]
565
+ return self._exec(argv, timeout=timeout)
566
+
567
+ @staticmethod
568
+ def _no_ssh_msg() -> str:
569
+ return _t(
570
+ "rbrowser.no_ssh",
571
+ "Binário 'ssh' não encontrado. No Windows: Configurações → Recursos "
572
+ "opcionais → Cliente OpenSSH.",
573
+ )
574
+
575
+ @staticmethod
576
+ def _quote_remote_path(path: str) -> str:
577
+ """Escapa um caminho para shell POSIX preservando a expansão de ``~``."""
578
+ if not path:
579
+ return ""
580
+ if path == "~":
581
+ return "~"
582
+ if path.startswith("~/"):
583
+ return "~/" + shlex.quote(path[2:])
584
+ return shlex.quote(path)
585
+
586
+ def _abs(self, path: str) -> str:
587
+ if not path or path == "~":
588
+ return self.home
589
+ if path.startswith("~/") and self.home != "~":
590
+ return posixpath.join(self.home, path[2:])
591
+ if path.startswith("/"):
592
+ return posixpath.normpath(path) if path != "/" else "/"
593
+ return posixpath.join(self.home, path)
594
+
595
+ def connect(self) -> Result:
596
+ if not self._ssh:
597
+ return False, self._no_ssh_msg()
598
+ root = self._p.remote_root or "~"
599
+ cmd = (
600
+ "printf '__codis_ok__\\n'; "
601
+ f"cd {self._quote_remote_path(root)} 2>/dev/null && pwd || pwd"
602
+ )
603
+ rc, out, err = self._run(cmd, timeout=self._p.timeout + 10)
604
+ lines = [ln.strip() for ln in out.splitlines()]
605
+ if rc == 0 and "__codis_ok__" in lines:
606
+ rest = lines[lines.index("__codis_ok__") + 1 :]
607
+ if rest and rest[0].startswith("/"):
608
+ self.home = rest[0]
609
+ return True, _t("rbrowser.connected", "Conectado.")
610
+ return False, self.classify_error(err or out)
611
+
612
+ @staticmethod
613
+ def classify_error(err: str) -> str:
614
+ e = err.lower()
615
+ rules = (
616
+ (("host key verification failed", "remote host identification has changed"),
617
+ "rbrowser.err_hostkey",
618
+ "A chave do servidor mudou ou é desconhecida. Remova a entrada antiga de known_hosts."),
619
+ (("connection refused",), "rbrowser.err_refused", "Conexão recusada - o servidor SSH está em execução?"),
620
+ (("permission denied", "authentication failed", "too many authentication"),
621
+ "rbrowser.err_perm", "Permissão negada - verifique usuário, senha ou chave."),
622
+ (("no route to host", "network is unreachable", "unreachable"),
623
+ "rbrowser.err_route", "Host inacessível."),
624
+ (("timed out", "timeout"), "rbrowser.timeout", "Timeout na conexão."),
625
+ (("could not resolve", "name or service not known", "nodename nor servname"),
626
+ "rbrowser.err_dns", "Host não encontrado."),
627
+ (("no such file or directory", "not found", "no such file"),
628
+ "rbrowser.err_nofile", "Arquivo ou pasta não encontrado."),
629
+ (("not a directory",), "rbrowser.err_notdir", "O caminho não é uma pasta."),
630
+ ) # fmt: skip
631
+ for needles, key, default in rules:
632
+ if any(n in e for n in needles):
633
+ return _t(key, default)
634
+ return err.strip() or _t("rbrowser.err_generic", "Falha na conexão.")
635
+
636
+ def listdir(self, path: str) -> tuple[list[RemoteEntry], str]:
637
+ target = self._quote_remote_path(self._abs(path))
638
+ out, err, rc = "", "", 0
639
+ for opts in ("ls -la --time-style=long-iso", "ls -la"):
640
+ rc, out, err = self._run(f"LC_ALL=C {opts} {target}", timeout=30)
641
+ if rc == 0 or not re.search(r"unrecognized option|illegal option|invalid option", err):
642
+ break
643
+ entries = parse_ls_output(out)
644
+ if rc != 0 and not entries:
645
+ return [], self.classify_error(err) if err else f"rc={rc}"
646
+ self._resolve_links(self._abs(path), entries)
647
+ return entries, ""
648
+
649
+ def _resolve_links(self, directory: str, entries: list[RemoteEntry]) -> None:
650
+ """Descobre, com uma única chamada, quais symlinks apontam para pastas."""
651
+ links = [e for e in entries if e.is_link]
652
+ if not links:
653
+ return
654
+ names = " ".join(shlex.quote(e.name) for e in links)
655
+ script = (
656
+ f"cd {shlex.quote(directory)} 2>/dev/null && for n in {names}; do "
657
+ 'if [ -d "$n" ]; then printf "D\\t%s\\n" "$n"; '
658
+ 'elif [ ! -e "$n" ]; then printf "B\\t%s\\n" "$n"; fi; done'
659
+ )
660
+ rc, out, _ = self._run(script, timeout=20)
661
+ if rc != 0:
662
+ return
663
+ kinds = {}
664
+ for line in out.splitlines():
665
+ kind, _, name = line.partition("\t")
666
+ kinds[name] = kind
667
+ for e in links:
668
+ e.is_dir = kinds.get(e.name) == "D"
669
+ e.broken = kinds.get(e.name) == "B"
670
+
671
+ @staticmethod
672
+ def _sftp_quote(value: str) -> str:
673
+ """Escapa um argumento para o lote do ``sftp`` (rejeita quebra de linha,
674
+ que injetaria um segundo comando)."""
675
+ if "\n" in value or "\r" in value:
676
+ raise ValueError("invalid path: embedded newline")
677
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
678
+
679
+ _SFTP_ERRORS = re.compile(
680
+ r"no such file|not found|permission denied|couldn't|failure|"
681
+ r"remote open|local open|connection closed|not a directory|read-only",
682
+ re.IGNORECASE,
683
+ )
684
+
685
+ def _ensure_master(self) -> None:
686
+ """Garante a conexão mestre (reautentica se o ControlPersist expirou)."""
687
+ if self._mux and self._ssh:
688
+ self._run("true", timeout=self._p.timeout + 10)
689
+
690
+ def _sftp_batch(self, commands: str) -> Result:
691
+ if not self._sftp:
692
+ return False, _t("rbrowser.no_sftp", "Binário 'sftp' não encontrado.")
693
+ use_batch = self._mux
694
+ if use_batch:
695
+ self._ensure_master()
696
+ argv = self._argv("sftp", ["-b", "-"]) + [self._target()]
697
+ stdin_text = commands
698
+ else:
699
+ argv = self._argv("sftp") + [self._target()]
700
+ stdin_text = commands + "bye\n"
701
+ rc, out, err = self._exec(argv, timeout=3600, stdin_text=stdin_text)
702
+ failed = rc != 0 or (not use_batch and bool(self._SFTP_ERRORS.search(err + out)))
703
+ if failed:
704
+ raw = "\n".join(
705
+ ln for ln in (err or out).splitlines() if ln.strip() and not ln.startswith("Connected to")
706
+ )
707
+ msg = self.classify_error(raw)
708
+ logger.warning("SFTP falhou (rc=%d): %s", rc, raw)
709
+ return False, msg
710
+ return True, ""
711
+
712
+ def download(self, remote: str, local: Path, progress: ProgressCb | None = None) -> Result:
713
+ part = _temp_part(local)
714
+ part.unlink(missing_ok=True)
715
+ try:
716
+ cmd = (
717
+ f"get {self._sftp_quote(self._abs(remote))} "
718
+ f"{self._sftp_quote(part.as_posix())}\n"
719
+ )
720
+ except ValueError as exc:
721
+ return False, str(exc)
722
+ ok, msg = self._sftp_batch(cmd) if self._sftp else self._scp_copy(
723
+ f"{self._target()}:{shlex.quote(self._abs(remote))}", str(part)
724
+ )
725
+ if ok and part.exists():
726
+ os.replace(part, local)
727
+ return True, ""
728
+ part.unlink(missing_ok=True)
729
+ return False, msg or _t("rbrowser.dl_fail_msg", "Não foi possível baixar o arquivo.")
730
+
731
+ def upload(self, local: Path, remote: str, progress: ProgressCb | None = None) -> Result:
732
+ try:
733
+ cmd = (
734
+ f"put {self._sftp_quote(local.as_posix())} "
735
+ f"{self._sftp_quote(self._abs(remote))}\n"
736
+ )
737
+ except ValueError as exc:
738
+ return False, str(exc)
739
+ if self._sftp:
740
+ return self._sftp_batch(cmd)
741
+ return self._scp_copy(str(local), f"{self._target()}:{shlex.quote(self._abs(remote))}")
742
+
743
+ def _scp_copy(self, src: str, dst: str) -> Result:
744
+ if not self._scp:
745
+ return False, _t("rbrowser.no_sftp", "Binário 'sftp' não encontrado.")
746
+ argv = self._argv("scp") + ["--", src, dst]
747
+ rc, _out, err = self._exec(argv, timeout=3600)
748
+ return (True, "") if rc == 0 else (False, self.classify_error(err))
749
+
750
+ def _simple(self, cmd: str) -> Result:
751
+ rc, _out, err = self._run(cmd, timeout=60)
752
+ return (True, "") if rc == 0 else (False, self.classify_error(err))
753
+
754
+ def mkdir(self, path: str) -> Result:
755
+ return self._simple(f"mkdir -- {shlex.quote(self._abs(path))}")
756
+
757
+ def remove(self, path: str, is_dir: bool = False) -> Result:
758
+ flag = "-rf" if is_dir else "-f"
759
+ return self._simple(f"rm {flag} -- {shlex.quote(self._abs(path))}")
760
+
761
+ def rename(self, src: str, dst: str) -> Result:
762
+ return self._simple(f"mv -n -- {shlex.quote(self._abs(src))} {shlex.quote(self._abs(dst))}")
763
+
764
+ def start_debug_tunnel(
765
+ self, remote_port: int = 5678, local_port: int = 5678
766
+ ) -> subprocess.Popen | None:
767
+ """Abre ``ssh -N -L`` para depuração remota (processo independente)."""
768
+ if not self._ssh:
769
+ return None
770
+ extra = [
771
+ "-N", "-L", f"{local_port}:localhost:{remote_port}",
772
+ "-o", "ExitOnForwardFailure=yes",
773
+ "-o", "ControlMaster=no", "-o", "ControlPath=none",
774
+ ] # fmt: skip
775
+ argv = self._wrap(self._argv("ssh", extra, mux=False) + [self._target()])
776
+ try:
777
+ return proc_registry.track(
778
+ subprocess.Popen(
779
+ argv,
780
+ stdin=subprocess.DEVNULL,
781
+ stdout=subprocess.DEVNULL,
782
+ stderr=subprocess.DEVNULL,
783
+ **self._popen_kwargs(),
784
+ ),
785
+ "remote",
786
+ "túnel de depuração",
787
+ )
788
+ except OSError as exc:
789
+ logger.warning("Túnel de debug falhou: %s", exc)
790
+ return None
791
+
792
+ def close(self) -> None:
793
+ if self._ctl_dir and self._ssh:
794
+ ctl = os.path.join(self._ctl_dir, "%C")
795
+ with contextlib.suppress(OSError, subprocess.SubprocessError):
796
+ subprocess.run(
797
+ [self._ssh, "-o", f"ControlPath={ctl}", "-O", "exit", self._target()],
798
+ capture_output=True,
799
+ timeout=5,
800
+ check=False,
801
+ stdin=subprocess.DEVNULL,
802
+ )
803
+ for attr in ("_ctl_dir", "_askpass_dir"):
804
+ directory = getattr(self, attr)
805
+ if directory:
806
+ shutil.rmtree(directory, ignore_errors=True)
807
+ setattr(self, attr, None)
808
+
809
+
810
+ _DOS_LIST_RE = re.compile(
811
+ r"^(?P<date>\d{2}-\d{2}-\d{2,4})\s+(?P<time>\d{1,2}:\d{2}\s*[AP]M?)\s+"
812
+ r"(?P<size>\d+|<DIR>)\s+(?P<name>.+)$",
813
+ re.IGNORECASE,
814
+ )
815
+
816
+
817
+ def parse_ftp_list(lines: list[str]) -> list[RemoteEntry]:
818
+ """Interpreta linhas de ``LIST`` em formato Unix ou DOS/IIS."""
819
+ entries: list[RemoteEntry] = []
820
+ for line in lines:
821
+ dos = _DOS_LIST_RE.match(line.strip())
822
+ if dos:
823
+ is_dir = dos["size"].upper() == "<DIR>"
824
+ entries.append(
825
+ RemoteEntry(
826
+ name=dos["name"],
827
+ is_dir=is_dir,
828
+ size=None if is_dir else int(dos["size"]),
829
+ modified=f"{dos['date']} {dos['time']}",
830
+ )
831
+ )
832
+ continue
833
+ m = _LS_RE.match(line)
834
+ if m:
835
+ parsed = parse_ls_output(line)
836
+ entries.extend(parsed)
837
+ continue
838
+ parts = line.split(None, 8)
839
+ if len(parts) == 9 and parts[0][:1] in "-dl" and parts[8] not in (".", ".."):
840
+ name, _, target = parts[8].partition(" -> ")
841
+ entries.append(
842
+ RemoteEntry(
843
+ name=name,
844
+ is_dir=parts[0].startswith("d"),
845
+ size=int(parts[4]) if parts[4].isdigit() else None,
846
+ modified=" ".join(parts[5:8]),
847
+ is_link=parts[0].startswith("l"),
848
+ link_target=target,
849
+ )
850
+ )
851
+ return entries
852
+
853
+
854
+ class _ImplicitFTPTLS(ftplib.FTP_TLS):
855
+ """FTPS com TLS implícito (porta 990): o socket é embrulhado ao conectar."""
856
+
857
+ def __init__(self, *args: object, **kwargs: object) -> None:
858
+ super().__init__(*args, **kwargs) # type: ignore[arg-type]
859
+ self._raw_sock: socket.socket | None = None
860
+
861
+ @property
862
+ def sock(self) -> socket.socket | None: # type: ignore[override]
863
+ return self._raw_sock
864
+
865
+ @sock.setter
866
+ def sock(self, value: socket.socket | None) -> None:
867
+ if value is not None and not isinstance(value, ssl.SSLSocket):
868
+ value = self.context.wrap_socket(value, server_hostname=self.host)
869
+ self._raw_sock = value
870
+
871
+
872
+ class FTPAdapter(RemoteAdapter):
873
+ """FTP/FTPS com MLSD (quando disponível), reconexão e acesso serializado."""
874
+
875
+ _KEEPALIVE_S = 25
876
+
877
+ def __init__(self, profile: RemoteProfile) -> None:
878
+ super().__init__(profile)
879
+ self._ftp: ftplib.FTP | None = None
880
+ self._lock = threading.RLock()
881
+ self._last_use = 0.0
882
+
883
+ def _new_client(self) -> ftplib.FTP:
884
+ p = self._p
885
+ if p.proto == Protocol.FTPS:
886
+ ctx = _make_ssl_context(p.verify_tls)
887
+ cls = _ImplicitFTPTLS if p.port == 990 else ftplib.FTP_TLS
888
+ return cls(context=ctx)
889
+ return ftplib.FTP()
890
+
891
+ def connect(self) -> Result:
892
+ p = self._p
893
+ with self._lock:
894
+ self._drop()
895
+ try:
896
+ ftp = self._new_client()
897
+ ftp.connect(p.host, p.port, timeout=p.timeout)
898
+ ftp.login(p.user or "anonymous", p.decoded_password() or "anonymous@")
899
+ if isinstance(ftp, ftplib.FTP_TLS):
900
+ ftp.prot_p()
901
+ ftp.set_pasv(bool(p.passive_ftp))
902
+ self._ftp = ftp
903
+ self._last_use = time.monotonic()
904
+ root = p.remote_root if p.remote_root not in ("", "~") else ""
905
+ if root:
906
+ with contextlib.suppress(ftplib.all_errors):
907
+ ftp.cwd(root)
908
+ self.home = ftp.pwd() or "/"
909
+ return True, _t("rbrowser.connected", "Conectado.")
910
+ except (*ftplib.all_errors, ssl.SSLError, OSError) as exc:
911
+ self._drop()
912
+ return False, self._friendly(exc)
913
+
914
+ @staticmethod
915
+ def _friendly(exc: BaseException) -> str:
916
+ text = str(exc)
917
+ if text.startswith("530"):
918
+ return _t("rbrowser.err_perm", "Permissão negada - verifique usuário, senha ou chave.")
919
+ if isinstance(exc, ssl.SSLCertVerificationError):
920
+ return _t(
921
+ "rbrowser.err_tls",
922
+ "Certificado TLS inválido. Desative 'Verificar certificado' se confiar no servidor.",
923
+ )
924
+ if isinstance(exc, socket.gaierror):
925
+ return _t("rbrowser.err_dns", "Host não encontrado.")
926
+ if isinstance(exc, (ConnectionRefusedError, TimeoutError)):
927
+ return _t("rbrowser.err_refused", "Conexão recusada ou sem resposta.")
928
+ return text or _t("rbrowser.err_generic", "Falha na conexão.")
929
+
930
+ def _drop(self) -> None:
931
+ if self._ftp is not None:
932
+ with contextlib.suppress(*ftplib.all_errors, OSError):
933
+ self._ftp.close()
934
+ self._ftp = None
935
+
936
+ def _client(self) -> ftplib.FTP:
937
+ """Cliente vivo: reconecta se caiu ou ficou ocioso demais."""
938
+ if self._ftp is not None and time.monotonic() - self._last_use > self._KEEPALIVE_S:
939
+ try:
940
+ self._ftp.voidcmd("NOOP")
941
+ except (*ftplib.all_errors, OSError):
942
+ self._drop()
943
+ if self._ftp is None:
944
+ ok, msg = self.connect()
945
+ if not ok:
946
+ raise ConnectionError(msg)
947
+ assert self._ftp is not None
948
+ self._last_use = time.monotonic()
949
+ return self._ftp
950
+
951
+ def _abs(self, path: str) -> str:
952
+ if not path or path == "~":
953
+ return self.home
954
+ if path.startswith("~/"):
955
+ return posixpath.join(self.home, path[2:])
956
+ return path
957
+
958
+ def listdir(self, path: str) -> tuple[list[RemoteEntry], str]:
959
+ with self._lock:
960
+ try:
961
+ ftp = self._client()
962
+ target = self._abs(path)
963
+ with contextlib.suppress(ftplib.error_perm):
964
+ return self._mlsd(ftp, target), ""
965
+ ftp.cwd(target)
966
+ lines: list[str] = []
967
+ ftp.retrlines("LIST", lines.append)
968
+ return parse_ftp_list(lines), ""
969
+ except ConnectionError as exc:
970
+ return [], str(exc)
971
+ except (*ftplib.all_errors, OSError) as exc:
972
+ return [], self._friendly(exc)
973
+
974
+ @staticmethod
975
+ def _mlsd(ftp: ftplib.FTP, target: str) -> list[RemoteEntry]:
976
+ entries: list[RemoteEntry] = []
977
+ for name, facts in ftp.mlsd(target, facts=["type", "size", "modify"]):
978
+ kind = facts.get("type", "").lower()
979
+ if kind in ("cdir", "pdir") or name in (".", ".."):
980
+ continue
981
+ mod = facts.get("modify", "")
982
+ if len(mod) >= 12:
983
+ mod = f"{mod[0:4]}-{mod[4:6]}-{mod[6:8]} {mod[8:10]}:{mod[10:12]}"
984
+ size = facts.get("size", "")
985
+ entries.append(
986
+ RemoteEntry(
987
+ name=name,
988
+ is_dir=kind == "dir",
989
+ size=int(size) if size.isdigit() else None,
990
+ modified=mod,
991
+ )
992
+ )
993
+ return entries
994
+
995
+ def download(self, remote: str, local: Path, progress: ProgressCb | None = None) -> Result:
996
+ part = _temp_part(local)
997
+ with self._lock:
998
+ try:
999
+ ftp = self._client()
1000
+ done = 0
1001
+ with open(part, "wb") as fh:
1002
+
1003
+ def _write(chunk: bytes) -> None:
1004
+ nonlocal done
1005
+ fh.write(chunk)
1006
+ done += len(chunk)
1007
+ if progress:
1008
+ progress(done, None)
1009
+
1010
+ ftp.retrbinary(f"RETR {self._abs(remote)}", _write)
1011
+ os.replace(part, local)
1012
+ return True, ""
1013
+ except (ConnectionError, *ftplib.all_errors, OSError) as exc:
1014
+ part.unlink(missing_ok=True)
1015
+ logger.warning("FTP download: %s", exc)
1016
+ return False, self._friendly(exc)
1017
+
1018
+ def upload(self, local: Path, remote: str, progress: ProgressCb | None = None) -> Result:
1019
+ with self._lock:
1020
+ try:
1021
+ ftp = self._client()
1022
+ total = local.stat().st_size
1023
+ done = 0
1024
+
1025
+ def _cb(chunk: bytes) -> None:
1026
+ nonlocal done
1027
+ done += len(chunk)
1028
+ if progress:
1029
+ progress(done, total)
1030
+
1031
+ with open(local, "rb") as fh:
1032
+ ftp.storbinary(f"STOR {self._abs(remote)}", fh, callback=_cb)
1033
+ return True, ""
1034
+ except (ConnectionError, *ftplib.all_errors, OSError) as exc:
1035
+ logger.warning("FTP upload: %s", exc)
1036
+ return False, self._friendly(exc)
1037
+
1038
+ def _cmd(self, fn: Callable[[ftplib.FTP], object]) -> Result:
1039
+ with self._lock:
1040
+ try:
1041
+ fn(self._client())
1042
+ return True, ""
1043
+ except (ConnectionError, *ftplib.all_errors, OSError) as exc:
1044
+ return False, self._friendly(exc)
1045
+
1046
+ def mkdir(self, path: str) -> Result:
1047
+ return self._cmd(lambda f: f.mkd(self._abs(path)))
1048
+
1049
+ def remove(self, path: str, is_dir: bool = False) -> Result:
1050
+ if is_dir:
1051
+ return self._cmd(lambda f: f.rmd(self._abs(path)))
1052
+ return self._cmd(lambda f: f.delete(self._abs(path)))
1053
+
1054
+ def rename(self, src: str, dst: str) -> Result:
1055
+ return self._cmd(lambda f: f.rename(self._abs(src), self._abs(dst)))
1056
+
1057
+ def close(self) -> None:
1058
+ with self._lock:
1059
+ if self._ftp is not None:
1060
+ with contextlib.suppress(*ftplib.all_errors, OSError):
1061
+ self._ftp.quit()
1062
+ self._drop()
1063
+
1064
+
1065
+ _DATE_RE = re.compile(
1066
+ r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}|\d{2}-[A-Za-z]{3}-\d{4}\s+\d{2}:\d{2}"
1067
+ )
1068
+ _SIZE_RE = re.compile(r"(?:^|\s)(\d+(?:\.\d+)?[KMGT]?|-)\s*$")
1069
+
1070
+
1071
+ class _IndexParser(html.parser.HTMLParser):
1072
+ """Extrai links e o texto que os acompanha (data/tamanho) de um índice."""
1073
+
1074
+ def __init__(self) -> None:
1075
+ super().__init__(convert_charrefs=True)
1076
+ self.items: list[dict[str, str]] = []
1077
+ self._cur: dict[str, str] | None = None
1078
+ self._in_a = False
1079
+
1080
+ def _flush(self) -> None:
1081
+ if self._cur is not None:
1082
+ self.items.append(self._cur)
1083
+ self._cur = None
1084
+
1085
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
1086
+ if tag == "a":
1087
+ self._flush()
1088
+ href = dict(attrs).get("href") or ""
1089
+ self._cur = {"href": href, "label": "", "tail": ""}
1090
+ self._in_a = True
1091
+ elif tag in ("tr", "br", "hr"):
1092
+ self._flush()
1093
+
1094
+ def handle_endtag(self, tag: str) -> None:
1095
+ if tag == "a":
1096
+ self._in_a = False
1097
+ elif tag in ("tr", "pre"):
1098
+ self._flush()
1099
+
1100
+ def handle_data(self, data: str) -> None:
1101
+ if self._cur is None:
1102
+ return
1103
+ key = "label" if self._in_a else "tail"
1104
+ self._cur[key] += data
1105
+
1106
+ def close(self) -> None:
1107
+ super().close()
1108
+ self._flush()
1109
+
1110
+
1111
+ def parse_http_index(body: str, page_url: str) -> list[RemoteEntry]:
1112
+ """Lista filhos diretos de ``page_url`` a partir de um índice Apache/nginx."""
1113
+ parser = _IndexParser()
1114
+ parser.feed(body)
1115
+ parser.close()
1116
+ base = urllib.parse.urlparse(page_url)
1117
+ base_path = base.path if base.path.endswith("/") else base.path + "/"
1118
+ entries: list[RemoteEntry] = []
1119
+ seen: set[str] = set()
1120
+ for item in parser.items:
1121
+ href = item["href"].strip()
1122
+ if not href or href.startswith(("?", "#", "javascript:", "mailto:")):
1123
+ continue
1124
+ target = urllib.parse.urlparse(urllib.parse.urljoin(page_url, href))
1125
+ if target.netloc != base.netloc or not target.path.startswith(base_path):
1126
+ continue
1127
+ rest = target.path[len(base_path):]
1128
+ child = rest.strip("/")
1129
+ if not child or "/" in child:
1130
+ continue
1131
+ name = urllib.parse.unquote(child)
1132
+ if name in seen:
1133
+ continue
1134
+ seen.add(name)
1135
+ tail = item["tail"].replace("\xa0", " ")
1136
+ date = _DATE_RE.search(tail)
1137
+ size_m = _SIZE_RE.search(tail[date.end():] if date else tail)
1138
+ is_dir = rest.endswith("/")
1139
+ entries.append(
1140
+ RemoteEntry(
1141
+ name=name,
1142
+ is_dir=is_dir,
1143
+ size=None if is_dir or not size_m else parse_human_size(size_m.group(1)),
1144
+ modified=re.sub(r"\s+", " ", date.group(0)) if date else "",
1145
+ )
1146
+ )
1147
+ return entries
1148
+
1149
+
1150
+ class HTTPAdapter(RemoteAdapter):
1151
+ """Navegação em índices de diretório HTTP(S) (somente leitura)."""
1152
+
1153
+ read_only = True
1154
+ _MAX_REDIRECTS = 5
1155
+
1156
+ def __init__(self, profile: RemoteProfile) -> None:
1157
+ super().__init__(profile)
1158
+ scheme = "https" if profile.proto in (Protocol.HTTPS, Protocol.WEBDAVS) else "http"
1159
+ host = profile.host
1160
+ self._prefix = ""
1161
+ if "://" in host:
1162
+ parsed = urllib.parse.urlparse(host)
1163
+ scheme = parsed.scheme or scheme
1164
+ host = parsed.netloc
1165
+ self._prefix = parsed.path.rstrip("/")
1166
+ default = 443 if scheme == "https" else 80
1167
+ netloc = host if ":" in host.rsplit("]", 1)[-1] or profile.port == default else f"{host}:{profile.port}"
1168
+ self._base = f"{scheme}://{netloc}"
1169
+ self._opener = urllib.request.build_opener(
1170
+ urllib.request.HTTPSHandler(context=_make_ssl_context(profile.verify_tls))
1171
+ )
1172
+ root = profile.remote_root
1173
+ self.home = "/" if root in ("", "~") else "/" + root.strip("/")
1174
+
1175
+ def _url(self, path: str) -> str:
1176
+ clean = "/" + path.lstrip("/") if path not in ("", "~") else self.home
1177
+ quoted = urllib.parse.quote(self._prefix + clean, safe="/~:@!$&'()*+,;=-._")
1178
+ return self._base + quoted
1179
+
1180
+ def _headers(self) -> dict[str, str]:
1181
+ headers = {"User-Agent": "Codis-RemoteBrowser/3"}
1182
+ if self._p.user:
1183
+ raw = f"{self._p.user}:{self._p.decoded_password()}".encode()
1184
+ headers["Authorization"] = "Basic " + base64.b64encode(raw).decode()
1185
+ return headers
1186
+
1187
+ def _open(
1188
+ self,
1189
+ method: str,
1190
+ url: str,
1191
+ *,
1192
+ data: object = None,
1193
+ headers: dict[str, str] | None = None,
1194
+ ):
1195
+ """Abre ``url`` seguindo redirecionamentos também para métodos WebDAV."""
1196
+ merged = {**self._headers(), **(headers or {})}
1197
+ for _ in range(self._MAX_REDIRECTS + 1):
1198
+ parsed = urllib.parse.urlparse(url)
1199
+ if parsed.scheme not in ("http", "https"):
1200
+ raise ValueError(f"Esquema de URL não suportado: {parsed.scheme!r}")
1201
+ req = urllib.request.Request(url, data=data, method=method, headers=merged) # type: ignore[arg-type]
1202
+ try:
1203
+ return self._opener.open(req, timeout=self._p.timeout)
1204
+ except urllib.error.HTTPError as exc:
1205
+ location = exc.headers.get("Location") if exc.headers else None
1206
+ if exc.code in (301, 302, 307, 308) and location:
1207
+ url = urllib.parse.urljoin(url, location)
1208
+ continue
1209
+ raise
1210
+ raise urllib.error.URLError("too many redirects")
1211
+
1212
+ @staticmethod
1213
+ def _friendly(exc: BaseException) -> str:
1214
+ if isinstance(exc, urllib.error.HTTPError):
1215
+ mapping = {
1216
+ 401: ("rbrowser.http_401", "Credenciais necessárias ou inválidas (HTTP 401)."),
1217
+ 403: ("rbrowser.http_403", "Acesso negado (HTTP 403)."),
1218
+ 404: ("rbrowser.http_404", "Não encontrado (HTTP 404)."),
1219
+ 405: ("rbrowser.http_405", "Operação não permitida pelo servidor (HTTP 405)."),
1220
+ 409: ("rbrowser.http_409", "Conflito: a pasta de destino não existe (HTTP 409)."),
1221
+ 507: ("rbrowser.http_507", "Sem espaço no servidor (HTTP 507)."),
1222
+ }
1223
+ if exc.code in mapping:
1224
+ return _t(*mapping[exc.code])
1225
+ return f"HTTP {exc.code} {exc.reason}"
1226
+ reason = getattr(exc, "reason", exc)
1227
+ if isinstance(reason, ssl.SSLCertVerificationError):
1228
+ return _t(
1229
+ "rbrowser.err_tls",
1230
+ "Certificado TLS inválido. Desative 'Verificar certificado' se confiar no servidor.",
1231
+ )
1232
+ if isinstance(reason, socket.gaierror):
1233
+ return _t("rbrowser.err_dns", "Host não encontrado.")
1234
+ if isinstance(reason, (ConnectionRefusedError, TimeoutError, socket.timeout)):
1235
+ return _t("rbrowser.err_refused", "Conexão recusada ou sem resposta.")
1236
+ return str(reason) or _t("rbrowser.err_generic", "Falha na conexão.")
1237
+
1238
+ def connect(self) -> Result:
1239
+ try:
1240
+ with self._open("GET", self._url(self.home)) as resp:
1241
+ resp.read(1024)
1242
+ return True, _t("rbrowser.connected", "Conectado.")
1243
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1244
+ return False, self._friendly(exc)
1245
+
1246
+ def listdir(self, path: str) -> tuple[list[RemoteEntry], str]:
1247
+ url = self._url(path)
1248
+ if not url.endswith("/"):
1249
+ url += "/"
1250
+ try:
1251
+ with self._open("GET", url) as resp:
1252
+ body = resp.read(MAX_LISTING_BYTES).decode("utf-8", errors="replace")
1253
+ final_url = resp.geturl()
1254
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1255
+ return [], self._friendly(exc)
1256
+ return parse_http_index(body, final_url if final_url.endswith("/") else url), ""
1257
+
1258
+ def download(self, remote: str, local: Path, progress: ProgressCb | None = None) -> Result:
1259
+ part = _temp_part(local)
1260
+ try:
1261
+ with self._open("GET", self._url(remote)) as resp, open(part, "wb") as fh:
1262
+ total = int(resp.headers.get("Content-Length") or 0) or None
1263
+ done = 0
1264
+ while chunk := resp.read(64 * 1024):
1265
+ fh.write(chunk)
1266
+ done += len(chunk)
1267
+ if progress:
1268
+ progress(done, total)
1269
+ os.replace(part, local)
1270
+ return True, ""
1271
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1272
+ part.unlink(missing_ok=True)
1273
+ logger.warning("HTTP download %s: %s", remote, exc)
1274
+ return False, self._friendly(exc)
1275
+
1276
+ def upload(self, local: Path, remote: str, progress: ProgressCb | None = None) -> Result:
1277
+ return False, _t("rbrowser.http_no_upload", "Upload não suportado via HTTP.")
1278
+
1279
+
1280
+ _PROPFIND_BODY = (
1281
+ b'<?xml version="1.0" encoding="utf-8"?>'
1282
+ b'<d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:getcontentlength/>'
1283
+ b"<d:getlastmodified/></d:prop></d:propfind>"
1284
+ )
1285
+ _DAV = "{DAV:}"
1286
+
1287
+
1288
+ class WebDAVAdapter(HTTPAdapter):
1289
+ """WebDAV completo: listar, baixar, enviar, criar pasta, renomear, excluir."""
1290
+
1291
+ read_only = False
1292
+
1293
+ def connect(self) -> Result:
1294
+ """Valida com ``PROPFIND Depth: 0`` (um GET numa coleção WebDAV costuma
1295
+ cair no navegador HTML do servidor ou redirecionar)."""
1296
+ url = self._url(self.home).rstrip("/") + "/"
1297
+ try:
1298
+ with self._open(
1299
+ "PROPFIND",
1300
+ url,
1301
+ data=_PROPFIND_BODY,
1302
+ headers={"Depth": "0", "Content-Type": "application/xml"},
1303
+ ) as resp:
1304
+ resp.read(1024)
1305
+ return True, _t("rbrowser.connected", "Conectado.")
1306
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1307
+ return False, self._friendly(exc)
1308
+
1309
+ def listdir(self, path: str) -> tuple[list[RemoteEntry], str]:
1310
+ url = self._url(path)
1311
+ if not url.endswith("/"):
1312
+ url += "/"
1313
+ try:
1314
+ with self._open(
1315
+ "PROPFIND",
1316
+ url,
1317
+ data=_PROPFIND_BODY,
1318
+ headers={"Depth": "1", "Content-Type": "application/xml"},
1319
+ ) as resp:
1320
+ body = resp.read(MAX_LISTING_BYTES)
1321
+ final = urllib.parse.urlparse(resp.geturl()).path
1322
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1323
+ return [], self._friendly(exc)
1324
+ try:
1325
+ root = _XML_FROMSTRING(body)
1326
+ except ET.ParseError as exc:
1327
+ return [], f"XML inválido: {exc}"
1328
+ self_path = urllib.parse.unquote(final).rstrip("/")
1329
+ entries: list[RemoteEntry] = []
1330
+ for response in root.findall(f"{_DAV}response"):
1331
+ href_el = response.find(f"{_DAV}href")
1332
+ if href_el is None or not href_el.text:
1333
+ continue
1334
+ href_path = urllib.parse.unquote(urllib.parse.urlparse(href_el.text.strip()).path)
1335
+ if href_path.rstrip("/") == self_path:
1336
+ continue
1337
+ name = posixpath.basename(href_path.rstrip("/"))
1338
+ if not name:
1339
+ continue
1340
+ is_dir = response.find(f".//{_DAV}resourcetype/{_DAV}collection") is not None
1341
+ size_el = response.find(f".//{_DAV}getcontentlength")
1342
+ mod_el = response.find(f".//{_DAV}getlastmodified")
1343
+ size_txt = (size_el.text or "").strip() if size_el is not None else ""
1344
+ entries.append(
1345
+ RemoteEntry(
1346
+ name=name,
1347
+ is_dir=is_dir,
1348
+ size=int(size_txt) if size_txt.isdigit() and not is_dir else None,
1349
+ modified=(mod_el.text or "").strip() if mod_el is not None else "",
1350
+ )
1351
+ )
1352
+ return entries, ""
1353
+
1354
+ def upload(self, local: Path, remote: str, progress: ProgressCb | None = None) -> Result:
1355
+ try:
1356
+ with open(local, "rb") as fh:
1357
+ headers = {
1358
+ "Content-Length": str(local.stat().st_size),
1359
+ "Content-Type": "application/octet-stream",
1360
+ }
1361
+ with self._open("PUT", self._url(remote), data=fh, headers=headers) as resp:
1362
+ ok = resp.status in (200, 201, 204)
1363
+ return ok, "" if ok else f"HTTP {resp.status}"
1364
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1365
+ logger.warning("WebDAV PUT: %s", exc)
1366
+ return False, self._friendly(exc)
1367
+
1368
+ def _method(self, method: str, url: str, headers: dict[str, str] | None = None) -> Result:
1369
+ try:
1370
+ with self._open(method, url, headers=headers) as resp:
1371
+ resp.read()
1372
+ return True, ""
1373
+ except (urllib.error.URLError, OSError, ValueError) as exc:
1374
+ return False, self._friendly(exc)
1375
+
1376
+ def mkdir(self, path: str) -> Result:
1377
+ return self._method("MKCOL", self._url(path).rstrip("/") + "/")
1378
+
1379
+ def remove(self, path: str, is_dir: bool = False) -> Result:
1380
+ url = self._url(path)
1381
+ return self._method("DELETE", url.rstrip("/") + "/" if is_dir else url)
1382
+
1383
+ def rename(self, src: str, dst: str) -> Result:
1384
+ return self._method(
1385
+ "MOVE", self._url(src), {"Destination": self._url(dst), "Overwrite": "F"}
1386
+ )
1387
+
1388
+
1389
+ def make_adapter(profile: RemoteProfile) -> RemoteAdapter:
1390
+ """Cria o adaptador adequado ao protocolo do perfil."""
1391
+ proto = profile.proto
1392
+ if proto in (Protocol.FTP, Protocol.FTPS):
1393
+ return FTPAdapter(profile)
1394
+ if proto in (Protocol.WEBDAV, Protocol.WEBDAVS):
1395
+ return WebDAVAdapter(profile)
1396
+ if proto in (Protocol.HTTP, Protocol.HTTPS):
1397
+ return HTTPAdapter(profile)
1398
+ return SSHAdapter(profile)