repos / pico

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

pico / pastes
Antonio Mika · 08 Oct 24

scp_hooks.go

 1package pastes
 2
 3import (
 4	"fmt"
 5	"strconv"
 6	"strings"
 7	"time"
 8
 9	"github.com/araddon/dateparse"
10	"github.com/charmbracelet/ssh"
11	"github.com/picosh/pico/db"
12	"github.com/picosh/pico/filehandlers"
13	"github.com/picosh/pico/shared"
14	"github.com/picosh/utils"
15)
16
17var DEFAULT_EXPIRES_AT = 90
18
19type FileHooks struct {
20	Cfg *shared.ConfigSite
21	Db  db.DB
22}
23
24func (p *FileHooks) FileValidate(s ssh.Session, data *filehandlers.PostMetaData) (bool, error) {
25	if !utils.IsTextFile(string(data.Text)) {
26		err := fmt.Errorf(
27			"WARNING: (%s) invalid file must be plain text (utf-8), skipping",
28			data.Filename,
29		)
30		return false, err
31	}
32
33	return true, nil
34}
35
36func (p *FileHooks) FileMeta(s ssh.Session, data *filehandlers.PostMetaData) error {
37	data.Title = utils.ToUpper(data.Slug)
38	// we want the slug to be the filename for pastes
39	data.Slug = data.Filename
40
41	if data.Post.ExpiresAt == nil || data.Post.ExpiresAt.IsZero() {
42		// mark posts for deletion a X days after creation
43		expiresAt := time.Now().AddDate(0, 0, DEFAULT_EXPIRES_AT)
44		data.ExpiresAt = &expiresAt
45	}
46
47	var hidden bool
48	var expiresFound bool
49	var expires *time.Time
50
51	cmd := s.Command()
52
53	for _, arg := range cmd {
54		if strings.Contains(arg, "=") {
55			splitArg := strings.Split(arg, "=")
56			if len(splitArg) != 2 {
57				continue
58			}
59
60			switch splitArg[0] {
61			case "hidden":
62				val, err := strconv.ParseBool(splitArg[1])
63				if err != nil {
64					continue
65				}
66
67				hidden = val
68			case "expires":
69				val, err := strconv.ParseBool(splitArg[1])
70				if err == nil {
71					expiresFound = !val
72					continue
73				}
74
75				duration, err := time.ParseDuration(splitArg[1])
76				if err == nil {
77					expiresFound = true
78					expireTime := time.Now().Add(duration)
79					expires = &expireTime
80					continue
81				}
82
83				expireTime, err := dateparse.ParseStrict(splitArg[1])
84				if err == nil {
85					expiresFound = true
86					expires = &expireTime
87				}
88			}
89		}
90	}
91
92	data.Hidden = hidden
93
94	if expiresFound {
95		data.ExpiresAt = expires
96	}
97
98	return nil
99}