aboutsummaryrefslogtreecommitdiff
path: root/internal/image/service.go
blob: 2a60c673d24d69f6c10f53e78601428ae294c6ce (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
package image

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"time"

	gonanoid "github.com/matoous/go-nanoid"
	"github.com/pkg/errors"

	"go.ofmax.li/tmpl"
)

// Servicer image management
type Servicer interface {
	NewID() (string, error)
	AddFile(extension string, meta *PostMeta, fileBytes []byte) (string, string, error)
	GetFile(fileUrl string) (*PostMeta, error)
	Render(w http.ResponseWriter, templateName string, data interface{}) error
}

// NewService new image service
func NewService(repo Repo, storagePath string, renderer *tmpl.HTML) *Service {
	return &Service{repo,
		storagePath,
		renderer,
	}
}

// Service a container for working with images
type Service struct {
	db          Repo
	storagePath string
	tmpl        *tmpl.HTML
}

// Render renders templates
func (is *Service) Render(w http.ResponseWriter, templateName string, data interface{}) error {
	return is.tmpl.Render(w, templateName, data)
}

// NewID create an uniqueish ID
func (is *Service) NewID() (string, error) {
	return gonanoid.Nanoid()
}

// AddFile writes to disk, writes meta to db
func (is *Service) AddFile(extension string, postMeta *PostMeta, fileBytes []byte) (string, string, error) {
	fileID, err := is.NewID()
	if err != nil {
		return "", "", errors.Wrap(err, "generated id for fileID failed")
	}
	fileName := fmt.Sprintf("%s.%s", fileID, extension)
	filePath := path.Join(is.storagePath, fileName)
	if err := ioutil.WriteFile(filePath, fileBytes, 0750); err != nil {
		log.Fatal(err)
		return "", "", errors.Wrap(err, "couldn't write image file")
	}
	postID, err := is.NewID()
	if err != nil {
		return "", "", errors.Wrap(err, "generating postid for uuid")
	}
	t := time.Now().UTC()
	postMeta.FilePath = fileName
	postMeta.CreatedAt = t.Format(time.RFC3339)
	is.db.AddNewFile(postID, postMeta, 946080000)
	if err := is.db.AddNewFile(postID, postMeta, 946080000); err != nil {
		log.Fatal(err)
		return "", "", errors.Wrap(err, "couldn't write to redis")
	}
	return fileName, postID, nil
}

// GetFile fetch file from db interface
func (is *Service) GetFile(fileUrl string) (*PostMeta, error) {
	result, err := is.db.GetFile(fileUrl)
	if err != nil {
		return &PostMeta{}, err
	}
	return result, err
}