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 if len(filename) > 256 { // arbitrarily chosen
49 return fmt.Errorf("Filename is too long")
50 }
51 ext := strings.ToLower(path.Ext(filename))
52 found := false
53 for _, mimetype := range c.OkExtensions {
54 if ext == mimetype {
55 found = true
56 }
57 }
58 if !found {
59 return fmt.Errorf("Invalid file extension: %s", ext)
60 }
61 if len(fileBytes) > c.MaxFileSize {
62 return fmt.Errorf("File too large. File was %d bytes, Max file size is %d", len(fileBytes), c.MaxFileSize)
63 }
64 return nil
65}
66
67func zipit(source string, target io.Writer) error {
68 archive := zip.NewWriter(target)
69
70 info, err := os.Stat(source)
71 if err != nil {
72 return nil
73 }
74
75 var baseDir string
76 if info.IsDir() {
77 baseDir = filepath.Base(source)
78 }
79
80 filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
81 if err != nil {
82 return err
83 }
84
85 header, err := zip.FileInfoHeader(info)
86 if err != nil {
87 return err
88 }
89
90 if baseDir != "" {
91 header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
92 }
93
94 if info.IsDir() {
95 header.Name += "/"
96 } else {
97 header.Method = zip.Deflate
98 }
99
100 writer, err := archive.CreateHeader(header)
101 if err != nil {
102 return err
103 }
104
105 if info.IsDir() {
106 return nil
107 }
108
109 file, err := os.Open(path)
110 if err != nil {
111 return err
112 }
113 defer file.Close()
114 _, err = io.Copy(writer, file)
115 return err
116 })
117
118 archive.Close()
119
120 return err
121}