xonecas.io
8058
Ir

irvc / files

irvc / media.go

2.2 KB
1package main
2
3import (
4	"errors"
5	"fmt"
6	"io"
7	"net/http"
8	"os"
9	"path/filepath"
10	"regexp"
11
12	"github.com/gin-gonic/gin"
13)
14
15// Raster images and browser-playable video. SVG and HTML can carry script, so
16// they are not accepted. c.File serves these with Range support, so video
17// seeks and streams without extra work.
18var mediaExt = map[string]string{
19	"image/png":  ".png",
20	"image/jpeg": ".jpg",
21	"image/gif":  ".gif",
22	"image/webp": ".webp",
23	"video/mp4":  ".mp4",
24	"video/webm": ".webm",
25}
26
27// The extension allows digits so mp4 serves; the stem is the token from upload.
28var mediaName = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[a-z0-9]+$`)
29
30func (s *Server) handleUpload(c *gin.Context) {
31	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, s.cfg.MaxUpload)
32	file, err := c.FormFile("file")
33	if err != nil {
34		var tooBig *http.MaxBytesError
35		if errors.As(err, &tooBig) {
36			c.JSON(http.StatusRequestEntityTooLarge, gin.H{
37				"error": fmt.Sprintf("file is larger than %d MB", s.cfg.MaxUpload>>20),
38			})
39			return
40		}
41		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload"})
42		return
43	}
44	f, err := file.Open()
45	if err != nil {
46		c.JSON(http.StatusInternalServerError, gin.H{"error": "open"})
47		return
48	}
49	defer f.Close()
50	head := make([]byte, 512)
51	n, _ := io.ReadFull(f, head)
52	ext, ok := mediaExt[http.DetectContentType(head[:n])]
53	if !ok {
54		c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported media"})
55		return
56	}
57	if _, err := f.Seek(0, io.SeekStart); err != nil {
58		c.JSON(http.StatusInternalServerError, gin.H{"error": "read"})
59		return
60	}
61	name := randToken() + ext
62	dst, err := os.Create(filepath.Join(s.cfg.MediaDir, name))
63	if err != nil {
64		c.JSON(http.StatusInternalServerError, gin.H{"error": "write"})
65		return
66	}
67	defer dst.Close()
68	if _, err := io.Copy(dst, f); err != nil {
69		c.JSON(http.StatusInternalServerError, gin.H{"error": "write"})
70		return
71	}
72	c.JSON(http.StatusOK, gin.H{"url": "/api/media/" + name})
73}
74
75func (s *Server) handleMedia(c *gin.Context) {
76	name := c.Param("name")
77	if !mediaName.MatchString(name) {
78		c.Status(http.StatusNotFound)
79		return
80	}
81	c.Header("X-Content-Type-Options", "nosniff")
82	c.File(filepath.Join(s.cfg.MediaDir, name))
83}