summaryrefslogtreecommitdiff
path: root/controller/file.go
blob: 53121d5a061187a44510106bd07acfb61862d4e2 (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
package controller

import (
	"fmt"
	"io"
	"net/http"
	"time"

	"drop.janw.name/storage"
)

const MAX_FILESIZE = (1 << 19) * 100

func (app App) FilePost(res http.ResponseWriter, req *http.Request) {
	if !app.requireAuth(res, req) {
		return
	}

	if err := req.ParseMultipartForm(MAX_FILESIZE); err != nil {
		panic(err)
	}

	formFile, formFileHeader, err := req.FormFile("file")
	if err != nil {
		panic(err)
	}

	protected := req.FormValue("protect") == "on"

	fileData, err := io.ReadAll(formFile)
	if err != nil {
		panic(err)
	}

	file := storage.File{
		Protected:      protected,
		Filename:       formFileHeader.Filename,
		Data:           fileData,
		AvailableUntil: time.Now().Add(time.Hour * 2),
	}

	key, err := app.storage.Put(file)
	if err != nil {
		panic(err)
	}

	app.tmpl.ExecuteTemplate(res, "uploaded", struct {
		DownloadURL string
	}{
		DownloadURL: fmt.Sprintf("%s/%s", app.config.Http.BaseAddress, key),
	})
}

func (app App) FileGet(res http.ResponseWriter, req *http.Request) {
	fileId := req.PathValue("file")

	file, _ := app.storage.Get(fileId)

	if file == nil || !file.IsAvailable() {
		if !app.requireAuth(res, req) {
			return
		}

		res.WriteHeader(http.StatusNotFound)
		app.tmpl.ExecuteTemplate(res, "404", nil)
		return
	}

	if file.Protected && !app.requireAuth(res, req) {
		return
	}

	res.Header().Add("Content-Type", "application/octet-stream")
	res.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", file.Filename))

	if _, err := res.Write(file.Data); err != nil {
		panic(err)
	}
}