# api/views.py import logging from django.utils import timezone from rest_framework import status from rest_framework.decorators import api_view, renderer_classes from rest_framework.response import Response from blog.models import Category, Post, SiteInfo from explore import github as github_api from explore.llm import LLMError, analyze_repos, build_conditions, build_query, extract_spec from explore.models import Idea, Note, Repository, SearchSpec from .renderers import MarkdownRenderer logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # 序列化小工具 # --------------------------------------------------------------------------- def _bad(message, code, http_status=status.HTTP_400_BAD_REQUEST): return Response({"error": message, "code": code}, status=http_status) def _to_int(value, default, minimum, maximum): try: number = int(value) except (TypeError, ValueError): return default return max(minimum, min(number, maximum)) def _note_payload(note): return { "id": note.id, "content": note.content, "created_at": note.created_at.isoformat(), "repository_id": note.repository_id, } def _repo_payload(repo): return { "id": repo.id, "github_id": repo.github_id, "full_name": repo.full_name, "html_url": repo.html_url, "description": repo.description, "language": repo.language, "stars": repo.stars, "forks": repo.forks, "topics": repo.topics, "license": repo.license_name, "updated_at": repo.repo_updated_at.isoformat() if repo.repo_updated_at else None, "archived": repo.archived, "ai_analysis": repo.ai_analysis or {}, "notes": [_note_payload(note) for note in repo.notes.all()], } def _spec_payload(spec): return { "id": spec.id, "keywords": spec.keywords, "language": spec.language, "min_stars": spec.min_stars, "topic": spec.topic, "sort": spec.sort, "query": spec.query, "github_url": spec.github_url, "conditions": build_conditions(spec.language, spec.min_stars, spec.topic, spec.sort), "model": spec.model, "elapsed_ms": spec.elapsed_ms, } def _idea_payload(idea): return { "id": idea.id, "text": idea.text, "created_at": idea.created_at.isoformat(), } def _get_idea(idea_id): try: return Idea.objects.get(pk=int(idea_id)) except (Idea.DoesNotExist, TypeError, ValueError): return None def _read_note_content(request): content = str(request.data.get("content") or "").strip() if not content: return None, _bad("写点什么再记下", "note_empty") if len(content) > 2000: return None, _bad("单条思考最多 2000 字", "note_too_long") return content, None # --------------------------------------------------------------------------- # 站点地图(原有接口) # --------------------------------------------------------------------------- @api_view(["GET"]) @renderer_classes([MarkdownRenderer]) def sitemap_markdown(request): """生成站点地图的 Markdown 文本 分类按最早文章时间升序,文章按发布时间从小到大 """ site_name = "我的博客" try: site_info = SiteInfo.get_site_info() if site_info.about_title: site_name = site_info.about_title except Exception: pass lines = [f"# {site_name}", ""] categories = Category.objects.all().order_by("name") for cat in categories: posts = cat.posts.filter(status="published").order_by("published_at") lines.append(f"## {cat.name}") lines.append("") if posts.exists(): for post in posts: post_url = f"/post/{post.slug}/" lines.append(f"### [{post.title}]({post_url})") else: lines.append("- *暂无文章*") lines.append("") uncategorized = Post.objects.filter( categories__isnull=True, status="published" ).order_by("published_at") if uncategorized.exists(): lines.append("## 未分类") lines.append("") for post in uncategorized: post_url = f"/post/{post.slug}/" lines.append(f"### [{post.title}]({post_url})") lines.append("") return Response("\n".join(lines)) # --------------------------------------------------------------------------- # 拾源:想法 -> GitHub 检索条件 -> 仓库 # --------------------------------------------------------------------------- @api_view(["POST"]) def explore_extract(request): """想法入库,调用模型生成 GitHub 搜索条件(不搜索)""" if not isinstance(request.data, dict): return _bad("请求格式不对", "bad_payload") idea_text = str(request.data.get("idea") or "").strip() if len(idea_text) < 4: return _bad("再多描述一点你的想法", "idea_too_short") if len(idea_text) > 500: return _bad("想法太长了,请控制在 500 字以内", "idea_too_long") idea = None raw_idea_id = request.data.get("idea_id") if raw_idea_id not in (None, ""): idea = _get_idea(raw_idea_id) if idea is None: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) if idea.text != idea_text: idea.text = idea_text idea.save(update_fields=["text", "updated_at"]) else: idea = Idea.objects.create(text=idea_text) try: spec = extract_spec(idea_text) except LLMError as exc: logger.warning("explore extract failed code=%s idea=%r", exc.code, idea_text[:80]) return Response( {"error": exc.message, "code": exc.code, "idea_id": idea.id}, status=exc.status, ) spec_obj = SearchSpec.objects.create( idea=idea, keywords=spec["keywords"], language=spec["language"], min_stars=spec["min_stars"], topic=spec["topic"], sort=spec["sort"], query=spec["query"], github_url=spec["github_url"], model=spec["model"], elapsed_ms=spec["elapsed_ms"], ) logger.info( "explore extract ok: idea=%s keywords=%s language=%r stars=%s sort=%r", idea.id, spec["keywords"], spec["language"], spec["min_stars"], spec["sort"], ) payload = {"idea_id": idea.id, "spec_id": spec_obj.id} payload.update(_spec_payload(spec_obj)) return Response(payload) @api_view(["POST"]) def explore_query(request): """关键词被前端删改后,重拼检索式并更新这条想法最新的条件""" if not isinstance(request.data, dict): return _bad("请求格式不对", "bad_payload") idea = _get_idea(request.data.get("idea_id")) if idea is None: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) spec = idea.specs.first() if spec is None: return _bad("还没有检索条件,请先提炼一次", "spec_missing") keywords = request.data.get("keywords") if not isinstance(keywords, list): return _bad("关键词格式不对", "keywords_invalid") try: query_info = build_query( keywords, spec.language, spec.min_stars, spec.topic, spec.sort ) except ValueError as exc: return _bad(str(exc), "query_invalid") spec.keywords = query_info["keywords"] spec.query = query_info["query"] spec.github_url = query_info["github_url"] spec.save(update_fields=["keywords", "query", "github_url"]) payload = {"idea_id": idea.id, "spec_id": spec.id} payload.update(query_info) return Response(payload) @api_view(["POST"]) def explore_search(request): """按想法最新的检索条件(可被前端筛选覆盖)调用 GitHub 搜索并存仓库""" if not isinstance(request.data, dict): return _bad("请求格式不对", "bad_payload") idea = _get_idea(request.data.get("idea_id")) if idea is None: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) spec = idea.specs.first() if spec is None: return _bad("还没有检索条件,请先提炼一次", "spec_missing") count = _to_int(request.data.get("count"), 10, 1, 20) stars = _to_int(request.data.get("stars"), spec.min_stars, 0, 1_000_000) language = request.data.get("language", spec.language) language = str(language or "").strip() if language.lower() in {"all", "全部", "any"}: language = "" sort = str(request.data.get("sort", spec.sort) or "").strip().lower() if sort in {"best", "bestmatch", "relevance"}: sort = "" if sort not in {"stars", "updated"}: sort = "" try: query_info = build_query(spec.keywords, language, stars, spec.topic, sort) except ValueError as exc: return _bad(str(exc), "query_invalid") try: data = github_api.search_repositories( query_info["query"], sort=sort, per_page=count ) except github_api.GitHubError as exc: logger.warning("explore search failed: %s", exc) return Response({"error": exc.message, "code": exc.code}, status=exc.status) repos = [] for item in data["items"]: if not item["github_id"]: continue repo, _ = Repository.objects.update_or_create( idea=idea, github_id=item["github_id"], defaults={ "full_name": item["full_name"], "html_url": item["html_url"], "description": item["description"], "language": item["language"], "stars": item["stars"], "forks": item["forks"], "topics": item["topics"], "license_name": item["license"], "repo_updated_at": item["updated_at"], "archived": item["archived"], }, ) repos.append(repo) logger.info( "explore search: idea=%s q=%r total=%s shown=%s", idea.id, query_info["query"], data["total_count"], len(repos), ) return Response({ "idea_id": idea.id, "query": query_info["query"], "github_url": query_info["github_url"], "conditions": query_info["conditions"], "sort": sort, "per_page": count, "stars": stars, "language": language, "total_count": data["total_count"], "incomplete": data["incomplete"], "repositories": [_repo_payload(repo) for repo in repos], }) @api_view(["POST"]) def explore_analyze(request): """为当前这批仓库生成 AI 解读(润色 / 精髓 / 能做什么 / 可发散)""" if not isinstance(request.data, dict): return _bad("请求格式不对", "bad_payload") idea = _get_idea(request.data.get("idea_id")) if idea is None: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) repo_ids = request.data.get("repo_ids") if isinstance(repo_ids, list) and repo_ids: ids = [] for value in repo_ids[:10]: try: ids.append(int(value)) except (TypeError, ValueError): continue repos = list(Repository.objects.filter(idea=idea, id__in=ids)) else: repos = list(idea.repositories.all()[:10]) if not repos: return Response({"analyses": {}}) existing = {repo.id: repo.ai_analysis for repo in repos if repo.ai_analysis} missing = [repo for repo in repos if not repo.ai_analysis] if missing: payload = [{ "id": repo.id, "name": repo.full_name, "description": repo.description, "language": repo.language, "topics": repo.topics, "stars": repo.stars, } for repo in missing] try: analyses = analyze_repos(payload) except LLMError as exc: logger.warning("explore analyze failed code=%s idea=%s", exc.code, idea.id) return Response( { "error": exc.message, "code": exc.code, "analyses": {str(key): value for key, value in existing.items()}, }, status=exc.status, ) now = timezone.now() for repo in missing: analysis = analyses.get(repo.id) if not analysis: continue repo.ai_analysis = analysis repo.ai_analyzed_at = now repo.save(update_fields=["ai_analysis", "ai_analyzed_at"]) existing[repo.id] = analysis logger.info("explore analyze: idea=%s requested=%s ready=%s", idea.id, len(repos), len(existing)) return Response({"analyses": {str(key): value for key, value in existing.items()}}) @api_view(["GET"]) def explore_idea_detail(request, idea_id): """刷新页面/恢复现场:想法 + 最新条件 + 思考 + 已检索仓库""" try: idea = Idea.objects.prefetch_related( "specs", "notes", "repositories__notes" ).get(pk=idea_id) except Idea.DoesNotExist: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) spec = idea.specs.first() idea_notes = [note for note in idea.notes.all() if note.repository_id is None] return Response({ "idea": _idea_payload(idea), "spec": _spec_payload(spec) if spec else None, "notes": [_note_payload(note) for note in idea_notes], "repositories": [_repo_payload(repo) for repo in idea.repositories.all()], }) @api_view(["POST"]) def explore_idea_note_create(request, idea_id): """在想法下写一条「我的其他思考」""" idea = _get_idea(idea_id) if idea is None: return _bad("想法不存在", "idea_not_found", status.HTTP_404_NOT_FOUND) content, error = _read_note_content(request) if error: return error note = Note.objects.create(idea=idea, content=content) return Response(_note_payload(note), status=status.HTTP_201_CREATED) @api_view(["POST"]) def explore_repo_note_create(request, repo_id): """在某个仓库下写一条「我的其他思考」""" try: repo = Repository.objects.select_related("idea").get(pk=repo_id) except Repository.DoesNotExist: return _bad("仓库不存在", "repo_not_found", status.HTTP_404_NOT_FOUND) content, error = _read_note_content(request) if error: return error note = Note.objects.create(idea=repo.idea, repository=repo, content=content) return Response(_note_payload(note), status=status.HTTP_201_CREATED) @api_view(["DELETE"]) def explore_note_delete(request, note_id): try: note = Note.objects.get(pk=note_id) except Note.DoesNotExist: return _bad("思考不存在", "note_not_found", status.HTTP_404_NOT_FOUND) note.delete() return Response(status=status.HTTP_204_NO_CONTENT)