package sync import ( "fmt" "path" "regexp" "strings" "srs.epita.fr/fic-server/libfic" "github.com/julienschmidt/httprouter" "gopkg.in/russross/blackfriday.v2" ) // getThemes returns all theme directories in the base directory. 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 } // getAuthors parses the AUTHORS file. func getAuthors(i Importer, tname string) ([]string, error) { if authors, err := getFileContent(i, path.Join(tname, "AUTHORS.txt")); err != nil { return nil, err } else { var ret []string re := regexp.MustCompile("^([^<]+)(?: +<(.*)>)?$") for _, a := range strings.Split(strings.TrimSpace(authors), "\n") { grp := re.FindStringSubmatch(a) if len(grp) < 2 || grp[2] == "" { ret = append(ret, a) } else { ret = append(ret, fmt.Sprintf("%s", grp[2], grp[1])) } } return ret, nil } } // SyncThemes imports new or updates existing themes. func SyncThemes(i Importer) []string { var errs []string if themes, err := getThemes(i); err != nil { errs = append(errs, err.Error()) } else { for _, tdir := range themes { var authors []string var intro string var theme fic.Theme var tname string // Extract theme's label if f := strings.Index(tdir, "-"); f >= 0 { tname = tdir[f+1:] } else { tname = tdir } if authors, err = getAuthors(i, tdir); err != nil { errs = append(errs, fmt.Sprintf("%q: unable to get AUTHORS: %s", tname, err)) continue } else if intro, err = getFileContent(i, path.Join(tdir, "overview.txt")); err != nil { errs = append(errs, fmt.Sprintf("%q: unable to get theme's overview: %s", tname, err)) } else if theme, err = fic.GetThemeByName(tname); err != nil { if _, err := fic.CreateTheme(tname, fic.ToURLid(tname), tdir, strings.Join(authors, ", "), intro); err != nil { errs = append(errs, fmt.Sprintf("%q: an error occurs during add: %s", tdir, err)) continue } } // Format authors authors_str := strings.Join(authors, ", ") // Format overview (markdown) intro = string(blackfriday.Run([]byte(intro))) if theme.Name != tname || theme.Authors != authors_str || theme.Intro != intro { theme.Name = tname theme.Authors = authors_str theme.Intro = intro theme.Path = tdir if _, err := theme.Update(); err != nil { errs = append(errs, fmt.Sprintf("%q: an error occurs during update: %s", tdir, err)) continue } } } } return errs } // ApiListRemoteThemes is an accessor letting foreign packages to access remote themes list. func ApiListRemoteThemes(_ httprouter.Params, _ []byte) (interface{}, error) { return getThemes(GlobalImporter) } // ApiListRemoteTheme is an accessor letting foreign packages to access remote main theme attributes. func ApiGetRemoteTheme(ps httprouter.Params, _ []byte) (interface{}, error) { return getAuthors(GlobalImporter, ps.ByName("thid")) }