Refactor avatar package, support default avatar fallback (#36788)

* Fix #34715
This commit is contained in:
wxiaoguang
2026-03-01 21:32:35 +08:00
committed by GitHub
parent 1592576fa5
commit 2c624d4deb
15 changed files with 205 additions and 276 deletions
+48 -54
View File
@@ -6,11 +6,14 @@ package web
import (
"errors"
"fmt"
"image/png"
"net/http"
"os"
"path"
"strings"
"code.gitea.io/gitea/modules/assetfs"
"code.gitea.io/gitea/modules/avatar"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@@ -22,79 +25,70 @@ import (
func avatarStorageHandler(storageSetting *setting.Storage, prefix string, objStore storage.ObjectStorage) http.HandlerFunc {
prefix = strings.Trim(prefix, "/")
funcInfo := routing.GetFuncInfo(avatarStorageHandler, prefix)
exeModTime := assetfs.GetExecutableModTime()
fallbackEtag := fmt.Sprintf(`"avatar-%s"`, exeModTime.Format("20060102150405"))
if storageSetting.ServeDirect() {
return func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet && req.Method != http.MethodHead {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if !strings.HasPrefix(req.URL.Path, "/"+prefix+"/") {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/")
rPath = util.PathJoinRelX(rPath)
u, err := objStore.URL(rPath, path.Base(rPath), req.Method, nil)
if err != nil {
if os.IsNotExist(err) || errors.Is(err, os.ErrNotExist) {
log.Warn("Unable to find %s %s", prefix, rPath)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
log.Error("Error whilst getting URL for %s %s. Error: %v", prefix, rPath, err)
http.Error(w, fmt.Sprintf("Error whilst getting URL for %s %s", prefix, rPath), http.StatusInternalServerError)
return
}
http.Redirect(w, req, u.String(), http.StatusTemporaryRedirect)
handleError := func(w http.ResponseWriter, req *http.Request, avatarPath string, err error) bool {
if err == nil {
return false
}
if errors.Is(err, os.ErrNotExist) || errors.Is(err, util.ErrNotExist) {
// if avatar doesn't exist, generate a random one and serve it with proper cache control headers
w.Header().Set("Content-Type", "image/png")
if !httpcache.HandleGenericETagPublicCache(req, w, fallbackEtag, &exeModTime) {
if req.Method == http.MethodGet {
img := avatar.RandomImageWithSize(96, []byte(avatarPath))
_ = png.Encode(w, img)
} // else: for HEAD request, just return the headers without body
}
} else {
// for internal errors, log the error and return 500
log.Error("Error when serving avatar %s: %s", req.URL.Path, err)
http.Error(w, "unable to serve avatar image", http.StatusInternalServerError)
}
return true
}
return func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet && req.Method != http.MethodHead {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if !strings.HasPrefix(req.URL.Path, "/"+prefix+"/") {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/")
rPath = util.PathJoinRelX(rPath)
if rPath == "" || rPath == "." {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
avatarPath, ok := strings.CutPrefix(req.URL.Path, "/"+prefix+"/")
if !ok {
http.Error(w, "invalid avatar path", http.StatusBadRequest)
return
}
avatarPath = util.PathJoinRelX(avatarPath)
if avatarPath == "" || avatarPath == "." {
http.Error(w, "not found", http.StatusNotFound)
return
}
fi, err := objStore.Stat(rPath)
if err != nil {
if os.IsNotExist(err) || errors.Is(err, os.ErrNotExist) {
log.Warn("Unable to find %s %s", prefix, rPath)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
if storageSetting.ServeDirect() {
// Old logic: no check for existence by Stat, so old code's "errors.Is(err, os.ErrNotExist)" didn't work.
// So in theory, it doesn't work with the non-existing avatar fallback, it just gets the URL and redirects to it.
// Checking "stat" requires one more request to the storage, which is inefficient.
// Workaround: disable "SERVE_DIRECT". Leave the problem to the future.
u, err := objStore.URL(avatarPath, path.Base(avatarPath), req.Method, nil)
if handleError(w, req, avatarPath, err) {
return
}
log.Error("Error whilst opening %s %s. Error: %v", prefix, rPath, err)
http.Error(w, fmt.Sprintf("Error whilst opening %s %s", prefix, rPath), http.StatusInternalServerError)
http.Redirect(w, req, u.String(), http.StatusTemporaryRedirect)
return
}
fr, err := objStore.Open(rPath)
if err != nil {
log.Error("Error whilst opening %s %s. Error: %v", prefix, rPath, err)
http.Error(w, fmt.Sprintf("Error whilst opening %s %s", prefix, rPath), http.StatusInternalServerError)
fr, err := objStore.Open(avatarPath)
if handleError(w, req, avatarPath, err) {
return
}
defer fr.Close()
fi, err := fr.Stat()
if handleError(w, req, avatarPath, err) {
return
}
httpcache.SetCacheControlInHeader(w.Header(), httpcache.CacheControlForPublicStatic())
http.ServeContent(w, req, path.Base(rPath), fi.ModTime(), fr)
http.ServeContent(w, req, path.Base(avatarPath), fi.ModTime(), fr)
}
}
+1 -1
View File
@@ -187,7 +187,7 @@ func ServeAttachment(ctx *context.Context, uuid string) {
}
}
if httpcache.HandleGenericETagCache(ctx.Req, ctx.Resp, `"`+attach.UUID+`"`) {
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+attach.UUID+`"`, attach.CreatedUnix.AsTimePtr()) {
return
}
+2 -2
View File
@@ -20,7 +20,7 @@ import (
// ServeBlobOrLFS download a git.Blob redirecting to LFS if necessary
func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified *time.Time) error {
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return nil
}
@@ -48,7 +48,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified *time.Tim
closed = true
return common.ServeBlob(ctx.Base, ctx.Repo.Repository, ctx.Repo.TreePath, blob, lastModified)
}
if httpcache.HandleGenericETagCache(ctx.Req, ctx.Resp, `"`+pointer.Oid+`"`) {
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+pointer.Oid+`"`, meta.UpdatedUnix.AsTimePtr()) {
return nil
}