repos / pico

pico services mono repo
git clone https://github.com/picosh/pico.git

pico / pkg / apps / pastes
Antonio Mika  ·  2025-03-12

scp_hooks.go

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