Repository navigation
Expand file tree
/
Copy pathurl_utils.py
More file actions
212 lines (169 loc) · 8.24 KB
/
Copy pathurl_utils.py
File metadata and controls
212 lines (169 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""
URL parsing utilities for WriterAgent.
HTTP / LLM endpoint helpers live below. Filesystem ``file:`` conversion is a
separate section — do not fold it into ``normalize_endpoint_url``.
Imported by the off-main ``=PY`` sandbox via the compute bundle
(``scripts/build_compute_bundle.py``); stdlib + ``deal_shim`` only.
"""
# crosshair: off
from __future__ import annotations
import os
import posixpath
import urllib.parse
from pathlib import Path
from typing import Any
from plugin.framework.deal_shim import deal
def matches_extension_dispatch_url(url: Any, extension_id: str) -> bool:
"""Return True when *url* is an extension menu/protocol dispatch URL."""
prefix = extension_id + ":"
return url.Protocol.startswith(prefix) or url.Complete.startswith(prefix)
def dispatch_command_from_url(url: Any) -> str:
"""Extract handler command from a LibreOffice dispatch URL.
Shared extractor for LibrePy and WriterAgent dispatch URLs.
Do not append ``Query`` here.
LO usually sets ``Path`` (e.g. ``main.settings``). Some dispatch paths only
populate ``Complete`` (``org.extension.librepy:main.settings``); derive Path
from that so menu handlers still run.
"""
path = url.Path.strip().lstrip("/")
if path:
return path
before, colon, after = url.Complete.strip().partition(":")
return after.lstrip("/") if colon else before
def host_matches(host: str, *domains: str) -> bool:
"""True when host equals any domain or is a subdomain of it."""
h = host.lower()
return any(h == domain or h.endswith("." + domain) for domain in domains)
@deal.post(lambda result: isinstance(result, str) and result.startswith("/"))
def get_api_version_suffix(url: Any, is_openwebui: bool = False) -> str:
"""Return the API version suffix (e.g. '/v1', '/v4', '/api/paas/v4') for a given endpoint URL."""
if is_openwebui:
return "/api"
host = get_url_hostname(url)
# Z.ai: bare host uses general OpenAI base (/api/paas/v4); deeper paths append /v4 only.
if host_matches(host, "z.ai"):
if not get_url_path(url).rstrip("/"):
return "/api/paas/v4"
return "/v4"
# Google Gemini: OpenAI-compatible API base is /v1beta/openai
if host_matches(host, "generativelanguage.googleapis.com"):
return "/v1beta/openai"
return "/v1"
@deal.post(lambda result: isinstance(result, str))
@deal.ensure(lambda url, is_openwebui=False, result="": bool(isinstance(url, str) and url.strip()) or result == "")
def normalize_endpoint_url(url: Any, is_openwebui: bool = False) -> str:
"""Clean up endpoint URL: strip whitespace, trailing slashes, and domain-specific version suffixes."""
if type(url) is not str or not url.strip():
return ""
url = url.strip().rstrip("/")
# One strip, longest suffix first. Open WebUI must take /api/v1 in one
# pass (half-stripping to /api, then re-appending /api, yields /api/api/...).
# Z.ai legacy presets stored https://api.z.ai/v4 before the general base
# was /api/paas/v4. That /v4 is only a fallback after the live suffix.
if is_openwebui:
suffixes = ("/api/v1", "/api", "/v1")
else:
host = get_url_hostname(url)
extra = ("/v1beta",) if host_matches(host, "generativelanguage.googleapis.com") else ("/v4",) if host_matches(host, "z.ai") else ()
suffixes = (get_api_version_suffix(url), *extra, "/v1")
for suffix in suffixes:
if url.lower().endswith(suffix):
return url[: -len(suffix)]
return url
def _parse(url: Any) -> urllib.parse.ParseResult:
try:
return urllib.parse.urlparse(url if type(url) is str else "")
except ValueError:
return urllib.parse.urlparse("")
@deal.post(lambda result: isinstance(result, str))
def get_url_hostname(url: Any) -> str:
"""Return hostname from URL safely."""
return _parse(url).hostname or ""
# Labels that registries under two-letter country TLDs use as a public second level
# (bbc.co.uk, abc.net.au, soumu.go.jp). A short list rather than the Public Suffix List:
# a missing label leaves two labels, and an extra match keeps one more label than needed.
_CC_SECOND_LEVEL = frozenset({"ac", "co", "com", "edu", "go", "gob", "gouv", "gov", "govt", "mil", "ne", "net", "or", "org"})
@deal.post(lambda result: isinstance(result, str))
def get_url_domain(url: Any) -> str:
"""Return 'example.com' from 'https://api.example.com/v1' and 'bbc.co.uk' from 'https://www.bbc.co.uk/'."""
labels = get_url_hostname(url).split(".")
keep = 3 if len(labels) > 2 and len(labels[-1]) == 2 and labels[-2] in _CC_SECOND_LEVEL else 2
return ".".join(labels[-keep:])
@deal.post(lambda result: isinstance(result, str))
def get_url_path(url: Any) -> str:
"""Return path from URL safely."""
return _parse(url).path
@deal.post(lambda result: isinstance(result, dict))
def get_url_query_dict(url: Any) -> dict[str, list[str]]:
"""Return query parameters as dict (values are lists)."""
return urllib.parse.parse_qs(_parse(url).query)
@deal.post(lambda result: isinstance(result, str))
def get_url_path_and_query(url: Any) -> str:
"""Return path + query string from URL."""
parsed = _parse(url)
path = parsed.path or "/"
return f"{path}?{parsed.query}" if parsed.query else path
@deal.post(lambda result: isinstance(result, bool))
def is_pdf_url(url: Any) -> bool:
"""Check for .pdf in the URL path safely."""
return _parse(url).path.lower().endswith(".pdf")
# ---------------------------------------------------------------------------
# Filesystem / document file: URLs (UNO-free; not HTTP endpoints)
# ---------------------------------------------------------------------------
def path_to_file_url(path: str) -> str:
"""Build a document / ``loadComponentFromURL`` / GraphicProvider-style ``file:`` URL.
Normalize with ``os.path.abspath`` then ``Path.as_uri()`` so Unix yields
``file:///…`` (three slashes). ``urljoin('file:', …)`` wrongly produces
``file:/…``. POSIX absolute paths (leading ``/``, not ``//``) use
``posixpath.normpath`` + ``urllib.parse.quote`` so they do not pick up a
Windows drive letter. Not an LLM endpoint helper; no ``@deal`` (those
contracts are for HTTP strings). UNO-free so embeddings extract can import
this module.
"""
if path.startswith("/") and not path.startswith("//"):
return "file://" + urllib.parse.quote(posixpath.normpath(path))
return Path(os.path.abspath(path)).as_uri()
def path_from_file_url(raw: str) -> str | None:
"""Convert a ``file://`` / ``file:/`` URL to a filesystem path (stdlib only)."""
# crosshair: off
# file: URLs are normalized case-insensitively with RFC 8089 localhost handling and correct UNC
# formatting so paths like FILE:///tmp/x and file://localhost/C:/x resolve safely.
text = raw.strip()
if len(text) < 5 or text[:5].lower() != "file:":
return None
text = "file:" + text[5:]
if text.startswith("file:/") and not text.startswith("file://"):
text = "file://" + text[len("file:") :]
if not text.startswith("file://"):
return None
parsed = urllib.parse.urlparse(text)
unquoted = urllib.parse.unquote(parsed.path)
host = parsed.netloc
if host.lower() == "localhost":
host = ""
if os.name == "nt":
if host:
tail = unquoted[1:] if unquoted.startswith("/") else unquoted
tail = tail.replace("/", "\\")
path = "\\\\" + host + ("\\" + tail if tail else "")
elif len(unquoted) >= 3 and unquoted[0] == "/" and unquoted[2] == ":":
path = unquoted[1:].replace("/", "\\")
else:
path = unquoted
else:
path = unquoted
return path or None
def normalize_file_url(url: str) -> str:
"""Repair ``file:/path`` URLs (one slash) to ``file:///home/...``.
``loadComponentFromURL`` and ``fileUrlToSystemPath`` need three slashes.
Shared by ``get_document_path`` and document-research URL→path.
``session_manager`` keeps its own stdlib copy (no UNO, Windows).
"""
raw = url.strip()
if raw.startswith("file:/") and not raw.startswith("file://"):
return "file://" + raw[len("file:") :]
return raw