option.go 2.2 KB
Newer Older
1 2 3
package middleware

import (
4
	"github.com/HFO4/cloudreve/bootstrap"
H
HFO4 已提交
5
	model "github.com/HFO4/cloudreve/models"
6 7
	"github.com/HFO4/cloudreve/pkg/hashid"
	"github.com/HFO4/cloudreve/pkg/serializer"
8
	"github.com/HFO4/cloudreve/pkg/util"
9
	"github.com/gin-gonic/gin"
10
	"io/ioutil"
11 12
)

H
HFO4 已提交
13
// HashID 将给定对象的HashID转换为真实ID
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
func HashID(IDType int) gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Param("id") != "" {
			id, err := hashid.DecodeHashID(c.Param("id"), IDType)
			if err == nil {
				c.Set("object_id", id)
				c.Next()
				return
			}
			c.JSON(200, serializer.ParamErr("无法解析对象ID", nil))
			c.Abort()
			return

		}
		c.Next()
	}
}
H
HFO4 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43

// IsFunctionEnabled 当功能未开启时阻止访问
func IsFunctionEnabled(key string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if !model.IsTrueVal(model.GetSettingByName(key)) {
			c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "未开启此功能", nil))
			c.Abort()
			return
		}

		c.Next()
	}
}
44 45 46 47 48 49

// InjectSiteInfo 向首页html中插入站点信息
func InjectSiteInfo() gin.HandlerFunc {
	ignoreFunc := func(c *gin.Context) {
		c.Next()
	}
50 51 52 53
	if bootstrap.StaticFS == nil {
		return ignoreFunc
	}

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	// 读取index.html
	file, err := bootstrap.StaticFS.Open("/index.html")
	if err != nil {
		util.Log().Warning("静态文件[index.html]不存在,可能会影响首页展示")
		return ignoreFunc
	}

	fileContentBytes, err := ioutil.ReadAll(file)
	if err != nil {
		util.Log().Warning("静态文件[index.html]读取失败,可能会影响首页展示")
		return ignoreFunc
	}
	fileContent := string(fileContentBytes)

	return func(c *gin.Context) {
		if c.Request.URL.Path == "/" || c.Request.URL.Path == "/index.html" {
			// 读取、替换站点设置
			options := model.GetSettingByNames("siteName", "siteKeywords", "siteScript",
				"pwa_small_icon")
			finalHTML := util.Replace(map[string]string{
				"{siteName}":       options["siteName"],
				"{siteDes}":        options["siteDes"],
				"{siteScript}":     options["siteScript"],
				"{pwa_small_icon}": options["pwa_small_icon"],
			}, fileContent)

			c.Header("Content-Type", "text/html")
			c.String(200, finalHTML)
			c.Abort()
			return
		}
		c.Next()
	}
}