- 新增 explore 应用:Idea / SearchSpec / Repository / Note 及迁移 - Ollama 生成 GitHub 检索条件(language / stars / topic / sort),并批量解读仓库简介 - 接入 GitHub 仓库搜索 REST API,结果入库并按想法关联 - 想法级与仓库级「我的其他思考」,支持多条添加与删除 - 新增存档页:按想法 / 有想法的仓库两个视角,跨想法合并仓库 - 前端 /explore/ 四步流程、条件展示、筛选器、AI 解读目录、?idea= 恢复现场 - settings 增加 OLLAMA_* / GITHUB_* 配置
157 lines
5.0 KiB
Python
157 lines
5.0 KiB
Python
"""GitHub 仓库搜索 REST 客户端。
|
|
|
|
接口:GET https://api.github.com/search/repositories
|
|
只做「按检索式取仓库」,不克隆、不分析。
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import socket
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from django.conf import settings
|
|
from django.core.cache import cache
|
|
from django.utils.dateparse import parse_datetime
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CACHE_SECONDS = 600
|
|
MAX_PER_PAGE = 30
|
|
|
|
|
|
class GitHubError(Exception):
|
|
code = "github_error"
|
|
status = 502
|
|
|
|
def __init__(self, message, status=None):
|
|
super().__init__(message)
|
|
self.message = message
|
|
if status is not None:
|
|
self.status = status
|
|
|
|
|
|
class GitHubTimeout(GitHubError):
|
|
code = "github_timeout"
|
|
status = 504
|
|
|
|
def __init__(self):
|
|
super().__init__("GitHub 响应超时,请稍后重试")
|
|
|
|
|
|
class GitHubRateLimited(GitHubError):
|
|
code = "github_rate_limited"
|
|
status = 429
|
|
|
|
def __init__(self, message):
|
|
super().__init__(message)
|
|
|
|
|
|
def _headers():
|
|
headers = {
|
|
"Accept": "application/vnd.github+json",
|
|
"X-GitHub-Api-Version": "2022-11-28",
|
|
"User-Agent": "shiyuan-blog",
|
|
}
|
|
token = getattr(settings, "GITHUB_TOKEN", "")
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
return headers
|
|
|
|
|
|
def _normalize(item):
|
|
license_info = item.get("license") or {}
|
|
updated_raw = item.get("updated_at")
|
|
updated_at = parse_datetime(updated_raw) if updated_raw else None
|
|
|
|
return {
|
|
"github_id": item.get("id"),
|
|
"full_name": item.get("full_name") or "",
|
|
"html_url": item.get("html_url") or "",
|
|
"description": item.get("description") or "",
|
|
"language": item.get("language") or "",
|
|
"stars": int(item.get("stargazers_count") or 0),
|
|
"forks": int(item.get("forks_count") or 0),
|
|
"topics": item.get("topics") or [],
|
|
"license": license_info.get("spdx_id") or license_info.get("name") or "",
|
|
"updated_at": updated_at,
|
|
"archived": bool(item.get("archived")),
|
|
}
|
|
|
|
|
|
def search_repositories(query, sort="", per_page=7):
|
|
"""按 GitHub 检索式搜索仓库,返回 {total_count, incomplete, items}。"""
|
|
query = (query or "").strip()
|
|
if not query:
|
|
raise GitHubError("检索式为空", status=400)
|
|
|
|
try:
|
|
per_page = max(1, min(int(per_page or 7), MAX_PER_PAGE))
|
|
except (TypeError, ValueError):
|
|
per_page = 7
|
|
|
|
cache_key = "explore:gh:" + hashlib.sha1(
|
|
"{}|{}|{}".format(query, sort, per_page).encode("utf-8")
|
|
).hexdigest()
|
|
cached = cache.get(cache_key)
|
|
if cached is not None:
|
|
return cached
|
|
|
|
params = {"q": query, "per_page": per_page, "page": 1}
|
|
if sort in {"stars", "updated", "forks"}:
|
|
params["sort"] = sort
|
|
params["order"] = "desc"
|
|
|
|
url = "https://api.github.com/search/repositories?" + urllib.parse.urlencode(params)
|
|
request = urllib.request.Request(url, headers=_headers(), method="GET")
|
|
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=settings.GITHUB_TIMEOUT) as response:
|
|
raw = response.read()
|
|
except urllib.error.HTTPError as exc:
|
|
remaining = exc.headers.get("X-RateLimit-Remaining")
|
|
reset = exc.headers.get("X-RateLimit-Reset")
|
|
|
|
if exc.code in (403, 429) and (remaining == "0" or exc.code == 429):
|
|
wait_seconds = 60
|
|
if reset:
|
|
try:
|
|
wait_seconds = max(0, int(reset) - int(time.time()))
|
|
except (TypeError, ValueError):
|
|
pass
|
|
raise GitHubRateLimited(
|
|
"GitHub 搜索被限流了,约 {} 秒后恢复(未登录每分钟 10 次)".format(wait_seconds)
|
|
)
|
|
|
|
detail = exc.read().decode("utf-8", "replace")[:300]
|
|
logger.warning("GitHub search HTTP %s: %s", exc.code, detail)
|
|
if exc.code == 422:
|
|
raise GitHubError("GitHub 检索条件不合法", status=400) from exc
|
|
raise GitHubError("GitHub 搜索接口返回错误") from exc
|
|
except (socket.timeout, TimeoutError) as exc:
|
|
raise GitHubTimeout() from exc
|
|
except urllib.error.URLError as exc:
|
|
if isinstance(exc.reason, (socket.timeout, TimeoutError)):
|
|
raise GitHubTimeout() from exc
|
|
logger.warning("GitHub unreachable: %s", exc.reason)
|
|
raise GitHubError("连不上 GitHub") from exc
|
|
except OSError as exc:
|
|
logger.warning("GitHub network error: %s", exc)
|
|
raise GitHubError("连不上 GitHub") from exc
|
|
|
|
try:
|
|
data = json.loads(raw.decode("utf-8"))
|
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
raise GitHubError("GitHub 返回内容无法解析") from exc
|
|
|
|
result = {
|
|
"total_count": int(data.get("total_count") or 0),
|
|
"incomplete": bool(data.get("incomplete_results")),
|
|
"items": [_normalize(item) for item in data.get("items") or []],
|
|
}
|
|
cache.set(cache_key, result, CACHE_SECONDS)
|
|
return result
|