all repos — flounder @ 2799ede93e92daa87144e345d5b086aac4e8c037

A small site builder for the Gemini protocol

utils.go (view raw)

  1package main
  2
  3import (
  4	"archive/zip"
  5	"fmt"
  6	"io"
  7	"os"
  8	"path"
  9	"path/filepath"
 10	"strings"
 11	"time"
 12)
 13
 14func timeago(t *time.Time) string {
 15	d := time.Since(*t)
 16	if d.Seconds() < 60 {
 17		return fmt.Sprintf("%d seconds ago", int(d.Seconds()))
 18	} else if d.Minutes() < 60 {
 19		return fmt.Sprintf("%d minutes ago", int(d.Minutes()))
 20	} else if d.Hours() < 24 {
 21		return fmt.Sprintf("%d hours ago", int(d.Hours()))
 22	} else {
 23		return fmt.Sprintf("%d days ago", int(d.Hours())/24)
 24	}
 25}
 26
 27/// Perform some checks to make sure the file is OK
 28func checkIfValidFile(filename string, fileBytes []byte) error {
 29	if len(filename) == 0 {
 30		return fmt.Errorf("Please enter a filename")
 31	}
 32	ext := strings.ToLower(path.Ext(filename))
 33	found := false
 34	for _, mimetype := range c.OkExtensions {
 35		if ext == mimetype {
 36			found = true
 37		}
 38	}
 39	if !found {
 40		return fmt.Errorf("Invalid file extension: %s", ext)
 41	}
 42	fmt.Println(len(fileBytes))
 43	if len(fileBytes) > c.MaxFileSize {
 44		return fmt.Errorf("File too large. File was %d bytes, Max file size is %d", len(fileBytes), c.MaxFileSize)
 45	}
 46	return nil
 47}
 48
 49func zipit(source string, target io.Writer) error {
 50	archive := zip.NewWriter(target)
 51
 52	info, err := os.Stat(source)
 53	if err != nil {
 54		return nil
 55	}
 56
 57	var baseDir string
 58	if info.IsDir() {
 59		baseDir = filepath.Base(source)
 60	}
 61
 62	filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
 63		if err != nil {
 64			return err
 65		}
 66
 67		header, err := zip.FileInfoHeader(info)
 68		if err != nil {
 69			return err
 70		}
 71
 72		if baseDir != "" {
 73			header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
 74		}
 75
 76		if info.IsDir() {
 77			header.Name += "/"
 78		} else {
 79			header.Method = zip.Deflate
 80		}
 81
 82		writer, err := archive.CreateHeader(header)
 83		if err != nil {
 84			return err
 85		}
 86
 87		if info.IsDir() {
 88			return nil
 89		}
 90
 91		file, err := os.Open(path)
 92		if err != nil {
 93			return err
 94		}
 95		defer file.Close()
 96		_, err = io.Copy(writer, file)
 97		return err
 98	})
 99
100	archive.Close()
101
102	return err
103}