website/routes/configs.go
2024-05-05 21:22:45 +03:00

127 lines
2.6 KiB
Go

package routes
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"path"
"strings"
"git.matterlinux.xyz/Matter/website/lib"
"github.com/bigkevmcd/go-configparser"
"github.com/gofiber/fiber/v2"
)
type Config struct {
Redirect string `json:"redirect"`
Image string `json:"image"`
Url string `json:"url"`
Name string
Desc string
Author string
Keywords string
}
func LoadConfig(c *Config) (error) {
agent := fiber.Get(c.Url)
code, body, errs := agent.Bytes()
if len(errs) > 0 {
return fmt.Errorf("request to %s failed", c.Url)
}
if code != 200 {
return fmt.Errorf("bad response from %s", c.Url)
}
parser := configparser.New()
err := parser.ParseReader(bytes.NewReader(body))
if err != nil {
return fmt.Errorf("failed to parse %s: %s", c.Url, err.Error())
}
name, err := parser.Get("details", "name")
if err != nil {
return fmt.Errorf("failed get details/name: %s", c.Url)
}
keywords, err := parser.Get("details", "keywords")
if err != nil {
return fmt.Errorf("failed get details/keywords: %s", c.Url)
}
author, err := parser.Get("details", "author")
if err != nil {
return fmt.Errorf("failed get details/keywords: %s", c.Url)
}
desc, err := parser.Get("details", "desc")
c.Name = name
c.Desc = desc
c.Author = author
c.Keywords = strings.ReplaceAll(keywords, ",", ", ")
if(!lib.IsStringValid(c.Name) ||
!lib.IsStringValid(c.Desc) ||
!lib.IsStringValid(c.Author) ||
!lib.IsStringValid(c.Keywords)){
return fmt.Errorf("keywords or name contain illegal chars: %s", c.Url)
}
return nil
}
func GetConfigs() ([]Config, error) {
var data map[string][]Config
configs_path := path.Join(lib.CONTENT_PATH, "configs.json")
raw, err := os.ReadFile(configs_path)
if err != nil {
return nil, err
}
err = json.Unmarshal(raw, &data)
if err != nil {
return nil, err
}
if _, ok := data["list"]; !ok {
return nil, fmt.Errorf("json data does not contain the list key")
}
for i := range data["list"] {
err = LoadConfig(&data["list"][i])
if err != nil {
return nil, err
}
}
return data["list"], nil
}
func ConfigsRoute(c *fiber.Ctx) error{
con, err := lib.GetContent("", "configs")
if err != nil {
log.Printf("GetContent failed: %s", err.Error())
return lib.RenderError(c, 500)
}
configs, err := GetConfigs()
if err != nil {
log.Printf("GetConfigs failed: %s", err.Error())
return lib.RenderError(c, 500)
}
return c.Render("configs", fiber.Map{
"content": con,
"list": configs,
})
}
func ConfigRoute(c *fiber.Ctx) error{
return c.Redirect("/configs")
}