This repository has been archived by the owner on Mar 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrender.go
96 lines (81 loc) · 2.21 KB
/
render.go
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
package main
import (
"github.com/multiplio/cast-render/render"
"encoding/json"
"fmt"
"image/png"
"log"
"strings"
"github.com/cbroglie/mustache"
cid "github.com/ipfs/go-cid"
ipfs "github.com/ipfs/go-ipfs-api"
"github.com/qiangxue/fasthttp-routing"
)
type renderContext struct {
shell *ipfs.Shell
renderer *render.Renderer
postTemplate *string
}
func (r *renderContext) handleTwitter(c *routing.Context) error {
hash := c.Param("hash")
log.Println("Got hash :", hash)
imagePath := environment.RootURL + "/post/" + hash + "/image"
page, err := mustache.Render(*r.postTemplate, map[string]string{
"imagePath": imagePath,
"title": "cast by multipl",
})
if err != nil {
log.Println("error:", err)
return routing.NewHTTPError(400, "Could not render post.")
}
c.Response.Header.SetContentType("text/html; charset=utf-8")
fmt.Fprintf(c, page)
return nil
}
type post struct {
Description string `json:"description"`
Content string `json:"content"`
FontSize float64 `json:"fontSize"`
Spacing float64 `json:"spacing"`
}
func (r *renderContext) handleImage(c *routing.Context) error {
// get and validate hash
hash := c.Param("hash")
if hash == "" {
log.Println("No hash in url")
return routing.NewHTTPError(400, "Provide a post hash.")
}
// Create a cid from a marshaled string
cid, err := cid.Decode(hash)
if err != nil {
log.Println("Hash is not valid cid")
return routing.NewHTTPError(400, "Provide a valid post hash.")
}
log.Println("Got cid :", cid)
// get post from ipfs
block, err := r.shell.BlockGet("/ipfs/" + cid.String())
if err != nil {
log.Println("error:", err)
return routing.NewHTTPError(400, "No post found.")
}
var post post
err = json.Unmarshal(block, &post)
if err != nil {
log.Println("error:", err)
return routing.NewHTTPError(400, "Not a post.")
}
// render
lines := strings.Split(post.Content, "\n")
rgba, err := r.renderer.Render(lines, &post.FontSize, &post.Spacing)
if err != nil {
log.Println("Could not render : ", cid, " : ", err)
return routing.NewHTTPError(400, "Not a post.")
}
// write
err = png.Encode(c, rgba)
if err != nil {
log.Println(err)
return routing.NewHTTPError(400, "Not a post.")
}
return nil
}