repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

pico / prose
Antonio Mika · 08 Oct 24

scp_hooks.go

 1package prose
 2
 3import (
 4	"fmt"
 5	"strings"
 6
 7	"slices"
 8
 9	"github.com/charmbracelet/ssh"
10	"github.com/picosh/pico/db"
11	"github.com/picosh/pico/filehandlers"
12	"github.com/picosh/pico/shared"
13	"github.com/picosh/utils"
14)
15
16type MarkdownHooks struct {
17	Cfg *shared.ConfigSite
18	Db  db.DB
19}
20
21func (p *MarkdownHooks) FileValidate(s ssh.Session, data *filehandlers.PostMetaData) (bool, error) {
22	if !utils.IsTextFile(data.Text) {
23		err := fmt.Errorf(
24			"WARNING: (%s) invalid file must be plain text (utf-8), skipping",
25			data.Filename,
26		)
27		return false, err
28	}
29
30	// special styles css file we want to permit but no other css file.
31	// sometimes the directory is provided in the filename, so we want to
32	// remove that before we perform this check.
33	if strings.Replace(data.Filename, "/", "", 1) == "_styles.css" {
34		return true, nil
35	}
36
37	if !utils.IsExtAllowed(data.Filename, p.Cfg.AllowedExt) {
38		extStr := strings.Join(p.Cfg.AllowedExt, ",")
39		err := fmt.Errorf(
40			"WARNING: (%s) invalid file, format must be (%s), skipping",
41			data.Filename,
42			extStr,
43		)
44		return false, err
45	}
46
47	return true, nil
48}
49
50func (p *MarkdownHooks) FileMeta(s ssh.Session, data *filehandlers.PostMetaData) error {
51	parsedText, err := shared.ParseText(data.Text)
52	if err != nil {
53		return fmt.Errorf("%s: %w", data.Filename, err)
54	}
55
56	if parsedText.Title == "" {
57		data.Title = utils.ToUpper(data.Slug)
58	} else {
59		data.Title = parsedText.Title
60	}
61
62	data.Aliases = parsedText.Aliases
63	data.Tags = parsedText.Tags
64	data.Description = parsedText.Description
65
66	if parsedText.PublishAt != nil && !parsedText.PublishAt.IsZero() {
67		data.PublishAt = parsedText.MetaData.PublishAt
68	}
69
70	isHiddenFilename := slices.Contains(p.Cfg.HiddenPosts, data.Filename)
71	data.Hidden = parsedText.MetaData.Hidden || isHiddenFilename
72
73	return nil
74}