Skip to content

Commit 69dd56e

Browse files
committed
Make fallback embed more generalised && bundle html templates in the binary
1 parent 9dded0a commit 69dd56e

File tree

8 files changed

+346
-238
lines changed

8 files changed

+346
-238
lines changed
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package fallbackembed
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"io"
7+
"io/ioutil"
8+
"net/http"
9+
"regexp"
10+
"strconv"
11+
"strings"
12+
"time"
13+
)
14+
15+
// FallbackEmbed represents this package
16+
type FallbackEmbed struct {
17+
data *Data
18+
httpClient *http.Client
19+
targetKey string
20+
providerURL string
21+
}
22+
23+
// Data represents the data for FallbackEmbed providers
24+
type Data []struct {
25+
Name string `json:"name"`
26+
Patterns []Regex `json:"patterns"`
27+
}
28+
29+
// New returns a FallbackEmbed object
30+
func New(providerURL, targetKey string) *FallbackEmbed {
31+
obj := &FallbackEmbed{
32+
httpClient: &http.Client{
33+
Timeout: time.Second * 30,
34+
},
35+
providerURL: providerURL,
36+
targetKey: targetKey,
37+
}
38+
39+
return obj
40+
}
41+
42+
// ParseProviders parses the raw json obtained from noembed.com
43+
func (f *FallbackEmbed) ParseProviders(buf io.Reader) error {
44+
data, err := ioutil.ReadAll(buf)
45+
if err != nil {
46+
return err
47+
}
48+
49+
var providerData Data
50+
err = json.Unmarshal(data, &providerData)
51+
if err != nil {
52+
return err
53+
}
54+
55+
f.data = &providerData
56+
return nil
57+
}
58+
59+
// Get returns html string
60+
func (f *FallbackEmbed) Get(url string, width int, height int) (html string, err error) {
61+
if !f.ValidURL(url) {
62+
return
63+
}
64+
65+
// Do replacements
66+
reqURL := strings.Replace(f.providerURL, "{url}", url, 1)
67+
reqURL = strings.Replace(reqURL, "{width}", strconv.Itoa(width), 1)
68+
reqURL = strings.Replace(reqURL, "{height}", strconv.Itoa(height), 1)
69+
70+
var httpResp *http.Response
71+
httpResp, err = f.httpClient.Get(reqURL)
72+
if err != nil {
73+
return
74+
}
75+
defer httpResp.Body.Close()
76+
77+
var body []byte
78+
body, err = ioutil.ReadAll(httpResp.Body)
79+
if err != nil {
80+
return
81+
}
82+
83+
// Try to parse json response
84+
resp := make(map[string]interface{})
85+
err = json.Unmarshal(body, &resp)
86+
if err != nil {
87+
return
88+
}
89+
90+
// Check targetKey exists
91+
if jsonVal, ok := resp[f.targetKey]; ok {
92+
// Check targetVal is string
93+
if htmlString, ok := jsonVal.(string); ok {
94+
html = htmlString
95+
return
96+
}
97+
}
98+
99+
err = errors.New("Failed to get target json key")
100+
return
101+
}
102+
103+
// ValidURL is used to test if a url is supported by noembed
104+
func (f *FallbackEmbed) ValidURL(url string) bool {
105+
for _, entry := range *f.data {
106+
for _, pattern := range entry.Patterns {
107+
if pattern.Regexp.MatchString(url) {
108+
return true
109+
}
110+
}
111+
}
112+
return false
113+
}
114+
115+
// Regex Unmarshaler
116+
type Regex struct {
117+
regexp.Regexp
118+
}
119+
120+
// UnmarshalText used to unmarshal regexp's from text
121+
func (r *Regex) UnmarshalText(text []byte) error {
122+
reg, err := regexp.Compile(string(text))
123+
r.Regexp = *reg
124+
return err
125+
}

fileuploader.config.example.toml

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,17 @@ MaxAge = "24h" # 1 day
4545
IdentifiedMaxAge = "168h" # 1 week
4646
CheckInterval = "5m"
4747

48-
[Embed]
49-
TemplatePath = "templates/embed.html"
48+
[WebPreview]
49+
TemplatesDirectory = "templates"
5050
CacheMaxAge = "1h"
5151
CacheCleanInterval = "15m"
5252

53+
# Fallback provider specific
54+
FallbackProviderDisabled = false
55+
FallbackProviderURL = "https://noembed.com/embed?url={url}"
56+
FallbackProviderFile = "fallback-providers.json"
57+
FallbackProviderJsonKey = "html"
58+
5359
# If EXTJWT is supported by the gateway or network, a validated token with an account present (when
5460
# the user is authenticated to an irc services account) will use the IdentifiedMaxAge setting above
5561
# instead of the base MaxAge.

main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"github.com/kiwiirc/plugin-fileuploader/server"
77
)
88

9+
//go:generate go run ./scripts/generate-templates.go
10+
911
func main() {
1012
var configPath = flag.String("config", "fileuploader.config.toml", "path to config file")
1113
flag.Parse()

noembed/noembed.go

Lines changed: 0 additions & 124 deletions
This file was deleted.

scripts/generate-templates.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
import (
4+
"io"
5+
"io/ioutil"
6+
"os"
7+
"path"
8+
"strings"
9+
)
10+
11+
const templatesDir = "./templates"
12+
13+
func main() {
14+
files, _ := ioutil.ReadDir(templatesDir)
15+
16+
out, _ := os.Create(path.Join(templatesDir, "templates.go"))
17+
out.Write([]byte("package templates\n\nvar Get = map[string]string{\n"))
18+
for _, fileInfo := range files {
19+
if strings.HasSuffix(fileInfo.Name(), ".html") {
20+
out.Write([]byte(strings.TrimSuffix(fileInfo.Name(), ".html") + ": `"))
21+
file, _ := os.Open(path.Join(templatesDir, fileInfo.Name()))
22+
io.Copy(out, file)
23+
out.Write([]byte("`,\n"))
24+
}
25+
}
26+
out.Write([]byte("}\n"))
27+
}

server/config.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,17 @@ type Config struct {
4646
JwtSecretsByIssuer map[string]string
4747
Loggers []LoggerConfig
4848

49-
// Embed Provider
50-
Embed struct {
51-
TemplatePath string
49+
// WebPreview config options
50+
WebPreview struct {
51+
TemplatesDirectory string
5252
CacheMaxAge duration
5353
CacheCleanInterval duration
54-
ImageCachePath string
55-
ImageCacheMaxSize uint64
54+
55+
// Fallback provider configuration
56+
FallbackProviderDisabled bool
57+
FallbackProviderURL string
58+
FallbackProviderFile string
59+
FallbackProviderJsonKey string
5660
}
5761
}
5862

0 commit comments

Comments
 (0)