Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions internal/aistudio/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -1187,8 +1187,16 @@ func (s *PooledService) UploadInlineMediaToLease(
drive := s.client.transport.(DriveTransport)
uploadCtx, cancelUploads := context.WithCancel(targetCtx)
resultChannel := make(chan uploadResult, len(pending))
sem := make(chan struct{}, min(len(pending), 4))
for index, job := range pending {
go func(index int, job uploadJob) {
select {
case sem <- struct{}{}:
case <-uploadCtx.Done():
resultChannel <- uploadResult{index: index, err: uploadCtx.Err()}
return
}
defer func() { <-sem }()
file, err := drive.UploadDrive(uploadCtx, targetID, token, UploadRequest{
AccountID: targetID,
Name: job.name,
Expand Down
2 changes: 1 addition & 1 deletion internal/aistudio/video_duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (scan *mp4Duration) Write(data []byte) (int, error) {
take := min(int64(len(data)), scan.moovLeft)
scan.moov, scan.moovLeft, data = append(scan.moov, data[:take]...), scan.moovLeft-take, data[take:]
if scan.moovLeft == 0 {
scan.duration, scan.done = mvhdDuration(scan.moov), true
scan.duration, scan.done, scan.moov = mvhdDuration(scan.moov), true, nil
}
case scan.skip > 0:
take := min(int64(len(data)), scan.skip)
Expand Down
5 changes: 4 additions & 1 deletion internal/api/admin_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,10 @@ func (auth *adminAuth) handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
limit := int64(1 << 20)
if r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/api/prompts/") {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/api/prompts/media":
limit = openAIFileMaxBytes
case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/api/prompts/"):
limit = maxPublicBodyBytes
}
r.Body = http.MaxBytesReader(w, r.Body, limit)
Expand Down
23 changes: 22 additions & 1 deletion internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,30 @@ type errorCodeProvider interface {
ErrorCode() string
}

// readRequestBody 读取请求正文,已知 ContentLength 时在上限内预分配缓冲
func readRequestBody(r *http.Request, maxPrealloc int64) ([]byte, error) {
if r.ContentLength <= 0 || maxPrealloc <= 0 {
return io.ReadAll(r.Body)
}
buf := make([]byte, 0, min(r.ContentLength, maxPrealloc)+1)
for {
if len(buf) == cap(buf) {
buf = append(buf, 0)[:len(buf)]
}
n, err := r.Body.Read(buf[len(buf):cap(buf)])
buf = buf[:len(buf)+n]
if errors.Is(err, io.EOF) {
return buf, nil
}
if err != nil {
return buf, err
}
}
}

// decodeJSON 把请求正文解码为一个 JSON 值;读取或解码失败时以同一正文与读取错误逐段解码,返回其错误
func decodeJSON(r *http.Request, target any) error {
body, readErr := io.ReadAll(r.Body)
body, readErr := readRequestBody(r, 1<<20)
if readErr == nil && json.Unmarshal(body, target) == nil {
return nil
}
Expand Down
4 changes: 3 additions & 1 deletion internal/api/gemini.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ func (s *server) handleGeminiAction(w http.ResponseWriter, r *http.Request) {
writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error())
return
}
request.Contents, request.SystemInstruction = nil, nil
cache, ok := s.applyGeminiCache(w, request.CachedContent, &generateRequest)
if !ok {
return
Expand Down Expand Up @@ -521,7 +522,7 @@ func (s *server) handleGeminiAction(w http.ResponseWriter, r *http.Request) {

// decodeGeminiJSON 读取请求体,按 proto3 JSON 规则统一字段名后解码到 target
func decodeGeminiJSON(r *http.Request, target any) error {
body, err := io.ReadAll(r.Body)
body, err := readRequestBody(r, 8<<20)
if err == nil {
body, err = geminiCamelKeys(body)
}
Expand Down Expand Up @@ -1050,6 +1051,7 @@ func mapGeminiParts(input []geminiPart) ([]aistudio.Part, bool, error) {
if err != nil {
return nil, false, fmt.Errorf("inlineData.data: %w", err)
}
inline.Data = ""
mimeType, data := normalizeImagePayload(attachmentMIME(mime, inline.DisplayName, data), data)
parts = append(parts, aistudio.Part{
InlineData: aistudio.NewBlob(mimeType, data),
Expand Down
64 changes: 63 additions & 1 deletion internal/api/prompts.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ import (
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"

"github.com/Mag1cFall/AIStudio2API/internal/aistudio"
Expand Down Expand Up @@ -48,14 +52,16 @@ type SystemInstructionPreset struct {
Text string `json:"text"`
}

// PromptStore 保存 Playground 对话与系统指令预设
// PromptStore 保存 Playground 对话、附件媒体与系统指令预设
type PromptStore interface {
Prompts(ctx context.Context, pageSize int, pageToken string) ([]PromptSummary, string, error)
Prompt(context.Context, string) (Prompt, error)
SavePrompt(context.Context, Prompt) (PromptSummary, error)
RenamePrompt(ctx context.Context, id, title, description string) (PromptSummary, error)
CopyPrompt(ctx context.Context, source, id, title string) (PromptSummary, error)
DeletePrompt(context.Context, string) error
SaveMedia(ctx context.Context, mimeType string, content io.Reader) (string, error)
OpenMedia(ctx context.Context, id string) (*os.File, string, error)
SystemInstructions(context.Context) ([]SystemInstructionPreset, error)
SaveSystemInstruction(context.Context, SystemInstructionPreset) error
DeleteSystemInstruction(context.Context, string) error
Expand All @@ -65,6 +71,8 @@ func (s *server) registerPrompts(mux *http.ServeMux) {
mux.HandleFunc("GET /api/prompts/system-instructions", s.handleSystemInstructions)
mux.HandleFunc("PUT /api/prompts/system-instructions/{id}", s.handleSaveSystemInstruction)
mux.HandleFunc("DELETE /api/prompts/system-instructions/{id}", s.handleDeleteSystemInstruction)
mux.HandleFunc("POST /api/prompts/media", s.handleUploadPromptMedia)
mux.HandleFunc("GET /api/prompts/media/{id}", s.handlePromptMedia)
mux.HandleFunc("GET /api/prompts", s.handlePrompts)
mux.HandleFunc("GET /api/prompts/{id}", s.handlePrompt)
mux.HandleFunc("PUT /api/prompts/{id}", s.handleSavePrompt)
Expand Down Expand Up @@ -214,6 +222,60 @@ func (s *server) handleDeletePrompt(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}

// handleUploadPromptMedia 流式保存对话附件媒体并返回按内容计算的媒体 ID
func (s *server) handleUploadPromptMedia(w http.ResponseWriter, r *http.Request) {
mimeType := strings.TrimSpace(r.Header.Get("Content-Type"))
if parsed, params, err := mime.ParseMediaType(mimeType); err == nil && parsed != "" {
if formatted := mime.FormatMediaType(parsed, params); formatted != "" {
mimeType = formatted
} else {
mimeType = parsed
}
} else {
mimeType = "application/octet-stream"
}
id, err := s.config.Prompts.SaveMedia(r.Context(), mimeType, r.Body)
if err != nil {
var maxBytes *http.MaxBytesError
if errors.As(err, &maxBytes) {
writeAdminError(w, http.StatusRequestEntityTooLarge, "file_too_large", "Attachment exceeds 512 MB")
return
}
writeAdminError(w, http.StatusInternalServerError, "prompt_store_failed", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]string{"id": id})
}

// handlePromptMedia 流式返回已保存的对话附件媒体,支持浏览器 Range 播放与跳转
func (s *server) handlePromptMedia(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
file, mimeType, err := s.config.Prompts.OpenMedia(r.Context(), id)
if err != nil {
writePromptError(w, err)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "prompt_store_failed", err.Error())
return
}
w.Header().Set("Content-Type", mimeType)
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
if mimeType == "application/pdf" || strings.HasPrefix(mimeType, "application/pdf;") {
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
} else {
w.Header().Set("Content-Security-Policy", "sandbox; frame-ancestors 'self'")
}
if info.Size() == 0 {
w.Header().Set("Content-Length", "0")
w.WriteHeader(http.StatusOK)
return
}
http.ServeContent(w, r, id, info.ModTime(), file)
}

// handleSystemInstructions 返回保存在对话库中的系统指令预设列表
func (s *server) handleSystemInstructions(w http.ResponseWriter, r *http.Request) {
presets, err := s.config.Prompts.SystemInstructions(r.Context())
Expand Down
11 changes: 9 additions & 2 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,13 +380,20 @@ func rootHandler(apiHandler http.Handler) http.Handler {
return securityHeaders(root)
}

// compressAdmin 以 gzip 压缩管理接口发给接受 gzip 的客户端的 JSON、CSV 与事件流响应
// compressAdmin 以 gzip 压缩管理接口发给接受 gzip 的客户端的 JSON、CSV 与事件流响应,媒体流原样输出以支持 Range
func compressAdmin(next http.Handler) http.Handler {
wrap, err := gzhttp.NewWrapper(gzhttp.ContentTypes([]string{"application/json", "text/csv", "text/event-stream"}))
if err != nil {
panic(err)
}
return wrap(next)
compressed := wrap(next)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/prompts/media/") {
next.ServeHTTP(w, r)
return
}
compressed.ServeHTTP(w, r)
})
}

// securityHeaders 禁止页面被其他站点嵌入并关闭 MIME 嗅探与 Referer
Expand Down
Loading