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