i18n: logs in bootstrapper and response code in middleware

pull/1491/head
HFO4 2 years ago
parent 16d17ac1e6
commit db23f4061d

@ -10,9 +10,9 @@ func RunScript(name string) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
if err := invoker.RunDBScript(name, ctx); err != nil { if err := invoker.RunDBScript(name, ctx); err != nil {
util.Log().Error("数据库脚本执行失败: %s", err) util.Log().Error("Failed to execute database script: %s", err)
return return
} }
util.Log().Info("数据库脚本 [%s] 执行完毕", name) util.Log().Info("Finish executing database script %q.", name)
} }

@ -46,13 +46,13 @@ func (b *GinFS) Exists(prefix string, filepath string) bool {
// InitStatic 初始化静态资源文件 // InitStatic 初始化静态资源文件
func InitStatic(statics fs.FS) { func InitStatic(statics fs.FS) {
if util.Exists(util.RelativePath(StaticFolder)) { if util.Exists(util.RelativePath(StaticFolder)) {
util.Log().Info("检测到 statics 目录存在,将使用此目录下的静态资源文件") util.Log().Info("Folder with name \"statics\" already exists, it will be used to serve static files.")
StaticFS = static.LocalFile(util.RelativePath("statics"), false) StaticFS = static.LocalFile(util.RelativePath("statics"), false)
} else { } else {
// 初始化静态资源 // 初始化静态资源
embedFS, err := fs.Sub(statics, "assets/build") embedFS, err := fs.Sub(statics, "assets/build")
if err != nil { if err != nil {
util.Log().Panic("无法初始化静态资源, %s", err) util.Log().Panic("Failed to initialize static resources: %s", err)
} }
StaticFS = &GinFS{ StaticFS = &GinFS{
@ -62,19 +62,19 @@ func InitStatic(statics fs.FS) {
// 检查静态资源的版本 // 检查静态资源的版本
f, err := StaticFS.Open("version.json") f, err := StaticFS.Open("version.json")
if err != nil { if err != nil {
util.Log().Warning("静态资源版本标识文件不存在,请重新构建或删除 statics 目录") util.Log().Warning("Missing version identifier file in static resources, please delete \"statics\" folder and rebuild it.")
return return
} }
b, err := io.ReadAll(f) b, err := io.ReadAll(f)
if err != nil { if err != nil {
util.Log().Warning("无法读取静态资源文件版本,请重新构建或删除 statics 目录") util.Log().Warning("Failed to read version identifier file in static resources, please delete \"statics\" folder and rebuild it.")
return return
} }
var v staticVersion var v staticVersion
if err := json.Unmarshal(b, &v); err != nil { if err := json.Unmarshal(b, &v); err != nil {
util.Log().Warning("无法解析静态资源文件版本, %s", err) util.Log().Warning("Failed to parse version identifier file in static resources: %s", err)
return return
} }
@ -84,12 +84,12 @@ func InitStatic(statics fs.FS) {
} }
if v.Name != staticName { if v.Name != staticName {
util.Log().Warning("静态资源版本不匹配,请重新构建或删除 statics 目录") util.Log().Warning("Static resource version mismatch, please delete \"statics\" folder and rebuild it.")
return return
} }
if v.Version != conf.RequiredStaticVersion { if v.Version != conf.RequiredStaticVersion {
util.Log().Warning("静态资源版本不匹配 [当前 %s, 需要: %s],请重新构建或删除 statics 目录", v.Version, conf.RequiredStaticVersion) util.Log().Warning("Static resource version mismatch [Current %s, Desired: %s]please delete \"statics\" folder and rebuild it.", v.Version, conf.RequiredStaticVersion)
return return
} }
} }
@ -99,13 +99,13 @@ func Eject(statics fs.FS) {
// 初始化静态资源 // 初始化静态资源
embedFS, err := fs.Sub(statics, "assets/build") embedFS, err := fs.Sub(statics, "assets/build")
if err != nil { if err != nil {
util.Log().Panic("无法初始化静态资源, %s", err) util.Log().Panic("Failed to initialize static resources: %s", err)
} }
var walk func(relPath string, d fs.DirEntry, err error) error var walk func(relPath string, d fs.DirEntry, err error) error
walk = func(relPath string, d fs.DirEntry, err error) error { walk = func(relPath string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
return errors.Errorf("无法获取[%s]的信息, %s, 跳过...", relPath, err) return errors.Errorf("Failed to read info of %q: %s, skipping...", relPath, err)
} }
if !d.IsDir() { if !d.IsDir() {
@ -114,13 +114,13 @@ func Eject(statics fs.FS) {
defer out.Close() defer out.Close()
if err != nil { if err != nil {
return errors.Errorf("无法创建文件[%s], %s, 跳过...", relPath, err) return errors.Errorf("Failed to create file %q: %s, skipping...", relPath, err)
} }
util.Log().Info("导出 [%s]...", relPath) util.Log().Info("Ejecting %q...", relPath)
obj, _ := embedFS.Open(relPath) obj, _ := embedFS.Open(relPath)
if _, err := io.Copy(out, bufio.NewReader(obj)); err != nil { if _, err := io.Copy(out, bufio.NewReader(obj)); err != nil {
return errors.Errorf("无法写入文件[%s], %s, 跳过...", relPath, err) return errors.Errorf("Cannot write file %q: %s, skipping...", relPath, err)
} }
} }
return nil return nil
@ -129,8 +129,8 @@ func Eject(statics fs.FS) {
// util.Log().Info("开始导出内置静态资源...") // util.Log().Info("开始导出内置静态资源...")
err = fs.WalkDir(embedFS, ".", walk) err = fs.WalkDir(embedFS, ".", walk)
if err != nil { if err != nil {
util.Log().Error("导出内置静态资源遇到错误:%s", err) util.Log().Error("Error occurs while ejecting static resources: %s", err)
return return
} }
util.Log().Info("内置静态资源导出完成") util.Log().Info("Finish ejecting static resources.")
} }

@ -142,18 +142,18 @@ func uploadCallbackCheck(c *gin.Context, policyType string) serializer.Response
// 验证 Callback Key // 验证 Callback Key
sessionID := c.Param("sessionID") sessionID := c.Param("sessionID")
if sessionID == "" { if sessionID == "" {
return serializer.ParamErr("Session ID 不能为空", nil) return serializer.ParamErr("Session ID cannot be empty", nil)
} }
callbackSessionRaw, exist := cache.Get(filesystem.UploadSessionCachePrefix + sessionID) callbackSessionRaw, exist := cache.Get(filesystem.UploadSessionCachePrefix + sessionID)
if !exist { if !exist {
return serializer.ParamErr("上传会话不存在或已过期", nil) return serializer.Err(serializer.CodeUploadSessionExpired, "上传会话不存在或已过期", nil)
} }
callbackSession := callbackSessionRaw.(serializer.UploadSession) callbackSession := callbackSessionRaw.(serializer.UploadSession)
c.Set(filesystem.UploadSessionCtx, &callbackSession) c.Set(filesystem.UploadSessionCtx, &callbackSession)
if callbackSession.Policy.Type != policyType { if callbackSession.Policy.Type != policyType {
return serializer.Err(serializer.CodePolicyNotAllowed, "Policy not supported", nil) return serializer.Err(serializer.CodePolicyNotAllowed, "", nil)
} }
// 清理回调会话 // 清理回调会话
@ -162,7 +162,7 @@ func uploadCallbackCheck(c *gin.Context, policyType string) serializer.Response
// 查找用户 // 查找用户
user, err := model.GetActiveUserByID(callbackSession.UID) user, err := model.GetActiveUserByID(callbackSession.UID)
if err != nil { if err != nil {
return serializer.Err(serializer.CodeCheckLogin, "找不到用户", err) return serializer.Err(serializer.CodeUserNotFound, "", err)
} }
c.Set(filesystem.UserCtx, &user) c.Set(filesystem.UserCtx, &user)
return serializer.Response{} return serializer.Response{}
@ -194,14 +194,14 @@ func QiniuCallbackAuth() gin.HandlerFunc {
mac := qbox.NewMac(session.Policy.AccessKey, session.Policy.SecretKey) mac := qbox.NewMac(session.Policy.AccessKey, session.Policy.SecretKey)
ok, err := mac.VerifyCallback(c.Request) ok, err := mac.VerifyCallback(c.Request)
if err != nil { if err != nil {
util.Log().Debug("无法验证回调请求,%s", err) util.Log().Debug("Failed to verify callback request: %s", err)
c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "无法验证回调请求"}) c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "Failed to verify callback request."})
c.Abort() c.Abort()
return return
} }
if !ok { if !ok {
c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "回调签名无效"}) c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "Invalid signature."})
c.Abort() c.Abort()
return return
} }
@ -215,8 +215,8 @@ func OSSCallbackAuth() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
err := oss.VerifyCallbackSignature(c.Request) err := oss.VerifyCallbackSignature(c.Request)
if err != nil { if err != nil {
util.Log().Debug("回调签名验证失败,%s", err) util.Log().Debug("Failed to verify callback request: %s", err)
c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "回调签名验证失败"}) c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "Failed to verify callback request."})
c.Abort() c.Abort()
return return
} }
@ -250,7 +250,7 @@ func UpyunCallbackAuth() gin.HandlerFunc {
// 计算正文MD5 // 计算正文MD5
actualContentMD5 := fmt.Sprintf("%x", md5.Sum(body)) actualContentMD5 := fmt.Sprintf("%x", md5.Sum(body))
if actualContentMD5 != contentMD5 { if actualContentMD5 != contentMD5 {
c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "MD5不一致"}) c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "MD5 mismatch."})
c.Abort() c.Abort()
return return
} }
@ -265,7 +265,7 @@ func UpyunCallbackAuth() gin.HandlerFunc {
// 对比签名 // 对比签名
if signature != actualSignature { if signature != actualSignature {
c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "鉴权失败"}) c.JSON(401, serializer.GeneralUploadCallbackFailed{Error: "Signature not match"})
c.Abort() c.Abort()
return return
} }
@ -289,7 +289,7 @@ func IsAdmin() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
user, _ := c.Get("user") user, _ := c.Get("user")
if user.(*model.User).Group.ID != 1 && user.(*model.User).ID != 1 { if user.(*model.User).Group.ID != 1 && user.(*model.User).ID != 1 {
c.JSON(200, serializer.Err(serializer.CodeAdminRequired, "您不是管理组成员", nil)) c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "", nil))
c.Abort() c.Abort()
return return
} }

@ -25,7 +25,7 @@ func UseSlaveAria2Instance(clusterController cluster.Controller) gin.HandlerFunc
// 获取对应主机节点的从机Aria2实例 // 获取对应主机节点的从机Aria2实例
caller, err := clusterController.GetAria2Instance(siteID.(string)) caller, err := clusterController.GetAria2Instance(siteID.(string))
if err != nil { if err != nil {
c.JSON(200, serializer.Err(serializer.CodeNotSet, "无法获取 Aria2 实例", err)) c.JSON(200, serializer.Err(serializer.CodeNotSet, "Failed to get Aria2 instance", err))
c.Abort() c.Abort()
return return
} }
@ -35,7 +35,7 @@ func UseSlaveAria2Instance(clusterController cluster.Controller) gin.HandlerFunc
return return
} }
c.JSON(200, serializer.ParamErr("未知的主机节点ID", nil)) c.JSON(200, serializer.ParamErr("Unknown master node ID", nil))
c.Abort() c.Abort()
} }
} }
@ -44,14 +44,14 @@ func SlaveRPCSignRequired(nodePool cluster.Pool) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
nodeID, err := strconv.ParseUint(c.GetHeader(auth.CrHeaderPrefix+"Node-Id"), 10, 64) nodeID, err := strconv.ParseUint(c.GetHeader(auth.CrHeaderPrefix+"Node-Id"), 10, 64)
if err != nil { if err != nil {
c.JSON(200, serializer.ParamErr("未知的主机节点ID", err)) c.JSON(200, serializer.ParamErr("Unknown master node ID", err))
c.Abort() c.Abort()
return return
} }
slaveNode := nodePool.GetNodeByID(uint(nodeID)) slaveNode := nodePool.GetNodeByID(uint(nodeID))
if slaveNode == nil { if slaveNode == nil {
c.JSON(200, serializer.ParamErr("未知的主机节点ID", err)) c.JSON(200, serializer.ParamErr("Unknown master node ID", err))
c.Abort() c.Abort()
return return
} }

@ -17,7 +17,7 @@ func HashID(IDType int) gin.HandlerFunc {
c.Next() c.Next()
return return
} }
c.JSON(200, serializer.ParamErr("无法解析对象ID", nil)) c.JSON(200, serializer.ParamErr("Failed to parse object ID", nil))
c.Abort() c.Abort()
return return

@ -23,13 +23,13 @@ func FrontendFileHandler() gin.HandlerFunc {
// 读取index.html // 读取index.html
file, err := bootstrap.StaticFS.Open("/index.html") file, err := bootstrap.StaticFS.Open("/index.html")
if err != nil { if err != nil {
util.Log().Warning("静态文件[index.html]不存在,可能会影响首页展示") util.Log().Warning("Static file \"index.html\" does not exist, it might affect the display of the homepage.")
return ignoreFunc return ignoreFunc
} }
fileContentBytes, err := ioutil.ReadAll(file) fileContentBytes, err := ioutil.ReadAll(file)
if err != nil { if err != nil {
util.Log().Warning("静态文件[index.html]读取失败,可能会影响首页展示") util.Log().Warning("Cannot read static file \"index.html\", it might affect the display of the homepage.")
return ignoreFunc return ignoreFunc
} }
fileContent := string(fileContentBytes) fileContent := string(fileContentBytes)

@ -20,10 +20,10 @@ func Session(secret string) gin.HandlerFunc {
var err error var err error
Store, err = redis.NewStoreWithDB(10, conf.RedisConfig.Network, conf.RedisConfig.Server, conf.RedisConfig.Password, conf.RedisConfig.DB, []byte(secret)) Store, err = redis.NewStoreWithDB(10, conf.RedisConfig.Network, conf.RedisConfig.Server, conf.RedisConfig.Password, conf.RedisConfig.DB, []byte(secret))
if err != nil { if err != nil {
util.Log().Panic("无法连接到 Redis%s", err) util.Log().Panic("Failed to connect to Redis%s", err)
} }
util.Log().Info("已连接到 Redis 服务器:%s", conf.RedisConfig.Server) util.Log().Info("Connect to Redis server %q.", conf.RedisConfig.Server)
} else { } else {
Store = memstore.NewStore([]byte(secret)) Store = memstore.NewStore([]byte(secret))
} }
@ -50,7 +50,7 @@ func CSRFCheck() gin.HandlerFunc {
return return
} }
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "来源非法", nil)) c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "Invalid origin", nil))
c.Abort() c.Abort()
} }
} }

@ -16,14 +16,14 @@ func ShareOwner() gin.HandlerFunc {
if userCtx, ok := c.Get("user"); ok { if userCtx, ok := c.Get("user"); ok {
user = userCtx.(*model.User) user = userCtx.(*model.User)
} else { } else {
c.JSON(200, serializer.Err(serializer.CodeCheckLogin, "请先登录", nil)) c.JSON(200, serializer.Err(serializer.CodeCheckLogin, "", nil))
c.Abort() c.Abort()
return return
} }
if share, ok := c.Get("share"); ok { if share, ok := c.Get("share"); ok {
if share.(*model.Share).Creator().ID != user.ID { if share.(*model.Share).Creator().ID != user.ID {
c.JSON(200, serializer.Err(serializer.CodeNotFound, "分享不存在", nil)) c.JSON(200, serializer.Err(serializer.CodeShareLinkNotFound, "", nil))
c.Abort() c.Abort()
return return
} }
@ -46,7 +46,7 @@ func ShareAvailable() gin.HandlerFunc {
share := model.GetShareByHashID(c.Param("id")) share := model.GetShareByHashID(c.Param("id"))
if share == nil || !share.IsAvailable() { if share == nil || !share.IsAvailable() {
c.JSON(200, serializer.Err(serializer.CodeNotFound, "分享不存在或已失效", nil)) c.JSON(200, serializer.Err(serializer.CodeShareLinkNotFound, "", nil))
c.Abort() c.Abort()
return return
} }
@ -65,7 +65,7 @@ func ShareCanPreview() gin.HandlerFunc {
c.Next() c.Next()
return return
} }
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "此分享无法预览", c.JSON(200, serializer.Err(serializer.CodeDisabledSharePreview, "",
nil)) nil))
c.Abort() c.Abort()
return return
@ -85,7 +85,7 @@ func CheckShareUnlocked() gin.HandlerFunc {
unlocked := util.GetSession(c, sessionKey) != nil unlocked := util.GetSession(c, sessionKey) != nil
if !unlocked { if !unlocked {
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr,
"无权访问此分享", nil)) "", nil))
c.Abort() c.Abort()
return return
} }
@ -109,7 +109,7 @@ func BeforeShareDownload() gin.HandlerFunc {
// 检查用户是否可以下载此分享的文件 // 检查用户是否可以下载此分享的文件
err := share.CanBeDownloadBy(user) err := share.CanBeDownloadBy(user)
if err != nil { if err != nil {
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, err.Error(), c.JSON(200, serializer.Err(serializer.CodeGroupNotAllowed, err.Error(),
nil)) nil))
c.Abort() c.Abort()
return return
@ -118,7 +118,7 @@ func BeforeShareDownload() gin.HandlerFunc {
// 对积分、下载次数进行更新 // 对积分、下载次数进行更新
err = share.DownloadBy(user, c) err = share.DownloadBy(user, c)
if err != nil { if err != nil {
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, err.Error(), c.JSON(200, serializer.Err(serializer.CodeGroupNotAllowed, err.Error(),
nil)) nil))
c.Abort() c.Abort()
return return

@ -188,6 +188,8 @@ const (
CodeQQNotLinked = 40068 CodeQQNotLinked = 40068
// 密码不正确 // 密码不正确
CodeIncorrectPassword = 40069 CodeIncorrectPassword = 40069
// 分享无法预览
CodeDisabledSharePreview = 40070
// CodeDBError 数据库操作失败 // CodeDBError 数据库操作失败
CodeDBError = 50001 CodeDBError = 50001
// CodeEncryptError 加密失败 // CodeEncryptError 加密失败

Loading…
Cancel
Save