all repos — flounder @ cd4229413269e4ea5dc31bec7a4a2c5415c78fba

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