summaryrefslogtreecommitdiff
path: root/main.go
blob: 0ebbdc4835659e6880ea0ad448c0b34371f81bce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main

import (
    "crypto/md5"
    "mime"
    "io/ioutil"
    "io"
    "encoding/json"
    "sync"
    "flag"
    "fmt"
    "html/template"
    "log"
    "strconv"
    "net/http"
    "os"
    "path"
    "strings"

    "github.com/jmoiron/sqlx"
    _"github.com/lib/pq"
)

type Config struct {
    Listen   string `json:"listen"`
    DBStr    string `json:"db"`
    TmplPath string `json:"tmpl"`

    DataPath string `json:"data"`
    MaxSize  uint `json:"max_upload"`
    MaxPages uint `json:"max_pages"`
}

type Server struct {
    mux  *http.ServeMux
    conf *Config
    db   *sqlx.DB

    fslock sync.RWMutex
    filestore map[string][]string
}

type note struct {
    Hash     string
    Name     string
    Location string
}

const scheme = `
    CREATE TABLE IF NOT EXISTS notes (
        hash     VARCHAR(4) PRIMARY KEY,
        name     TEXT NOT NULL,
        location TEXT NOT NULL,
        available BOOL DEFAULT True
    )
`

var validMIME = map[string]bool {
    "text/plain": true,
    "image/jpeg": true,
    "image/png": true,
    "application/pdf": true,
}

func main() {
    confFlag := flag.String("c", "config.json", "config file")
    flag.Parse()

    f, err := os.Open(*confFlag)
    if err != nil {
        log.Fatal(err)
    }

    var conf Config
    err = json.NewDecoder(f).Decode(&conf)
    if err != nil {
        log.Fatal(err)
    }

    s := NewServer(&conf)
    if err != nil {
        log.Fatal(err)
    }

    err = s.Connect()
    if err != nil {
        log.Fatal(err)
    }

    log.Fatal(s.Run())
}

func NewServer(conf *Config) *Server {
    s := &Server{}
    s.mux = http.NewServeMux()
    s.mux.HandleFunc("/", s.httpRoot)
    s.mux.HandleFunc("/upload", s.httpUpload)
    s.mux.Handle("/data/", http.StripPrefix("/data/",
        http.FileServer(http.Dir(conf.DataPath))))

    s.conf = conf

    s.filestore = map[string][]string{}

    return s
}

func (s *Server) Connect() error {
    files, err := ioutil.ReadDir(s.conf.DataPath)
    if err != nil {
        return err
    }

    for _, file := range files {
        name := file.Name()

        hash := name[0:4]
        s.saveFile(hash, name)
    }

    s.db, err = sqlx.Connect("postgres", s.conf.DBStr)
    if err != nil {
        return err
    }

    s.db.MustExec(scheme)
    return nil
}

func (s *Server) Run() error {
    log.Printf("Listening on %s", s.conf.Listen)
    return http.ListenAndServe(s.conf.Listen, s.mux)
}

func (s *Server) renderTemplate(w http.ResponseWriter, data interface{}, pathname string) error {

    tmpl, err := template.ParseFiles(path.Join(s.conf.TmplPath, pathname))
    if err != nil {
        log.Print(err)
        return err
    }

    err = tmpl.Execute(w, data)
    if err != nil {
        log.Print(err)
    }
    return err
}

func (s *Server) httpLog(r *http.Request, format string, args... interface{}) {
    args = append([]interface{}{r.URL.Path, r.RemoteAddr}, args...)
    log.Printf("(url: %s, ip: %s) " + format, args...)
}

func (s *Server) Error(w http.ResponseWriter, r *http.Request, err string, code int) {
    if code < 500 {
        http.Error(w, err, code)
    } else {
        w.WriteHeader(code)
    }

    s.httpLog(r, "ERR: %s", err)
}

func (s *Server) httpCreateNode(w http.ResponseWriter, r *http.Request) {
    var (
        name = r.FormValue("name")
        location = r.FormValue("location")
    )

    hash := fmt.Sprintf("%x", md5.Sum([]byte(name)))[0:4]

    _, err := s.db.ExecContext(r.Context(), `
        INSERT INTO notes (hash, name, location)
        VALUES ($1, $2, $3)`, hash, name, location)
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusInternalServerError)
        return
    }

    s.httpLog(r, "Created node %s", hash)

    var ref strings.Builder
    fmt.Fprintf(&ref, "#%s", hash)
    if location != "" {
        fmt.Fprintf(&ref, "/%s", location)
    }

    fmt.Fprintf(w, `
    <html>
        <p><b>Note:</b> %s</p>
        <p><b>Location:</b> %s</p>
        <p><b>Hash:</b> %s"</p>
        <p><b>Ref:</b> %s</p>
    </html>`, name, location, hash, ref.String())
}

func (s *Server) httpRoot(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        w.WriteHeader(http.StatusNotFound)
        return
    }

    if r.Method == "POST" {
        s.httpCreateNode(w, r)
        return
    }

    var page struct {
        Notes []note
        Msg   string
        Files *map[string][]string
    }
    page.Files = &s.filestore

    err := s.db.SelectContext(r.Context(), &page.Notes, `
        SELECT hash, name, location FROM notes WHERE available = True`)
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusInternalServerError)
        return
    }

    s.fslock.RLock()
    s.renderTemplate(w, &page, "root.template")
    s.fslock.RUnlock()
}

func (s *Server) httpUpload(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        w.WriteHeader(http.StatusMethodNotAllowed)
        return
    }

    r.Body = http.MaxBytesReader(w, r.Body, int64(s.conf.MaxSize) * 1000000)

    // Head hash
    hash := r.FormValue("h")
    _, err := strconv.ParseUint(hash, 16, 16)
    if err != nil || len(hash) != 4 {
        s.Error(w, r, "Invalid hash", http.StatusBadRequest)
        return
    }

    // Load file
    inf, header, err := r.FormFile("f")
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusInternalServerError)
        return
    }
    defer inf.Close()

    // Check if valid type
    mtype := header.Header.Get("Content-Type")
    ok := validMIME[mtype]
    if !ok {
        s.Error(w, r, "Invalid file type", http.StatusBadRequest)
        return
    }

    // Create file
    fname, err := s.allocFile(hash, mtype)
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusBadRequest)
        return
    }

    f, err := os.Create(path.Join(s.conf.DataPath, fname))
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusInternalServerError)
        return
    }
    defer f.Close()

    _, err = io.Copy(f, inf)
    if err != nil {
        s.Error(w, r, err.Error(), http.StatusInternalServerError)
        return
    }

    s.saveFile(hash, fname)
    s.httpLog(r, "Uploaded file %s", fname)

    http.Redirect(w, r, "/", http.StatusSeeOther)
}

func (s *Server) allocFile(hash string, t string) (string, error) {
    s.fslock.RLock()
    existing := s.filestore[hash]
    s.fslock.RUnlock()

    if len(existing) >= int(s.conf.MaxPages) {
        return "", fmt.Errorf("No more than %d pages is allowed", s.conf.MaxPages)
    }

    var ext string
    extarr, _ := mime.ExtensionsByType(t)
    if len(extarr) > 0 {
        ext = extarr[0]
    }

    return fmt.Sprintf("%s.%d%s", hash, len(existing), ext), nil
}

func (s *Server) saveFile(hash string, fname string) {
    s.fslock.Lock()
    s.filestore[hash] = append(s.filestore[hash], fname)

    s.fslock.Unlock()
}