1
0
mirror of https://github.com/hrfee/jfa-go.git synced 2024-10-18 09:00:11 +00:00
jfa-go/router.go

143 lines
4.2 KiB
Go

package main
import (
"fmt"
"html/template"
"io/fs"
"net/http"
"os"
"path/filepath"
"github.com/gin-contrib/pprof"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/logrusorgru/aurora/v3"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
// loads HTML templates. If [files]/html_templates is set, alternative files inside the directory are loaded in place of the internal templates.
func (app *appContext) loadHTML(router *gin.Engine) {
customPath := app.config.Section("files").Key("html_templates").MustString("")
templatePath := "html"
htmlFiles, err := fs.ReadDir(localFS, templatePath)
if err != nil {
app.err.Fatalf("Couldn't access template directory: \"%s\"", templatePath)
return
}
loadFiles := make([]string, len(htmlFiles))
for i, f := range htmlFiles {
if _, err := os.Stat(filepath.Join(customPath, f.Name())); os.IsNotExist(err) {
app.debug.Printf("Using default \"%s\"", f.Name())
loadFiles[i] = filepath.Join(templatePath, f.Name())
} else {
app.info.Printf("Using custom \"%s\"", f.Name())
loadFiles[i] = filepath.Join(filepath.Join(customPath, f.Name()))
}
}
tmpl, err := template.ParseFS(localFS, loadFiles...)
if err != nil {
app.err.Fatalf("Failed to load templates: %v", err)
}
router.SetHTMLTemplate(tmpl)
}
// sets gin logger.
func setGinLogger(router *gin.Engine, debugMode bool) {
if debugMode {
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
return fmt.Sprintf("[GIN/DEBUG] %s: %s(%s) => %d in %s; %s\n",
param.TimeStamp.Format("15:04:05"),
param.Method,
param.Path,
param.StatusCode,
param.Latency,
func() string {
if param.ErrorMessage != "" {
return "Error: " + param.ErrorMessage
}
return ""
}(),
)
}))
} else {
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
return fmt.Sprintf("[GIN] %s(%s) => %d\n",
param.Method,
param.Path,
param.StatusCode,
)
}))
}
}
func (app *appContext) loadRouter(address string, debug bool) *gin.Engine {
if debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
setGinLogger(router, debug)
router.Use(gin.Recovery())
app.loadHTML(router)
router.Use(static.Serve("/", app.webFS))
router.NoRoute(app.NoRouteHandler)
if debug {
app.debug.Println("Loading pprof")
pprof.Register(router)
}
SRV = &http.Server{
Addr: address,
Handler: router,
}
return router
}
func (app *appContext) loadRoutes(router *gin.Engine) {
router.GET("/", app.AdminPage)
router.GET("/accounts", app.AdminPage)
router.GET("/settings", app.AdminPage)
router.GET("/lang/:page/:file", app.ServeLang)
router.GET("/token/login", app.getTokenLogin)
router.GET("/token/refresh", app.getTokenRefresh)
router.POST("/newUser", app.NewUser)
router.Use(static.Serve("/invite/", app.webFS))
router.GET("/invite/:invCode", app.InviteProxy)
if *SWAGGER {
app.info.Print(aurora.Magenta("\n\nWARNING: Swagger should not be used on a public instance.\n\n"))
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
api := router.Group("/", app.webAuth())
router.POST("/logout", app.Logout)
api.DELETE("/users", app.DeleteUser)
api.GET("/users", app.GetUsers)
api.POST("/users", app.NewUserAdmin)
api.POST("/invites", app.GenerateInvite)
api.GET("/invites", app.GetInvites)
api.DELETE("/invites", app.DeleteInvite)
api.POST("/invites/profile", app.SetProfile)
api.GET("/profiles", app.GetProfiles)
api.POST("/profiles/default", app.SetDefaultProfile)
api.POST("/profiles", app.CreateProfile)
api.DELETE("/profiles", app.DeleteProfile)
api.POST("/invites/notify", app.SetNotify)
api.POST("/users/emails", app.ModifyEmails)
api.POST("/users/settings", app.ApplySettings)
api.GET("/config", app.GetConfig)
api.POST("/config", app.ModifyConfig)
api.POST("/restart", app.restart)
if app.config.Section("ombi").Key("enabled").MustBool(false) {
api.GET("/ombi/users", app.OmbiUsers)
api.POST("/ombi/defaults", app.SetOmbiDefaults)
}
}
func (app *appContext) loadSetup(router *gin.Engine) {
router.GET("/", app.ServeSetup)
router.POST("/jellyfin/test", app.TestJF)
router.POST("/config", app.ModifyConfig)
}