Files
ONE/backend/internal/model/model.go
T
Sakurasan 34f0faedcc 文件上传:R2 对象存储 + 后台文件管理 + 编辑器/封面联动
存储抽象(internal/storage,新包)
- BlobStore 接口(Put / Open / Delete)+ 两个实现:R2(aws-sdk-go-v2 走
  R2 的 S3 兼容 API,path-style、region auto)与本地磁盘(DataDir/uploads,
  零配置兜底)。选择:Endpoint / S3Api / Bucket / AccessKey / SecretAccessKey
  齐全 → R2,缺任一项回落本地并在启动日志提示缺失的字段名(只报名字不报值)
- 端点 URL 里的路径段不交给 SDK:path-style 下它会被折进对象 key,
  导致「数据库 key」和「实际对象 key」对不上(直链 404,实测复现)。
  EndpointKeyPrefix 提取路径段给上传 handler 拼进 key,StripEndpointPath
  只取 scheme://host 给 SDK——数据库 / 存储端 / 直链三方一致

数据与 API
- files 表:id / key(唯一) / name / mime / size / sha256 / store(r2|local) /
  created_at;URL 不入库,按「store 来源 + PublicBase」响应时解析,
  切存储端不破坏存量链接
- POST /api/admin/files:multipart 多文件,单文件 ≤50MB(MaxBytesReader 64MB);
  类型白名单 = 图片(jpg/png/webp/gif/avif)+ 附件(pdf/zip/txt),
  扩展名 + http.DetectContentType 双重校验(实测拦截随机字节改名 .png),
  SVG 拒绝(同源脚本);内容 sha256 做 key(2026/09/{哈希前12位}{扩展名}),
  同内容重复上传自动去重复用
- GET /api/admin/files(分页 + 文件名搜索)、DELETE /{id}(先删对象再删行,
  存储端失败保留行可重试)
- 公开路由 GET /uploads/{key}(main.go 挂载):按 key 查行、存储层流式返回,
  Cache-Control immutable + ETag 304;R2 + PublicBase 时 302 直链(后端不出流量)
- URL 解析:FileURL(store, key, PublicBase)——R2 且配了公开域名走直链,
  否则 /uploads/ 流式

后台文件管理页(FilesView,「工作台 → 文件」)
- 点击 / 拖拽多选上传(uploadFiles 走 FormData 裸 fetch,401 广播与
  request() 一致);缩略图卡片网格(图片出图、其他出类型占位);
  复制链接(clipboard,非 https 回落 prompt)/ 打开 / 删除(确认提示);
  分页、loading/empty 沿用既有模式

编辑器联动(EditorView)
- 封面:URL 输入框旁「上传」按钮,选图自动填 cover_url
- wysiwyg:Crepe ImageBlock 官方 onUpload 钩子——粘贴 / 拖拽 / 插图
  全部走上传,返回 URL 后由 Crepe 插节点
- Markdown 模式:插图弹层加「上传」按钮 + 编辑器粘贴 / 拖拽图片,
  上传后在原光标处插入 ![](url)(异步上传先记光标位,逐张追踪偏移)

.env.example
- 模板入库(无敏感值):Endpoint = 公开访问域名(直链)、S3Api = 上传端点、
  Bucket / AccessKey / SecretAccessKey

验证
- 本地兜底全流程:上传 201、同内容去重复用、随机字节改名 .png 被
  内容嗅探拒绝、.svg 拒绝、公开路由 immutable 缓存头 + 内容一致、
  删除后存储与公开路由双清 404
- R2 真实链路(站主 .env):上传 store=r2、直链 200(过程中定位并修复
  S3Api 路径段折进 key 导致的直链 404,见 EndpointKeyPrefix)
- 后端 go build/test/vet 全绿;前端构建通过
2026-09-27 16:26:11 +08:00

189 lines
6.6 KiB
Go

package model
// Post kinds. "long" is a normal article; "short" is a Twitter-like note
// with no title shown in the timeline.
const (
KindLong = "long"
KindShort = "short"
)
const (
StatusDraft = "draft"
StatusPublished = "published"
)
type Post struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Slug string `json:"slug"`
Summary string `json:"summary"`
CoverURL string `json:"cover_url"`
ContentMd string `json:"content_md,omitempty"`
ContentHTML string `json:"content_html"`
Status string `json:"status"`
PublishedAt string `json:"published_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ReadingMinutes int `json:"reading_minutes"`
// ContentLen 是正文字符数:列表接口不返回全文,但后台列表要显示字数。
ContentLen int64 `json:"content_len"`
Tags []string `json:"tags"`
}
type PostInput struct {
Kind string `json:"kind"`
Title string `json:"title"`
Slug string `json:"slug"`
Summary string `json:"summary"`
CoverURL string `json:"cover_url"`
ContentMd string `json:"content_md"`
Status string `json:"status"`
PublishedAt string `json:"published_at"`
Tags []string `json:"tags"`
ReadingMinutes *int `json:"reading_minutes"`
}
type Tag struct {
ID int64 `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Color string `json:"color"`
Count int `json:"count"`
}
// Project is a showcase entry rendered on the public /projects page. It links
// out to an external homepage and (optionally) a source repository.
type Project struct {
ID int64 `json:"id"`
Title string `json:"title"`
Slug string `json:"slug"`
Summary string `json:"summary"`
CoverURL string `json:"cover_url"`
URL string `json:"url"`
RepoURL string `json:"repo_url"`
Status string `json:"status"`
Position int `json:"position"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// ProjectInput carries the editable fields for a project. A blank Slug or
// Status is filled in by the store (slug from Title, status defaults to
// published) so the admin UI can omit them.
type ProjectInput struct {
Title string `json:"title"`
Slug string `json:"slug"`
Summary string `json:"summary"`
CoverURL string `json:"cover_url"`
URL string `json:"url"`
RepoURL string `json:"repo_url"`
Status string `json:"status"`
Position int `json:"position"`
}
type ArchiveMonth struct {
Month string `json:"month"`
Posts []Post `json:"posts"`
}
type ArchiveYear struct {
Year string `json:"year"`
Months []ArchiveMonth `json:"months"`
Count int `json:"count"`
}
type Page struct {
Items []Post `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
// File 是一条上传文件的索引行。内容本体在对象存储里(store 字段记来源:
// r2 | local),key 是存储端的对象名,URL 由 API 层按「来源 + PublicBase」
// 在响应时解析——切存储端不破坏存量链接。
type File struct {
ID int64 `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Mime string `json:"mime"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
Store string `json:"store"`
URL string `json:"url"`
CreatedAt string `json:"created_at"`
}
// FilePage 是文件管理的分页容器(Items 用 File,与文章的 Page 区分开)。
type FilePage struct {
Items []File `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
// Dashboard is the snapshot rendered on /admin (homepage).
type Dashboard struct {
TotalPosts int `json:"total_posts"`
PublishedPosts int `json:"published_posts"`
DraftPosts int `json:"draft_posts"`
ShortPosts int `json:"short_posts"`
LongPosts int `json:"long_posts"`
TotalTags int `json:"total_tags"`
TotalWords int `json:"total_words"`
RecentPosts []Post `json:"recent_posts"`
RecentDrafts []Post `json:"recent_drafts"`
TopTags []Tag `json:"top_tags"`
PublishedByMonth []MonthBucket `json:"published_by_month"`
}
type MonthBucket struct {
Month string `json:"month"` // "YYYY-MM"
Count int `json:"count"`
}
// SocialLink 是站主在后台填写的社交 / 源码入口(label + url),
// 前台渲染成图标或文字链接。icon 不入库 —— 由前端按 url 域名推导。
type SocialLink struct {
Label string `json:"label"`
URL string `json:"url"`
}
type Settings struct {
SiteTitle string `json:"site_title"`
SiteDesc string `json:"site_desc"`
AuthorName string `json:"author_name"`
AuthorBio string `json:"author_bio"`
FooterNote string `json:"footer_note"`
ICPLicense string `json:"icp"`
PostsPerPage int `json:"posts_per_page"`
// SocialLinks 以 JSON 数组形式存在 settings KV 里(key: social_links),
// 解析失败/为空时前台拿到空数组,区块自动隐藏。
SocialLinks []SocialLink `json:"social_links"`
// LightSkinID is the front-end skin used when the client (or system)
// prefers light. Valid values: paper / sage / rose.
// Dark side is fixed to ink for now — kept implicit so we can add
// dark variants later without breaking clients.
LightSkinID string `json:"light_skin_id"`
// ThemeID is kept for backward compatibility with older clients that
// only know about a single skin. settingsFromMap falls back to it
// when LightSkinID is empty.
ThemeID string `json:"theme_id,omitempty"`
// UIID selects which front-end UI the whole site renders. Valid values
// are "classic" (the original minimalist layout) and "vivid" (the
// livelier one). The admin UI is unaffected by this — it always uses the
// --admin-* tokens.
UIID string `json:"ui_id"`
// CustomCSS holds owner-authored stylesheets keyed by page section
// ("global", "home", "post", "archive", "tags", "projects", "about").
// Only injected for the vivid UI, and never on /admin. Always non-nil so
// the JSON response is {} rather than null.
CustomCSS map[string]string `json:"custom_css"`
// CustomJS holds owner-authored JavaScript (analytics snippets like
// Google Analytics / Plausible / Umami). Injected on every public page
// of either UI, never on /admin. Stored raw — it's the owner's own code,
// sanitizing it would only break the snippet.
CustomJS string `json:"custom_js"`
}