-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplates.go
429 lines (391 loc) · 8.71 KB
/
templates.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/pariz/gountries"
"github.com/rjeczalik/notify"
"github.com/thehowl/conf"
"zxq.co/ripple/rippleapi/common"
)
var templates = make(map[string]*template.Template)
var baseTemplates = [...]string{
"templates/base.html",
"templates/navbar.html",
"templates/simplepag.html",
"templates/donor_locked.html",
}
var simplePages []templateConfig
var gdb = gountries.New()
func countryReadable(s string) string {
if s == "XX" || s == "" {
return ""
}
reg, err := gdb.FindCountryByAlpha(s)
if err != nil {
return ""
}
return reg.Name.Common
}
func loadTemplates(subdir string) {
ts, err := ioutil.ReadDir("templates" + subdir)
if err != nil {
panic(err)
}
for _, i := range ts {
// if it's a directory, load recursively
if i.IsDir() && i.Name() != ".." && i.Name() != "." {
loadTemplates(subdir + "/" + i.Name())
continue
}
fullName := "templates" + subdir + "/" + i.Name()
_c := parseConfig(fullName)
var c templateConfig
if _c != nil {
c = *_c
}
if c.NoCompile {
continue
}
var files = c.inc("templates" + subdir + "/")
files = append(files, fullName)
// do not compile base templates on their own
var comp bool
for _, j := range baseTemplates {
if fullName == j {
comp = true
break
}
}
if comp {
continue
}
var inName string
if subdir != "" && subdir[0] == '/' {
inName = subdir[1:] + "/"
}
// add new template to template slice
templates[inName+i.Name()] = template.Must(template.New(i.Name()).Funcs(funcMap).ParseFiles(
append(files, baseTemplates[:]...)...,
))
if _c != nil {
simplePages = append(simplePages, *_c)
}
}
}
func resp(c *gin.Context, statusCode int, tpl string, data interface{}) {
if c == nil {
return
}
t := templates[tpl]
if t == nil {
c.String(500, "Template not found! Please report this to an Kurikku developer!")
return
}
sess := getSession(c)
if corrected, ok := data.(page); ok {
corrected.SetMessages(getMessages(c))
corrected.SetPath(c.Request.URL.Path)
corrected.SetContext(getContext(c))
corrected.SetGinContext(c)
corrected.SetSession(sess)
}
sess.Save()
buf := &bytes.Buffer{}
err := t.ExecuteTemplate(buf, "base", data)
if err != nil {
c.String(
200,
"An error occurred while trying to render the page, and we have now been notified about it.",
)
c.Error(err)
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
c.Status(statusCode)
_, err = io.Copy(c.Writer, buf)
if err != nil {
c.Writer.WriteString("We don't know what's happening now.")
c.Error(err)
return
}
}
type baseTemplateData struct {
TitleBar string // required
HeadingTitle string
HeadingOnRight bool
Scripts []string
KyutGrill string
KyutGrillAbsolute bool
SolidColour string
DisableHH bool // HH = Huge Heading
Messages []message
RequestInfo map[string]interface{}
MetaDescription string
MetaImage string
// ignore, they're set by resp()
Context context
Path string
FormData map[string]string
Gin *gin.Context
Session sessions.Session
}
func (b *baseTemplateData) SetMessages(m []message) {
b.Messages = append(b.Messages, m...)
}
func (b *baseTemplateData) SetPath(path string) {
b.Path = path
}
func (b *baseTemplateData) SetContext(c context) {
b.Context = c
}
func (b *baseTemplateData) SetGinContext(c *gin.Context) {
b.Gin = c
}
func (b *baseTemplateData) SetSession(sess sessions.Session) {
b.Session = sess
}
func (b baseTemplateData) Get(s string, params ...interface{}) map[string]interface{} {
s = fmt.Sprintf(s, params...)
req, err := http.NewRequest("GET", config.API+s, nil)
if err != nil {
b.Gin.Error(err)
return nil
}
req.Header.Set("User-Agent", "hanayo")
req.Header.Set("H-Key", config.APISecret)
req.Header.Set("X-Ripple-Token", b.Context.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
b.Gin.Error(err)
return nil
}
data, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
b.Gin.Error(err)
return nil
}
x := make(map[string]interface{})
err = json.Unmarshal(data, &x)
if err != nil {
b.Gin.Error(err)
return nil
}
return x
}
func ReplaceUnCorrectSymbols(s string) string {
if !utf8.ValidString(s) {
v := make([]rune, 0, len(s))
for i, r := range s {
if r == utf8.RuneError {
_, size := utf8.DecodeRuneInString(s[i:])
if size == 1 {
continue
}
}
v = append(v, r)
}
s = string(v)
}
return s
}
func GetFirstN(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func (b baseTemplateData) BaseGet(s string, params ...interface{}) map[string]interface{} {
s = fmt.Sprintf(s, params...)
req, err := http.NewRequest("GET", s, nil)
if err != nil {
b.Gin.Error(err)
return nil
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
b.Gin.Error(err)
return nil
}
data, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
b.Gin.Error(err)
return nil
}
x := make(map[string]interface{})
err = json.Unmarshal(data, &x)
if err != nil {
b.Gin.Error(err)
return nil
}
return x
}
func (b baseTemplateData) GetFirstLine(s string) string {
var finalStr string
var lines []string = strings.Split(s, "\n")
if len(lines) > 0 {
n := ReplaceUnCorrectSymbols(lines[0])
return n
} else {
s = ReplaceUnCorrectSymbols(s)
var count int = 50
if len(s) > 0 {
if count >= len(s) {
count = len(s) - 1
}
finalStr = s[:count]
}
return finalStr
}
}
func (b baseTemplateData) SubStringKR(s string, count int) string {
var finalStr string
if len(s) > 0 {
if count >= len(s) {
count = len(s) - 1
}
finalStr = s[:count]
}
finalStr = ReplaceUnCorrectSymbols(finalStr)
return finalStr
}
func (b baseTemplateData) ConvertFl64ToInt(s float64) string {
return strconv.Itoa(int(s))
}
func (b baseTemplateData) Has(privs uint64) bool {
return uint64(b.Context.User.Privileges)&privs == privs
}
func (b baseTemplateData) Conf() interface{} {
return config
}
// list of client flags
const (
CFDarkSite = 1 << iota
)
func (b baseTemplateData) ClientFlags() int {
s, _ := b.Gin.Cookie("cflags")
return common.Int(s)
}
type page interface {
SetMessages([]message)
SetPath(string)
SetContext(context)
SetGinContext(*gin.Context)
SetSession(sessions.Session)
}
func reloader() error {
c := make(chan notify.EventInfo, 1)
if err := notify.Watch("./templates/...", c, notify.All); err != nil {
return err
}
go func() {
var last time.Time
for range c {
if time.Since(last) < time.Second*3 {
continue
}
fmt.Println("Change detected! Refreshing templates")
simplePages = []templateConfig{}
loadTemplates("")
l.Close()
last = time.Now()
}
defer notify.Stop(c)
}()
return nil
}
type templateConfig struct {
NoCompile bool
Include string
Template string
// Stuff that used to be in simpleTemplate
Handler string
TitleBar string
KyutGrill string
MinPrivileges uint64
HugeHeadingRight bool
AdditionalJS string
DisableHH bool
}
func (t templateConfig) inc(prefix string) []string {
if t.Include == "" {
return nil
}
a := strings.Split(t.Include, ",")
for i, s := range a {
a[i] = prefix + s
}
return a
}
func (t templateConfig) mp() common.UserPrivileges {
return common.UserPrivileges(t.MinPrivileges)
}
func (t templateConfig) additionalJS() []string {
parts := strings.Split(t.AdditionalJS, ",")
if len(parts) > 0 && parts[len(parts)-1] == "" {
parts = parts[:len(parts)-1]
}
return parts
}
func parseConfig(s string) *templateConfig {
f, err := os.Open(s)
defer f.Close()
if err != nil {
return nil
}
i := bufio.NewScanner(f)
var inConfig bool
var buff string
var t templateConfig
for i.Scan() {
u := i.Text()
switch u {
case "{{/*###":
inConfig = true
case "*/}}":
if !inConfig {
continue
}
conf.LoadRaw(&t, []byte(buff))
t.Template = strings.TrimPrefix(s, "templates/")
return &t
}
if !inConfig {
continue
}
buff += u + "\n"
}
return nil
}
func respEmpty(c *gin.Context, title string, messages ...message) {
resp(c, 200, "empty.html", &baseTemplateData{TitleBar: title, Messages: messages})
}
// StaticReactBuilder React Builder test ver
func StaticReactBuilder(TitleBar string, DisableHH bool, KyutGrillPath string) func(c *gin.Context) {
builder := func(c *gin.Context) {
data := new(baseTemplateData)
defer resp(c, 200, "react.html", data)
data.DisableHH = DisableHH
data.KyutGrill = KyutGrillPath
data.TitleBar = T(c, TitleBar)
}
return builder
}