codeyear 0.2.14__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.
codeyear/server.py ADDED
@@ -0,0 +1,293 @@
1
+ """Small HTTP card service for public GitHub accounts.
2
+
3
+ Run ``codeyear serve`` locally or deploy the container to a Python host.
4
+ Only public GitHub data is read; private repositories still require the
5
+ local ``codeyear scan`` mode.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import sys
12
+ import threading
13
+ import time
14
+ from collections import OrderedDict
15
+ from datetime import date
16
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
17
+ from urllib.parse import parse_qs, urlparse
18
+
19
+ from .card import THEMES, build_svg
20
+ from .github_public import fetch_stats
21
+
22
+ USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$")
23
+ CACHE: OrderedDict[tuple, tuple[float, object]] = OrderedDict()
24
+ CACHE_LOCK = threading.Lock()
25
+ KEY_LOCKS: dict[tuple, threading.Lock] = {}
26
+ KEY_LOCKS_GUARD = threading.Lock()
27
+ CACHE_TTL = 3600
28
+ CACHE_MAX = 128
29
+ RATE: dict[str, tuple[float, int]] = {}
30
+ RATE_LOCK = threading.Lock()
31
+ RATE_WINDOW = 60
32
+ RATE_LIMIT = 60
33
+
34
+
35
+ def _allow(ip: str) -> bool:
36
+ now = time.time()
37
+ with RATE_LOCK:
38
+ if len(RATE) > 1024:
39
+ for key, (start, _count) in list(RATE.items()):
40
+ if now - start >= RATE_WINDOW:
41
+ RATE.pop(key, None)
42
+ start, count = RATE.get(ip, (now, 0))
43
+ if now - start >= RATE_WINDOW:
44
+ RATE[ip] = (now, 1)
45
+ return True
46
+ if count >= RATE_LIMIT:
47
+ return False
48
+ RATE[ip] = (start, count + 1)
49
+ return True
50
+
51
+
52
+ def _cached_stats(
53
+ username: str,
54
+ year: int,
55
+ token: str | None,
56
+ max_commits: int,
57
+ tz: str | None = None,
58
+ ):
59
+ tz_norm = (tz or "").strip().lower()
60
+ key = (
61
+ (username.lower(), year, max_commits, tz_norm)
62
+ if tz_norm
63
+ else (username.lower(), year, max_commits)
64
+ )
65
+ now = time.time()
66
+ with CACHE_LOCK:
67
+ item = CACHE.get(key)
68
+ if item and now - item[0] < CACHE_TTL:
69
+ CACHE.move_to_end(key)
70
+ return item[1]
71
+ if item:
72
+ CACHE.pop(key, None)
73
+
74
+ # Collapse concurrent misses for the same card. README <picture> blocks
75
+ # request both light and dark cards at once, which would otherwise trigger
76
+ # two full GitHub fetches.
77
+ with KEY_LOCKS_GUARD:
78
+ key_lock = KEY_LOCKS.setdefault(key, threading.Lock())
79
+ with key_lock:
80
+ now = time.time()
81
+ with CACHE_LOCK:
82
+ item = CACHE.get(key)
83
+ if item and now - item[0] < CACHE_TTL:
84
+ CACHE.move_to_end(key)
85
+ return item[1]
86
+ fetch_kwargs: dict = {
87
+ "token": token,
88
+ "max_commits": max_commits,
89
+ "quiet": True,
90
+ }
91
+ if tz:
92
+ fetch_kwargs["tz"] = tz
93
+ stats, _warnings, _login = fetch_stats(username, year, **fetch_kwargs)
94
+ with CACHE_LOCK:
95
+ CACHE[key] = (time.time(), stats)
96
+ CACHE.move_to_end(key)
97
+ while len(CACHE) > CACHE_MAX:
98
+ CACHE.popitem(last=False)
99
+ with KEY_LOCKS_GUARD:
100
+ if len(KEY_LOCKS) > CACHE_MAX * 2:
101
+ for old_key in list(KEY_LOCKS):
102
+ if old_key != key and not KEY_LOCKS[old_key].locked():
103
+ KEY_LOCKS.pop(old_key, None)
104
+ return stats
105
+
106
+
107
+ def _error_svg(message: str) -> str:
108
+ safe = (
109
+ message.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
110
+ )
111
+ return f"""<svg xmlns="http://www.w3.org/2000/svg" width="640" height="200">
112
+ <rect width="640" height="200" fill="#f5f2e9"/>
113
+ <text x="24" y="72" font-family="Georgia, serif" font-size="22" fill="#141413">CodeYear</text>
114
+ <text x="24" y="112" font-family="monospace" font-size="12" fill="#6f6a5e">{safe}</text>
115
+ <text x="24" y="140" font-family="monospace" font-size="11" fill="#73726c">public data only · try again or use local mode</text>
116
+ </svg>
117
+ """
118
+
119
+
120
+ class Handler(BaseHTTPRequestHandler):
121
+ token: str | None = None
122
+ max_commits: int = 200
123
+
124
+ def log_message(self, fmt: str, *args) -> None: # pragma: no cover
125
+ print(f"{self.address_string()} - {fmt % args}", file=sys.stderr)
126
+
127
+ def _send(self, status: int, body: str, content_type: str) -> None:
128
+ data = body.encode("utf-8")
129
+ self.send_response(status)
130
+ self.send_header("Content-Type", content_type)
131
+ self.send_header("Content-Length", str(len(data)))
132
+ self.send_header("Cache-Control",
133
+ "no-store" if status >= 400 else "public, max-age=3600")
134
+ self.send_header("Access-Control-Allow-Origin", "*")
135
+ self.end_headers()
136
+ self.wfile.write(data)
137
+
138
+ def do_GET(self) -> None:
139
+ parsed = urlparse(self.path)
140
+ if parsed.path == "/health":
141
+ self._send(200, "ok", "text/plain; charset=utf-8")
142
+ return
143
+ if parsed.path == "/":
144
+ self._send(200, LANDING, "text/html; charset=utf-8")
145
+ return
146
+ if parsed.path not in {"/card.svg", "/card-dark.svg"}:
147
+ self._send(404, "not found", "text/plain; charset=utf-8")
148
+ return
149
+
150
+ if not _allow(self.client_address[0]):
151
+ self._send(429, _error_svg("too many requests"), "image/svg+xml")
152
+ return
153
+
154
+ query = parse_qs(parsed.query)
155
+ username = (query.get("username") or [""])[0].strip()
156
+ if not USERNAME_RE.match(username):
157
+ self._send(400, _error_svg("invalid GitHub username"), "image/svg+xml")
158
+ return
159
+ try:
160
+ year = int((query.get("year") or [""])[0])
161
+ except ValueError:
162
+ year = date.today().year
163
+ if not 2008 <= year <= date.today().year + 1:
164
+ self._send(400, _error_svg("invalid year"), "image/svg+xml")
165
+ return
166
+
167
+ theme = (query.get("theme") or ["paper"])[0]
168
+ if theme not in THEMES:
169
+ theme = "paper"
170
+ lang = "en" if (query.get("lang") or ["zh"])[0] == "en" else "zh"
171
+ tz = (query.get("tz") or [""])[0].strip() or None
172
+ try:
173
+ stats = _cached_stats(
174
+ username, year, self.token, self.max_commits, tz=tz,
175
+ )
176
+ svg = build_svg(
177
+ stats, dark=parsed.path.endswith("-dark.svg"), theme=theme,
178
+ lang=lang,
179
+ )
180
+ except Exception as exc:
181
+ self._send(502, _error_svg(str(exc)), "image/svg+xml")
182
+ return
183
+ self._send(200, svg, "image/svg+xml; charset=utf-8")
184
+
185
+
186
+ LANDING = """<!doctype html>
187
+ <html lang="zh-CN">
188
+ <head>
189
+ <meta charset="utf-8">
190
+ <meta name="viewport" content="width=device-width,initial-scale=1">
191
+ <title>CodeYear · 在线卡片</title>
192
+ <style>
193
+ :root{--paper:#f5f2e9;--ink:#141413;--muted:#6f6a5e;--line:#d8d2c2;--acc:#c8552f}
194
+ *{box-sizing:border-box}
195
+ body{margin:0;background:var(--paper);color:var(--ink);
196
+ font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif}
197
+ .wrap{max-width:980px;margin:0 auto;padding:48px 28px 70px}
198
+ h1{font-family:Georgia,"Songti SC",serif;font-size:48px;font-weight:400;margin:0}
199
+ p{color:var(--muted);line-height:1.7}
200
+ .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:28px 0 18px}
201
+ input,select{background:white;border:1px solid var(--line);padding:9px 10px;
202
+ font:inherit;color:var(--ink);outline:none}
203
+ input{width:220px}
204
+ button{background:var(--acc);color:white;border:0;padding:10px 18px;
205
+ font:inherit;font-weight:600;cursor:pointer}
206
+ button.secondary{background:#ece8dc;color:var(--ink)}
207
+ .preview{border:1px solid var(--line);padding:12px;background:transparent;
208
+ min-height:120px;display:flex;align-items:center;justify-content:center}
209
+ img{max-width:100%;height:auto}
210
+ pre{white-space:pre-wrap;word-break:break-all;background:#ece8dc;padding:14px;
211
+ font-family:Consolas,monospace;font-size:12px;line-height:1.6}
212
+ .hint{font-size:12px}
213
+ </style>
214
+ </head>
215
+ <body>
216
+ <div class="wrap">
217
+ <h1>CodeYear</h1>
218
+ <p>输入一个公开 GitHub 用户名,生成一张可嵌入 Profile README 的年度卡片。
219
+ 只读公开仓库;私有仓库请运行本地版 <code>codeyear scan</code>。</p>
220
+
221
+ <div class="row">
222
+ <input id="user" placeholder="GitHub username" value="octocat">
223
+ <input id="year" type="number" value="__YEAR__" min="2008" max="__YEAR__" style="width:100px">
224
+ <select id="theme">
225
+ <option value="paper">纸色</option>
226
+ <option value="mono">黑白</option>
227
+ <option value="forest">森林</option>
228
+ <option value="ocean">海洋</option>
229
+ </select>
230
+ <select id="mode"><option value="light">浅色</option><option value="dark">深色</option></select>
231
+ <select id="lang"><option value="zh">中文</option><option value="en">English</option></select>
232
+ <button onclick="loadCard()">生成</button>
233
+ </div>
234
+
235
+ <div class="preview"><img id="card" alt="CodeYear card"></div>
236
+
237
+ <p class="hint">卡片会缓存 1 小时。公开数据受 GitHub API 限流影响;完整本地报告请安装 CodeYear。</p>
238
+
239
+ <h3>嵌入到 Profile README</h3>
240
+ <pre id="snippet"></pre>
241
+ <button class="secondary" onclick="copySnippet()">复制嵌入代码</button>
242
+ </div>
243
+ <script>
244
+ let current = "";
245
+ function loadCard() {
246
+ const user = document.getElementById("user").value.trim();
247
+ const year = document.getElementById("year").value || "__YEAR__";
248
+ const theme = document.getElementById("theme").value;
249
+ const mode = document.getElementById("mode").value;
250
+ const lang = document.getElementById("lang").value;
251
+ const base = location.origin;
252
+ const name = mode === "dark" ? "card-dark.svg" : "card.svg";
253
+ const langPart = lang === "en" ? "&lang=en" : "";
254
+ const qs = `username=${encodeURIComponent(user)}&year=${year}&theme=${theme}${langPart}`;
255
+ const url = `${base}/${name}?${qs}`;
256
+ document.getElementById("card").src = url + "&t=" + Date.now();
257
+ current = `<picture>
258
+ <source media="(prefers-color-scheme: dark)" srcset="${base}/card-dark.svg?${qs}">
259
+ <img src="${base}/card.svg?${qs}" width="640" alt="CodeYear ${year}">
260
+ </picture>`;
261
+ document.getElementById("snippet").textContent = current;
262
+ }
263
+ function copySnippet() {
264
+ navigator.clipboard.writeText(current).catch(() => {});
265
+ }
266
+ loadCard();
267
+ </script>
268
+ </body>
269
+ </html>
270
+ """
271
+
272
+
273
+ def serve(
274
+ host: str = "127.0.0.1",
275
+ port: int = 8000,
276
+ *,
277
+ token: str | None = None,
278
+ max_commits: int = 200,
279
+ ) -> int:
280
+ Handler.token = token
281
+ Handler.max_commits = max_commits
282
+ global LANDING
283
+ LANDING = LANDING.replace("__YEAR__", str(date.today().year))
284
+ httpd = ThreadingHTTPServer((host, port), Handler)
285
+ print(f"CodeYear card service: http://{host}:{port}", file=sys.stderr)
286
+ print(f"Endpoint: /card.svg?username=octocat&year={date.today().year}", file=sys.stderr)
287
+ try:
288
+ httpd.serve_forever()
289
+ except KeyboardInterrupt:
290
+ print("\n停止。", file=sys.stderr)
291
+ finally:
292
+ httpd.server_close()
293
+ return 0