-
Notifications
You must be signed in to change notification settings - Fork 386
/
manager.go
117 lines (98 loc) · 2.39 KB
/
manager.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
package addon
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/url"
"github.com/ponzu-cms/ponzu/management/editor"
"github.com/gorilla/schema"
"github.com/tidwall/gjson"
)
const defaultInput = `<input type="hidden" name="%s" value="%s"/>`
const managerHTML = `
<div class="card editor">
<form method="post" action="/admin/addon" enctype="multipart/form-data">
<div class="card-content">
<div class="card-title">{{ .AddonName }}</div>
</div>
{{ .DefaultInputs }}
{{ .Editor }}
</form>
</div>
`
type manager struct {
DefaultInputs template.HTML
Editor template.HTML
AddonName string
}
// Manage ...
func Manage(data []byte, reverseDNS string) ([]byte, error) {
a, ok := Types[reverseDNS]
if !ok {
return nil, fmt.Errorf("Addon has not been added to addon.Types map")
}
// convert json => map[string]interface{} => url.Values
var kv map[string]interface{}
err := json.Unmarshal(data, &kv)
if err != nil {
return nil, err
}
vals := make(url.Values)
for k, v := range kv {
switch v.(type) {
case []string:
s := v.([]string)
for i := range s {
if i == 0 {
vals.Set(k, s[i])
}
vals.Add(k, s[i])
}
default:
vals.Set(k, fmt.Sprintf("%v", v))
}
}
at := a()
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
dec.SetAliasTag("json")
err = dec.Decode(at, vals)
if err != nil {
return nil, err
}
e, ok := at.(editor.Editable)
if !ok {
return nil, fmt.Errorf("Addon is not editable - must implement editor.Editable: %T", at)
}
v, err := e.MarshalEditor()
if err != nil {
return nil, fmt.Errorf("Couldn't marshal editor for addon: %s", err.Error())
}
inputs := &bytes.Buffer{}
fields := []string{
"addon_name",
"addon_author",
"addon_author_url",
"addon_version",
"addon_reverse_dns",
"addon_status",
}
for _, f := range fields {
input := fmt.Sprintf(defaultInput, f, gjson.GetBytes(data, f).String())
_, err := inputs.WriteString(input)
if err != nil {
return nil, fmt.Errorf("Failed to write input for addon view: %s", f)
}
}
m := manager{
DefaultInputs: template.HTML(inputs.Bytes()),
Editor: template.HTML(v),
AddonName: gjson.GetBytes(data, "addon_name").String(),
}
// execute html template into buffer for func return val
buf := &bytes.Buffer{}
tmpl := template.Must(template.New("manager").Parse(managerHTML))
tmpl.Execute(buf, m)
return buf.Bytes(), nil
}