giu-mcp 0.2.0__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.
- giu_mcp/__init__.py +3 -0
- giu_mcp/__main__.py +5 -0
- giu_mcp/cli.py +160 -0
- giu_mcp/client.py +264 -0
- giu_mcp/cms.py +327 -0
- giu_mcp/config.py +105 -0
- giu_mcp/credentials.py +131 -0
- giu_mcp/icon.png +0 -0
- giu_mcp/portal.py +457 -0
- giu_mcp/prompts.py +100 -0
- giu_mcp/server.py +228 -0
- giu_mcp/util.py +123 -0
- giu_mcp-0.2.0.dist-info/METADATA +260 -0
- giu_mcp-0.2.0.dist-info/RECORD +18 -0
- giu_mcp-0.2.0.dist-info/WHEEL +5 -0
- giu_mcp-0.2.0.dist-info/entry_points.txt +2 -0
- giu_mcp-0.2.0.dist-info/licenses/LICENSE +75 -0
- giu_mcp-0.2.0.dist-info/top_level.txt +1 -0
giu_mcp/__init__.py
ADDED
giu_mcp/__main__.py
ADDED
giu_mcp/cli.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Command line: `giu-mcp` runs the MCP server; `giu-mcp login|logout|status|config` set it up."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__, credentials
|
|
13
|
+
|
|
14
|
+
CLIENTS = ["claude-code", "claude-desktop", "cursor", "vscode", "windsurf", "gemini", "codex", "json"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _launch_command() -> tuple[str, list[str]]:
|
|
18
|
+
"""How an AI app should start this server on this machine."""
|
|
19
|
+
if any(part.startswith("archive-v") for part in Path(sys.executable).parts):
|
|
20
|
+
return "uvx", ["giu-mcp"] # running via `uvx giu-mcp`: its cache path isn't stable
|
|
21
|
+
exe = shutil.which("giu-mcp")
|
|
22
|
+
if exe and Path(exe).resolve().parent != Path(sys.executable).resolve().parent:
|
|
23
|
+
return exe, [] # installed as a tool (pipx / uv tool): stable path on PATH
|
|
24
|
+
return sys.executable, ["-m", "giu_mcp"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cmd_login(args) -> int:
|
|
28
|
+
from .client import AuthError, GiuClient
|
|
29
|
+
from .config import PORTAL_HOME, Settings
|
|
30
|
+
from .portal import profile
|
|
31
|
+
|
|
32
|
+
print("Sign in with the same GIU username and password you use for portal.giu-uni.de.")
|
|
33
|
+
username = (args.username or input("GIU username: ")).strip()
|
|
34
|
+
password = getpass.getpass("GIU password (hidden): ")
|
|
35
|
+
if not username or not password:
|
|
36
|
+
print("Username and password are both required.", file=sys.stderr)
|
|
37
|
+
return 1
|
|
38
|
+
settings = Settings(username, password, args.domain.strip(), Path.home(), 45.0, "login")
|
|
39
|
+
if not args.no_verify:
|
|
40
|
+
print("Checking with the portal…")
|
|
41
|
+
try:
|
|
42
|
+
client = GiuClient(settings)
|
|
43
|
+
client.get(PORTAL_HOME)
|
|
44
|
+
who = profile(client)
|
|
45
|
+
except AuthError:
|
|
46
|
+
print("GIU rejected that username/password. Nothing was saved.", file=sys.stderr)
|
|
47
|
+
return 1
|
|
48
|
+
except Exception as e:
|
|
49
|
+
print(f"Could not reach the portal ({e}). Use --no-verify to save anyway.", file=sys.stderr)
|
|
50
|
+
return 1
|
|
51
|
+
print(f"Signed in as {who['name'] or username}" + (f" ({who['student_id']})" if who["student_id"] else ""))
|
|
52
|
+
where = credentials.save(username, password, args.domain.strip())
|
|
53
|
+
if where == "keyring":
|
|
54
|
+
print("Password saved in your operating system's credential store.")
|
|
55
|
+
else:
|
|
56
|
+
print(f"No OS credential store found: password saved in {credentials.config_dir() / 'account.json'} (readable by you only).")
|
|
57
|
+
print("\nNext: add the server to your AI app. For the exact snippet, run: giu-mcp config")
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def cmd_logout(args) -> int:
|
|
62
|
+
print("Signed out: saved GIU account removed." if credentials.clear() else "No saved GIU account.")
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_status(args) -> int:
|
|
67
|
+
from .client import AuthError, GiuClient
|
|
68
|
+
from .config import ConfigError, load_settings
|
|
69
|
+
from . import cms, portal
|
|
70
|
+
|
|
71
|
+
print(f"giu-mcp {__version__} | config folder: {credentials.config_dir()}")
|
|
72
|
+
try:
|
|
73
|
+
settings = load_settings()
|
|
74
|
+
except ConfigError as e:
|
|
75
|
+
print(e)
|
|
76
|
+
return 1
|
|
77
|
+
print(f"Account: {settings.username} (from {settings.source})")
|
|
78
|
+
client = GiuClient(settings)
|
|
79
|
+
try:
|
|
80
|
+
who = portal.profile(client)
|
|
81
|
+
print(f"Portal: OK, signed in as {who['name']} {who['student_id']}".rstrip())
|
|
82
|
+
print(f"CMS: OK, {len(cms.current_courses(client))} current course(s)")
|
|
83
|
+
except AuthError as e:
|
|
84
|
+
print(f"Sign-in failed: {e}\nRun `giu-mcp login` again.")
|
|
85
|
+
return 1
|
|
86
|
+
except Exception as e:
|
|
87
|
+
print(f"Could not reach GIU: {e}")
|
|
88
|
+
return 1
|
|
89
|
+
print(f"Downloads go to: {settings.download_dir}")
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cmd_config(args) -> int:
|
|
94
|
+
command, cmd_args = _launch_command()
|
|
95
|
+
server = {"command": command, "args": cmd_args}
|
|
96
|
+
show = args.client or "all"
|
|
97
|
+
|
|
98
|
+
def block(title: str, body: str) -> None:
|
|
99
|
+
print(f"\n== {title}\n{body}")
|
|
100
|
+
|
|
101
|
+
quoted = " ".join(f'"{x}"' if " " in x else x for x in [command, *cmd_args])
|
|
102
|
+
if show in ("all", "claude-code"):
|
|
103
|
+
block("Claude Code (run once in a terminal)", f"claude mcp add giu --scope user -- {quoted}")
|
|
104
|
+
if show in ("all", "claude-desktop", "cursor", "windsurf", "gemini", "json"):
|
|
105
|
+
where = {
|
|
106
|
+
"claude-desktop": "Claude Desktop: Settings > Developer > Edit Config (claude_desktop_config.json)",
|
|
107
|
+
"cursor": "Cursor: ~/.cursor/mcp.json",
|
|
108
|
+
"windsurf": "Windsurf: ~/.codeium/windsurf/mcp_config.json",
|
|
109
|
+
"gemini": "Gemini CLI: ~/.gemini/settings.json",
|
|
110
|
+
}
|
|
111
|
+
title = where.get(show) or "Claude Desktop, Cursor, Windsurf, Gemini CLI and most other apps (inside \"mcpServers\")"
|
|
112
|
+
block(title, json.dumps({"mcpServers": {"giu": server}}, indent=2))
|
|
113
|
+
if show in ("all", "vscode"):
|
|
114
|
+
block("VS Code (.vscode/mcp.json, or 'MCP: Add Server')", json.dumps({"servers": {"giu": {"type": "stdio", **server}}}, indent=2))
|
|
115
|
+
if show in ("all", "codex"):
|
|
116
|
+
toml_args = ", ".join(json.dumps(a) for a in cmd_args)
|
|
117
|
+
block("OpenAI Codex CLI (~/.codex/config.toml)", f"[mcp_servers.giu]\ncommand = {json.dumps(command)}\nargs = [{toml_args}]")
|
|
118
|
+
print("\nRestart the app afterwards. The server reads the account saved by `giu-mcp login`.")
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_serve(args) -> int:
|
|
123
|
+
if sys.stdin.isatty():
|
|
124
|
+
print(
|
|
125
|
+
"giu-mcp: starting the MCP server on stdio. AI apps launch this themselves;\n"
|
|
126
|
+
"to set up instead, run `giu-mcp login` then `giu-mcp config`. Ctrl+C to stop.",
|
|
127
|
+
file=sys.stderr,
|
|
128
|
+
)
|
|
129
|
+
from .server import main as serve
|
|
130
|
+
|
|
131
|
+
serve()
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def main(argv: list[str] | None = None) -> int:
|
|
136
|
+
p = argparse.ArgumentParser(
|
|
137
|
+
prog="giu-mcp",
|
|
138
|
+
description="MCP server for the GIU student portal and CMS. Run without a command to start the server.",
|
|
139
|
+
)
|
|
140
|
+
p.add_argument("--version", action="version", version=f"giu-mcp {__version__}")
|
|
141
|
+
sub = p.add_subparsers(dest="cmd", metavar="command")
|
|
142
|
+
sub.add_parser("serve", help="run the MCP server over stdio (the default)")
|
|
143
|
+
lp = sub.add_parser("login", help="save your GIU username and password for the server")
|
|
144
|
+
lp.add_argument("--username", help="GIU username (asked if omitted)")
|
|
145
|
+
lp.add_argument("--domain", default="", help="Windows domain, only if sign-in fails without it")
|
|
146
|
+
lp.add_argument("--no-verify", action="store_true", help="save without checking against the portal")
|
|
147
|
+
sub.add_parser("logout", help="remove the saved account")
|
|
148
|
+
sub.add_parser("status", help="check that the saved account can sign in")
|
|
149
|
+
cp = sub.add_parser("config", help="print the snippet to add this server to an AI app")
|
|
150
|
+
cp.add_argument("client", nargs="?", choices=CLIENTS, help="only this app (default: all)")
|
|
151
|
+
args = p.parse_args(argv)
|
|
152
|
+
handler = {"login": cmd_login, "logout": cmd_logout, "status": cmd_status, "config": cmd_config}.get(args.cmd, cmd_serve)
|
|
153
|
+
try:
|
|
154
|
+
return handler(args) or 0
|
|
155
|
+
except KeyboardInterrupt:
|
|
156
|
+
return 130
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == "__main__":
|
|
160
|
+
sys.exit(main())
|
giu_mcp/client.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""HTTP client for the GIU sites.
|
|
2
|
+
|
|
3
|
+
Both portal.giu-uni.de and cms.giu-uni.de are IIS / ASP.NET WebForms apps behind
|
|
4
|
+
Windows (NTLM) authentication, so every request goes through one requests.Session
|
|
5
|
+
with HttpNtlmAuth. ASP.NET postbacks (dropdowns, "Show" buttons) are replayed by
|
|
6
|
+
re-posting the page's hidden form state.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from urllib.parse import parse_qs, urljoin, urlparse
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
from bs4 import BeautifulSoup
|
|
20
|
+
from requests_ntlm import HttpNtlmAuth
|
|
21
|
+
|
|
22
|
+
from .config import PORTAL_HOME, Settings, load_settings
|
|
23
|
+
|
|
24
|
+
USER_AGENT = (
|
|
25
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
26
|
+
"(KHTML, like Gecko) Chrome/131.0 Safari/537.36 giu-mcp/0.1"
|
|
27
|
+
)
|
|
28
|
+
ALLOWED_HOSTS = {"portal.giu-uni.de", "cms.giu-uni.de"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class GiuError(RuntimeError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthError(GiuError):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PortalBounce(GiuError):
|
|
40
|
+
"""The portal sent us back to Home.aspx: its session state was not set up yet."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Page:
|
|
45
|
+
url: str
|
|
46
|
+
status: int
|
|
47
|
+
html: str
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def soup(self) -> BeautifulSoup:
|
|
51
|
+
return BeautifulSoup(self.html, "lxml")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class GiuClient:
|
|
55
|
+
def __init__(self, settings: Settings | None = None) -> None:
|
|
56
|
+
self._settings = settings
|
|
57
|
+
self._session: requests.Session | None = None
|
|
58
|
+
self._lock = threading.RLock()
|
|
59
|
+
self._portal_ready = False
|
|
60
|
+
self._cache: dict[str, tuple[float, Page]] = {}
|
|
61
|
+
|
|
62
|
+
# ------------------------------------------------------------------ session
|
|
63
|
+
@property
|
|
64
|
+
def settings(self) -> Settings:
|
|
65
|
+
if self._settings is None:
|
|
66
|
+
self._settings = load_settings()
|
|
67
|
+
return self._settings
|
|
68
|
+
|
|
69
|
+
def _new_session(self) -> requests.Session:
|
|
70
|
+
s = requests.Session()
|
|
71
|
+
s.auth = HttpNtlmAuth(self.settings.ntlm_user, self.settings.password)
|
|
72
|
+
s.headers.update({"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"})
|
|
73
|
+
return s
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def session(self) -> requests.Session:
|
|
77
|
+
if self._session is None:
|
|
78
|
+
self._session = self._new_session()
|
|
79
|
+
return self._session
|
|
80
|
+
|
|
81
|
+
def reset(self) -> None:
|
|
82
|
+
with self._lock:
|
|
83
|
+
if self._session is not None:
|
|
84
|
+
self._session.close()
|
|
85
|
+
self._session = None
|
|
86
|
+
self._portal_ready = False
|
|
87
|
+
self._cache.clear()
|
|
88
|
+
|
|
89
|
+
# ------------------------------------------------------------------ requests
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _check_host(url: str) -> None:
|
|
92
|
+
host = urlparse(url).hostname or ""
|
|
93
|
+
if host not in ALLOWED_HOSTS:
|
|
94
|
+
raise GiuError(f"Refusing to send GIU credentials to {host!r}")
|
|
95
|
+
|
|
96
|
+
def _send(self, method: str, url: str, **kw) -> requests.Response:
|
|
97
|
+
"""One hop, no redirects, with a single fresh-session retry for stale NTLM auth."""
|
|
98
|
+
with self._lock:
|
|
99
|
+
try:
|
|
100
|
+
resp = self.session.request(method, url, allow_redirects=False, **kw)
|
|
101
|
+
except requests.ConnectionError:
|
|
102
|
+
# A dropped keep-alive connection breaks the NTLM handshake; retry once fresh.
|
|
103
|
+
self.reset()
|
|
104
|
+
resp = self.session.request(method, url, allow_redirects=False, **kw)
|
|
105
|
+
if resp.status_code == 401:
|
|
106
|
+
# Session/connection auth went stale: rebuild once before giving up.
|
|
107
|
+
self.reset()
|
|
108
|
+
resp = self.session.request(method, url, allow_redirects=False, **kw)
|
|
109
|
+
if resp.status_code == 401:
|
|
110
|
+
raise AuthError(
|
|
111
|
+
"GIU rejected the username/password (HTTP 401). With the Claude Desktop "
|
|
112
|
+
"extension, fix them in Settings > Desktop app > Extensions > GIU MCP > Configure; otherwise "
|
|
113
|
+
"run `giu-mcp login` again."
|
|
114
|
+
)
|
|
115
|
+
return resp
|
|
116
|
+
|
|
117
|
+
def _request(self, method: str, url: str, **kw) -> requests.Response:
|
|
118
|
+
# Redirects are followed by hand so every hop is host-checked *before* the
|
|
119
|
+
# NTLM handshake, never after.
|
|
120
|
+
kw.setdefault("timeout", self.settings.timeout)
|
|
121
|
+
for _ in range(10):
|
|
122
|
+
self._check_host(url)
|
|
123
|
+
resp = self._send(method, url, **kw)
|
|
124
|
+
if not resp.is_redirect:
|
|
125
|
+
return resp
|
|
126
|
+
url = urljoin(resp.url, resp.headers["Location"])
|
|
127
|
+
if resp.status_code in (301, 302, 303) and method != "GET":
|
|
128
|
+
method = "GET"
|
|
129
|
+
kw.pop("data", None)
|
|
130
|
+
resp.close()
|
|
131
|
+
raise GiuError("Too many redirects")
|
|
132
|
+
|
|
133
|
+
def _ensure_portal(self, url: str) -> None:
|
|
134
|
+
# The portal only initialises its session state when Home.aspx loads; without
|
|
135
|
+
# that, every postback is bounced back to Home.
|
|
136
|
+
if urlparse(url).hostname == "portal.giu-uni.de" and not self._portal_ready:
|
|
137
|
+
with self._lock:
|
|
138
|
+
if not self._portal_ready:
|
|
139
|
+
self._portal_ready = True # set first: the GET below re-enters here
|
|
140
|
+
if url.split("?")[0].lower() != PORTAL_HOME.lower():
|
|
141
|
+
try:
|
|
142
|
+
self.get(PORTAL_HOME)
|
|
143
|
+
except Exception:
|
|
144
|
+
self._portal_ready = False
|
|
145
|
+
raise
|
|
146
|
+
|
|
147
|
+
def _finish(self, requested: str, resp: requests.Response) -> Page:
|
|
148
|
+
resp.raise_for_status()
|
|
149
|
+
final = urlparse(resp.url)
|
|
150
|
+
if final.path.lower().endswith("/systemmessage.aspx"):
|
|
151
|
+
msg = parse_qs(final.query).get("err", ["The portal refused this page."])[0]
|
|
152
|
+
raise GiuError(f"Portal message: {msg}")
|
|
153
|
+
if (
|
|
154
|
+
final.hostname == "portal.giu-uni.de"
|
|
155
|
+
and final.path.lower().endswith("/extstudent/home.aspx")
|
|
156
|
+
and not urlparse(requested).path.lower().endswith("/home.aspx")
|
|
157
|
+
):
|
|
158
|
+
self._portal_ready = False
|
|
159
|
+
raise PortalBounce("Portal redirected to Home.aspx")
|
|
160
|
+
return Page(resp.url, resp.status_code, resp.text)
|
|
161
|
+
|
|
162
|
+
def get(self, url: str, ttl: float = 0, **kw) -> Page:
|
|
163
|
+
"""GET a page. With ttl > 0, reuse a copy fetched within the last `ttl` seconds."""
|
|
164
|
+
if ttl and url in self._cache and time.monotonic() - self._cache[url][0] < ttl:
|
|
165
|
+
return self._cache[url][1]
|
|
166
|
+
self._ensure_portal(url)
|
|
167
|
+
page = self._finish(url, self._request("GET", url, **kw))
|
|
168
|
+
if ttl:
|
|
169
|
+
self._cache[url] = (time.monotonic(), page)
|
|
170
|
+
return page
|
|
171
|
+
|
|
172
|
+
def post(self, url: str, data: dict, **kw) -> Page:
|
|
173
|
+
self._ensure_portal(url)
|
|
174
|
+
return self._finish(url, self._request("POST", url, data=data, **kw))
|
|
175
|
+
|
|
176
|
+
# ------------------------------------------------------------------ webforms
|
|
177
|
+
@staticmethod
|
|
178
|
+
def form_state(soup: BeautifulSoup, form_id: str | None = None) -> tuple[str | None, dict]:
|
|
179
|
+
"""Return (action, fields) for the page's main form, as a browser would submit it."""
|
|
180
|
+
form = soup.find("form", id=form_id) if form_id else soup.find("form")
|
|
181
|
+
if form is None:
|
|
182
|
+
raise GiuError("Page has no form to post back")
|
|
183
|
+
fields: dict[str, str] = {}
|
|
184
|
+
for inp in form.find_all("input"):
|
|
185
|
+
name = inp.get("name")
|
|
186
|
+
if not name:
|
|
187
|
+
continue
|
|
188
|
+
typ = (inp.get("type") or "text").lower()
|
|
189
|
+
if typ in {"submit", "button", "image", "reset", "file"}:
|
|
190
|
+
continue
|
|
191
|
+
if typ in {"checkbox", "radio"} and not inp.has_attr("checked"):
|
|
192
|
+
continue
|
|
193
|
+
fields[name] = inp.get("value", "on" if typ in {"checkbox", "radio"} else "")
|
|
194
|
+
for sel in form.find_all("select"):
|
|
195
|
+
name = sel.get("name")
|
|
196
|
+
if not name:
|
|
197
|
+
continue
|
|
198
|
+
opt = sel.find("option", selected=True) or sel.find("option")
|
|
199
|
+
fields[name] = opt.get("value", opt.get_text(strip=True)) if opt else ""
|
|
200
|
+
for ta in form.find_all("textarea"):
|
|
201
|
+
if ta.get("name"):
|
|
202
|
+
fields[ta["name"]] = ta.get_text()
|
|
203
|
+
return form.get("action"), fields
|
|
204
|
+
|
|
205
|
+
def postback(
|
|
206
|
+
self,
|
|
207
|
+
page: Page,
|
|
208
|
+
event_target: str = "",
|
|
209
|
+
event_argument: str = "",
|
|
210
|
+
fields: dict | None = None,
|
|
211
|
+
submit: tuple[str, str] | None = None,
|
|
212
|
+
) -> Page:
|
|
213
|
+
"""Replay an ASP.NET postback from `page` (like changing a dropdown or clicking a button)."""
|
|
214
|
+
action, data = self.form_state(page.soup)
|
|
215
|
+
data["__EVENTTARGET"] = event_target
|
|
216
|
+
data["__EVENTARGUMENT"] = event_argument
|
|
217
|
+
if fields:
|
|
218
|
+
data.update(fields)
|
|
219
|
+
if submit:
|
|
220
|
+
data[submit[0]] = submit[1]
|
|
221
|
+
url = urljoin(page.url, action) if action else page.url
|
|
222
|
+
return self.post(url, data)
|
|
223
|
+
|
|
224
|
+
# ------------------------------------------------------------------ files
|
|
225
|
+
def fetch_bytes(self, url: str, max_bytes: int = 200 * 1024 * 1024) -> tuple[bytes, str]:
|
|
226
|
+
"""Download a file into memory. Returns (content, final_url)."""
|
|
227
|
+
resp = self._request("GET", url, stream=True)
|
|
228
|
+
resp.raise_for_status()
|
|
229
|
+
buf = bytearray()
|
|
230
|
+
for chunk in resp.iter_content(chunk_size=1 << 16):
|
|
231
|
+
buf.extend(chunk)
|
|
232
|
+
if len(buf) > max_bytes:
|
|
233
|
+
resp.close()
|
|
234
|
+
raise GiuError(f"File is larger than {max_bytes // (1024 * 1024)} MB")
|
|
235
|
+
return bytes(buf), resp.url
|
|
236
|
+
|
|
237
|
+
def download(self, url: str, dest: Path, overwrite: bool = False) -> tuple[Path, bool]:
|
|
238
|
+
"""Stream `url` to the file `dest`. Returns (path, downloaded) — False if it already existed."""
|
|
239
|
+
if dest.exists() and not overwrite:
|
|
240
|
+
return dest, False
|
|
241
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
resp = self._request("GET", url, stream=True)
|
|
243
|
+
resp.raise_for_status()
|
|
244
|
+
tmp = dest.with_name(dest.name + ".part")
|
|
245
|
+
with open(tmp, "wb") as fh:
|
|
246
|
+
for chunk in resp.iter_content(chunk_size=1 << 16):
|
|
247
|
+
fh.write(chunk)
|
|
248
|
+
tmp.replace(dest)
|
|
249
|
+
return dest, True
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def safe_filename(name: str) -> str:
|
|
253
|
+
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", name).strip(" .")
|
|
254
|
+
return name[:180] or "download"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
_client: GiuClient | None = None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def get_client() -> GiuClient:
|
|
261
|
+
global _client
|
|
262
|
+
if _client is None:
|
|
263
|
+
_client = GiuClient()
|
|
264
|
+
return _client
|