-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
500 lines (405 loc) · 12.4 KB
/
context.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
* Bulldozer Framework
* Copyright (C) DesertBit
*/
package template
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/desertbit/bulldozer/log"
"github.com/desertbit/bulldozer/sessions"
"github.com/desertbit/bulldozer/utils"
"strconv"
"sync"
)
const (
GlobalID = "global"
)
func init() {
// Register the custom types.
gob.Register(&contextData{})
}
//#########################//
//### Context Data type ###//
//#########################//
// This data can be stored in the session store (ex.: template events).
type contextData struct {
ID string
RootID string
DomID string
TemplateUID string
TemplateName string
StyleClasses []string
// Optional values which are stored in the session store.
// They survive application restarts.
// Values have to be encodable by gob. Don't store pointers!
Values map[interface{}]interface{}
valuesMutex sync.Mutex
}
func (c *contextData) createValuesMapIfNil() {
if c.Values == nil {
c.Values = make(map[interface{}]interface{})
}
}
//#########################//
//### Context Namespace ###//
//#########################//
type contextNamespace struct {
s *sessions.Session
store *contextStore
// The execution values lifetime is one complete template
// execution with all rendered sub templates.
values map[interface{}]interface{}
mutex sync.Mutex
}
func newContextNamespace(s *sessions.Session) *contextNamespace {
return &contextNamespace{
s: s,
store: getContextStore(s), // Get the context store if present or nil.
values: make(map[interface{}]interface{}),
}
}
func (ns *contextNamespace) AddToStore(d *contextData) {
if ns.store != nil {
ns.store.Set(d)
}
}
func (ns *contextNamespace) RemoveFromStore(d *contextData) {
if ns.store != nil {
ns.store.Remove(d)
}
}
//####################//
//### Context type ###//
//####################//
type Context struct {
data *contextData
ns *contextNamespace
t *Template
}
// newContext creates a new context.
func newContext(s *sessions.Session, t *Template, optArgs ...ExecOpts) *Context {
// Create a new context data value.
data := &contextData{
ID: GlobalID, // Set the global ID as default value.
DomID: t.staticDomID, // Use the static DOM ID by default. If emtpy, a new DOM ID will be calculated...
TemplateUID: t.ns.uid,
TemplateName: t.Name(),
StyleClasses: t.styleClasses,
}
// Apply the optional options.
if len(optArgs) > 0 {
opts := &optArgs[0]
// Set the custom ID if set.
if len(opts.ID) > 0 {
data.ID = opts.ID
}
// Set the custom DOM ID if set.
if len(opts.DomID) > 0 {
data.DomID = opts.DomID
}
// Append the additional style classes if present.
if len(opts.StyleClasses) > 0 {
data.StyleClasses = append(data.StyleClasses, opts.StyleClasses...)
}
}
// If the global context ID is set, then use this as ID.
if len(t.globalContextID) > 0 {
data.ID = t.globalContextID
}
// Calculate and set the unique DOM ID with
// the context ID and session encryption key if the DOM ID is emtpy.
if len(data.DomID) == 0 {
data.DomID = utils.EncryptDomId(s.DomEncryptionKey(), "c_"+data.ID)
}
// This is the root context. Set the root ID to the ID.
data.RootID = data.ID
// Create a new context value.
c := &Context{
data: data,
t: t,
ns: newContextNamespace(s),
}
// Add the context data to the store if present.
c.ns.AddToStore(data)
return c
}
// One variadiv boolean can be set. If false, the context won't be added to the context store.
func newContextFromData(s *sessions.Session, data *contextData, vars ...bool) (*Context, error) {
// Get the template namespace with the template UID.
ns, ok := getNameSpace(data.TemplateUID)
if !ok {
return nil, fmt.Errorf("no template namespace found '%s'!", data.TemplateUID)
}
// Get the template.
t := ns.Get(data.TemplateName)
if t == nil {
return nil, fmt.Errorf("no template with name '%s' in namespace '%s'!", data.TemplateName, data.TemplateUID)
}
// Create a new context value.
c := &Context{
data: data,
t: t,
ns: newContextNamespace(s),
}
if len(vars) == 0 || vars[0] {
// Add the context data to the store if present.
c.ns.AddToStore(data)
}
return c, nil
}
// New creates a new sub context.
// One optional slice can be passed, which defines additional style classes.
func (c *Context) New(t *Template, id string, vars ...[]string) *Context {
// Create a new context data value.
data := &contextData{
ID: id,
RootID: c.data.RootID, // Use the root ID of the parent context.
DomID: t.staticDomID, // Use the static DOM ID by default. If emtpy, a new DOM ID will be calculated...
TemplateUID: t.ns.uid,
TemplateName: t.Name(),
StyleClasses: t.styleClasses,
}
// If the global context ID is set, then use this as new ID and Root ID.
if len(t.globalContextID) > 0 {
data.ID = t.globalContextID
data.RootID = t.globalContextID
}
// Calculate and set the unique DOM ID with
// the context ID and session encryption key if the DOM ID is emtpy.
if len(data.DomID) == 0 {
data.DomID = utils.EncryptDomId(c.ns.s.DomEncryptionKey(), "c_"+data.ID)
}
// Add the additional style classes if present.
if len(vars) > 0 {
data.StyleClasses = append(data.StyleClasses, vars[0]...)
}
// Create a new context value.
subC := &Context{
data: data,
t: t,
ns: c.ns, // Contexts share the same namespace.
}
// Add the context data to the store if present.
c.ns.AddToStore(data)
return subC
}
// ID returns the unique ID of this execution context.
// Use this for example as database access keys...
func (c *Context) ID() string {
return c.data.ID
}
// RootID returns the unique ID of the root template.
func (c *Context) RootID() string {
return c.data.RootID
}
// DomID returns the DOM ID of the current context.
func (c *Context) DomID() string {
return c.data.DomID
}
// GenDomID generates the real DOM ID of id.
// This is equivalent to the following template call: {{id "YOUR_ID"}}
func (c *Context) GenDomID(id string) string {
// Create the DOM ID
domId := "c_" + c.data.ID + "+" + id
// Calculate the unique DOM ID with the session encryption key.
return utils.EncryptDomId(c.ns.s.DomEncryptionKey(), domId)
}
// Session resturns the current context session.
func (c *Context) Session() *sessions.Session {
return c.ns.s
}
// Template returns the current context template.
func (c *Context) Template() *Template {
return c.t
}
// Styles returns a slice of all template styles.
func (c *Context) Styles() []string {
return c.data.StyleClasses
}
// StylesString returns a string of all template styles.
func (c *Context) StylesString() (str string) {
// Get the slice.
styles := c.data.StyleClasses
// Add the styles to a string separated by one emtpy space.
if len(styles) > 0 {
for _, sc := range styles {
str += sc + " "
}
// Remove the last emtpy space.
str = str[:len(str)-1]
}
return
}
// Release removes all session template events
// and releases the current context.
func (c *Context) Release() {
// Remove all registered session events for the current DOM ID.
releaseSessionTemplateEvents(c.ns.s, c.data.DomID)
// Remove context data from the store.
c.ns.RemoveFromStore(c.data)
}
// Update executes the template and updates the new DOM content.
// One optional argument can be passed. This is the render data for the template.
// If omitted, the data is obtained through the template.OnGetData function.
func (c *Context) Update(vars ...interface{}) error {
var data interface{}
if len(vars) > 0 {
data = vars[0]
}
// Execute the template
var b bytes.Buffer
err := ExecuteContext(c, &b, data)
if err != nil {
return err
}
// Update the current div wrapper of this template.
c.ns.s.SendCommand(`Bulldozer.render.updateTemplate("` + c.data.DomID + `",'` + utils.EscapeJS(b.String()) + `');`)
return nil
}
// TriggerEvent triggers the event on the client side defined with the template event syntax.
func (c *Context) TriggerEvent(eventName string, params ...interface{}) {
cmd := `Bulldozer.core.emitServerEvent("` + c.data.DomID + `",'` + utils.EscapeJS(eventName) + `'`
// Append all the parameters
for i, param := range params {
// type assertion
switch v := param.(type) {
case int:
cmd += "," + strconv.Itoa(v)
case int64:
cmd += "," + strconv.FormatInt(v, 10)
case bool:
cmd += "," + strconv.FormatBool(v)
case string:
cmd += ",'" + utils.EscapeJS(v) + "'"
default:
log.L.Error("context: trigger event: invalid type of function event parameter: %v : parameters: %v", i+1, params)
return
}
}
cmd += ");"
// Send the command to the client
c.ns.s.SendCommand(cmd)
}
//############################//
//### Context Store Values ###//
//############################//
// StoreGet obtains the store value, which are stored in the session store.
// They survive application restarts.
// Values have to be encodable by gob. Don't store pointers!
// A single variadic argument is accepted, and it is optional:
// if a function is set, this function will be called if no value
// exists for the given key.
// This operation is thread-safe.
func (c *Context) StoreGet(key interface{}, vars ...func() interface{}) (value interface{}, ok bool) {
// Get the data pointer.
data := c.data
// Lock the mutex.
data.valuesMutex.Lock()
defer data.valuesMutex.Unlock()
// Get the value if the map is not nil.
ok = false
if data.Values != nil {
value, ok = data.Values[key]
}
// If no value is found and the create function variable
// is set, then call the function and set the new value.
if !ok && len(vars) > 0 {
value = vars[0]()
data.createValuesMapIfNil()
data.Values[key] = value
ok = true
// Tell the session, that data might have changed.
c.ns.s.Dirty()
}
return
}
// StorePull does the same as Get(), but additionally removes the value from the store if present.
// Use this for Flash values...
func (c *Context) StorePull(key interface{}, vars ...func() interface{}) (interface{}, bool) {
i, ok := c.StoreGet(key, vars...)
if ok {
c.StoreDelete(key)
}
return i, ok
}
// StoreSet sets the store value with the given key. This operation is thread-safe.
func (c *Context) StoreSet(key interface{}, value interface{}) {
// Get the data pointer.
data := c.data
// Lock the mutex.
data.valuesMutex.Lock()
defer data.valuesMutex.Unlock()
// Set the value.
data.createValuesMapIfNil()
data.Values[key] = value
// Tell the session, that data might have changed.
c.ns.s.Dirty()
}
// StoreDelete removes the store value with the given key.
// This operation is thread-safe.
func (c *Context) StoreDelete(key interface{}) {
// Get the data pointer.
data := c.data
// Lock the mutex.
data.valuesMutex.Lock()
defer data.valuesMutex.Unlock()
if data.Values == nil {
return
}
delete(data.Values, key)
// Tell the session, that data might have changed.
c.ns.s.Dirty()
}
//########################//
//### Execution Values ###//
//########################//
// Get obtains the execution value. Execution values exist for one complete execution cycle.
// A single variadic argument is accepted, and it is optional:
// if a function is set, this function will be called if no value
// exists for the given key.
// This operation is thread-safe.
func (c *Context) Get(key interface{}, vars ...func() interface{}) (value interface{}, ok bool) {
// Get the namespace.
ns := c.ns
// Lock the mutex.
ns.mutex.Lock()
defer ns.mutex.Unlock()
value, ok = ns.values[key]
// If no value is found and the create function variable
// is set, then call the function and set the new value.
if !ok && len(vars) > 0 {
value = vars[0]()
ns.values[key] = value
ok = true
}
return
}
// Pull does the same as Get(), but additionally removes the value from the map if present.
// Use this for Flash values...
func (c *Context) Pull(key interface{}, vars ...func() interface{}) (interface{}, bool) {
i, ok := c.Get(key, vars...)
if ok {
c.Delete(key)
}
return i, ok
}
// Set sets the execution value with the given key. This operation is thread-safe.
func (c *Context) Set(key interface{}, value interface{}) {
// Get the namespace.
ns := c.ns
// Lock the mutex.
ns.mutex.Lock()
defer ns.mutex.Unlock()
ns.values[key] = value
}
// Delete removes the execution value with the given key. This operation is thread-safe.
func (c *Context) Delete(key interface{}) {
// Get the namespace.
ns := c.ns
// Lock the mutex.
ns.mutex.Lock()
defer ns.mutex.Unlock()
delete(ns.values, key)
}