-
Notifications
You must be signed in to change notification settings - Fork 1
/
templates.go
294 lines (274 loc) · 7.59 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
// Copyright (c) 2017, The pfcdata developers
// See LICENSE for details.
package explorer
import (
"bytes"
"encoding/hex"
"fmt"
"html/template"
"math"
"path/filepath"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/picfight/pfcd/chaincfg"
"github.com/picfight/pfcd/dcrutil"
)
type pageTemplate struct {
file string
template *template.Template
}
type templates struct {
templates map[string]pageTemplate
defaults []string
folder string
helpers template.FuncMap
}
func newTemplates(folder string, defaults []string, helpers template.FuncMap) templates {
var defs []string
for _, file := range defaults {
defs = append(defs, filepath.Join(folder, file+".tmpl"))
}
return templates{
templates: make(map[string]pageTemplate),
defaults: defs,
folder: folder,
helpers: helpers,
}
}
func (t *templates) addTemplate(name string) error {
fileName := filepath.Join(t.folder, name+".tmpl")
files := append(t.defaults, fileName)
temp, err := template.New(name).Funcs(t.helpers).ParseFiles(files...)
if err == nil {
t.templates[name] = pageTemplate{
file: fileName,
template: temp,
}
}
return err
}
func (t *templates) reloadTemplates() error {
var errorStrings []string
for fileName := range t.templates {
err := t.addTemplate(fileName)
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
}
if errorStrings == nil {
return nil
}
return fmt.Errorf(strings.Join(errorStrings, " | "))
}
// execTemplateToString executes the associated input template using the
// supplied data, and writes the result into a string. If the template fails to
// execute or isn't found, a non-nil error will be returned. Check it before
// writing to theclient, otherwise you might as well execute directly into
// your response writer instead of the internal buffer of this function.
func (t *templates) execTemplateToString(name string, data interface{}) (string, error) {
temp, ok := t.templates[name]
if !ok {
return "", fmt.Errorf("Template %s not known", name)
}
var page bytes.Buffer
err := temp.template.ExecuteTemplate(&page, name, data)
return page.String(), err
}
var toInt64 = func(v interface{}) int64 {
switch vt := v.(type) {
case int64:
return vt
case int32:
return int64(vt)
case uint32:
return int64(vt)
case uint64:
return int64(vt)
case int:
return int64(vt)
case int16:
return int64(vt)
case uint16:
return int64(vt)
default:
return math.MinInt64
}
}
// float64Formatting formats a float64 value into multiple strings depending on whether
// boldNumPlaces is provided or not. boldNumPlaces defines the number of decimal
// places to be written with same font as the whole number value of the float.
// If boldNumPlaces is provided the returned slice should have at least four items
// otherwise it should have at least three items. i.e. given v is to 342.12132000,
// numplaces is 8 and boldNumPlaces is set to 2 the following should be returned
// []string{"342", "12", "132", "000"}. If boldNumPlace is not set the returned
// slice should be []string{"342", "12132", "000"}.
func float64Formatting(v float64, numPlaces int, useCommas bool, boldNumPlaces ...int) []string {
pow := math.Pow(10, float64(numPlaces))
formattedVal := math.Round(v*pow) / pow
clipped := fmt.Sprintf("%."+strconv.Itoa(numPlaces)+"f", formattedVal)
oldLength := len(clipped)
clipped = strings.TrimRight(clipped, "0")
trailingZeros := strings.Repeat("0", oldLength-len(clipped))
valueChunks := strings.Split(clipped, ".")
integer := valueChunks[0]
dec := ""
if len(valueChunks) > 1 {
dec = valueChunks[1]
}
if useCommas {
integer = humanize.Comma(int64(formattedVal))
}
if len(boldNumPlaces) == 0 {
return []string{integer, dec, trailingZeros}
}
places := boldNumPlaces[0]
if places > numPlaces {
return []string{integer, dec, trailingZeros}
}
if len(dec) < places {
places = len(dec)
}
return []string{integer, dec[:places], dec[places:], trailingZeros}
}
func makeTemplateFuncMap(params *chaincfg.Params) template.FuncMap {
netTheme := "theme-" + strings.ToLower(netName(params))
return template.FuncMap{
"add": func(a, b int64) int64 {
return a + b
},
"intAdd": func(a, b int) int {
return a + b
},
"subtract": func(a, b int64) int64 {
return a - b
},
"floatsubtract": func(a, b float64) float64 {
return a - b
},
"intSubtract": func(a, b int) int {
return a - b
},
"divide": func(n, d int64) int64 {
return n / d
},
"divideFloat": func(n, d float64) float64 {
return n / d
},
"multiply": func(a, b int64) int64 {
return a * b
},
"intMultiply": func(a, b int) int {
return a * b
},
"timezone": func() string {
t, _ := time.Now().Zone()
return t
},
"percentage": func(a, b int64) float64 {
return (float64(a) / float64(b)) * 100
},
"int64": toInt64,
"intComma": func(v interface{}) string {
return humanize.Comma(toInt64(v))
},
"int64Comma": func(v int64) string {
return humanize.Comma(v)
},
"ticketWindowProgress": func(i int) float64 {
p := (float64(i) / float64(params.StakeDiffWindowSize)) * 100
return p
},
"rewardAdjustmentProgress": func(i int) float64 {
p := (float64(i) / float64(1)) * 100
return p
},
"float64AsDecimalParts": float64Formatting,
"amountAsDecimalParts": func(v int64, useCommas bool) []string {
return float64Formatting(dcrutil.Amount(v).ToCoin(), 8, useCommas)
},
"toFloat64Amount": func(intAmount int64) float64 {
return dcrutil.Amount(intAmount).ToCoin()
},
"remaining": func(idx int, max, t int64) string {
x := (max - int64(idx)) * t
allsecs := int(time.Duration(x).Seconds())
str := ""
if allsecs > 604799 {
weeks := allsecs / 604800
allsecs %= 604800
str += fmt.Sprintf("%dw ", weeks)
}
if allsecs > 86399 {
days := allsecs / 86400
allsecs %= 86400
str += fmt.Sprintf("%dd ", days)
}
if allsecs > 3599 {
hours := allsecs / 3600
allsecs %= 3600
str += fmt.Sprintf("%dh ", hours)
}
if allsecs > 59 {
mins := allsecs / 60
allsecs %= 60
str += fmt.Sprintf("%dm ", mins)
}
if allsecs > 0 {
str += fmt.Sprintf("%ds ", allsecs)
}
return str + "remaining"
},
"TimeDurationFormat": func(duration time.Duration) (formatedDuration string) {
durationhr := int(duration.Minutes() / 60)
durationmin := int(duration.Minutes()) % 60
durationsec := int(duration.Seconds()) % 60
if durationhr != 0 {
formatedDuration = strconv.Itoa(durationhr) + " hrs " + strconv.Itoa(durationmin) + " min " + strconv.Itoa(durationsec) + " sec"
return
} else if (durationhr == 0) && (durationmin != 0) {
formatedDuration = strconv.Itoa(durationmin) + " min " + strconv.Itoa(durationsec) + " sec"
return
} else {
formatedDuration = strconv.Itoa(durationsec) + " sec"
}
return
},
"convertByteArrayToString": func(arr []byte) (inString string) {
inString = hex.EncodeToString(arr)
return
},
"uint16Mul": func(a uint16, b int) (result int) {
result = int(a) * b
return
},
"TimeConversion": func(a uint64) (result string) {
dateTime := time.Unix(int64(a), 0).UTC()
result = dateTime.Format("2006-01-02 15:04:05 MST")
return
},
"toLowerCase": func(a string) string {
return strings.ToLower(a)
},
"theme": func() string {
return netTheme
},
"uint16toInt64": func(v uint16) int64 {
return int64(v)
},
"zeroSlice": func(length int) []int {
if length < 0 {
length = 0
}
return make([]int, length)
},
"clipSlice": func(arr []*TrimmedTxInfo, n int) []*TrimmedTxInfo {
if len(arr) >= n {
return arr[:n]
} else {
return arr
}
},
}
}