server/admin/sync/themes.go

83 lines
2.1 KiB
Go

package sync
import (
"fmt"
"path"
"strings"
"srs.epita.fr/fic-server/libfic"
"github.com/julienschmidt/httprouter"
)
func getThemes(i Importer) ([]string, error) {
var themes []string
if dirs, err := i.listDir("/"); err != nil {
return nil, err
} else {
for _, dir := range dirs {
if _, err := i.listDir(dir); err == nil {
themes = append(themes, dir)
}
}
}
return themes, nil
}
func getAuthors(i Importer, tname string) ([]string, error) {
if authors, err := getFileContent(i, path.Join(tname, "AUTHORS.txt")); err != nil {
return nil, err
} else {
return strings.Split(strings.TrimSpace(authors), "\n"), nil
}
}
func SyncThemes(i Importer) []string {
var errs []string
if themes, err := getThemes(i); err != nil {
errs = append(errs, err.Error())
} else {
for _, tname := range themes {
var authors []string
var intro string
var theme fic.Theme
if authors, err = getAuthors(i, tname); err != nil {
errs = append(errs, fmt.Sprintf("%q: unable to get AUTHORS: %s", tname, err))
continue
} else if intro, err = getFileContent(i, path.Join(tname, "introduction.txt")); err != nil {
errs = append(errs, fmt.Sprintf("%q: unable to get introduction: %s", tname, err))
} else if theme, err = fic.GetThemeByName(tname); err != nil {
if _, err := fic.CreateTheme(tname, fic.ToURLid(tname), strings.Join(authors, ", "), intro); err != nil {
errs = append(errs, fmt.Sprintf("%q: an error occurs during add: %s", tname, err))
continue
}
}
authors_str := strings.Join(authors, ", ")
if theme.Name != tname || theme.Authors != authors_str || theme.Intro != intro {
theme.Name = tname
theme.Authors = authors_str
theme.Intro = intro
if _, err := theme.Update(); err != nil {
errs = append(errs, fmt.Sprintf("%q: an error occurs during update: %s", tname, err))
continue
}
}
}
}
return errs
}
func ApiListRemoteThemes(_ httprouter.Params, _ []byte) (interface{}, error) {
return getThemes(GlobalImporter)
}
func ApiGetRemoteTheme(ps httprouter.Params, _ []byte) (interface{}, error) {
return getAuthors(GlobalImporter, ps.ByName("thid"))
}