-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actor.go
208 lines (180 loc) · 6.41 KB
/
actor.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
// Package variables contains an actor and database client to store
// handle variables
package variables
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"gopkg.in/irc.v4"
"gorm.io/gorm"
"github.com/Luzifer/go_helpers/v2/fieldcollection"
"github.com/Luzifer/twitch-bot/v3/internal/helpers"
"github.com/Luzifer/twitch-bot/v3/pkg/database"
"github.com/Luzifer/twitch-bot/v3/plugins"
)
var (
db database.Connector
formatMessage plugins.MsgFormatter
ptrBoolFalse = func(b bool) *bool { return &b }(false)
ptrStringEmpty = func(s string) *string { return &s }("")
)
// Register provides the plugins.RegisterFunc
//
//nolint:funlen // Function contains only documentation registration
func Register(args plugins.RegistrationArguments) (err error) {
db = args.GetDatabaseConnector()
if err = db.DB().AutoMigrate(&variable{}); err != nil {
return errors.Wrap(err, "applying schema migration")
}
args.RegisterCopyDatabaseFunc("variable", func(src, target *gorm.DB) error {
return database.CopyObjects(src, target, &variable{})
})
formatMessage = args.FormatMessage
args.RegisterActor("setvariable", func() plugins.Actor { return &actorSetVariable{} })
args.RegisterActorDocumentation(plugins.ActionDocumentation{
Description: "Modify variable contents",
Name: "Modify Variable",
Type: "setvariable",
Fields: []plugins.ActionDocumentationField{
{
Default: "",
Description: "Name of the variable to update",
Key: "variable",
Name: "Variable",
Optional: false,
SupportTemplate: true,
Type: plugins.ActionDocumentationFieldTypeString,
},
{
Default: "false",
Description: "Clear variable content and unset the variable",
Key: "clear",
Name: "Clear",
Optional: true,
SupportTemplate: false,
Type: plugins.ActionDocumentationFieldTypeBool,
},
{
Default: "",
Description: "Value to set the variable to",
Key: "set",
Name: "Set Content",
Optional: true,
SupportTemplate: true,
Type: plugins.ActionDocumentationFieldTypeString,
},
},
})
if err = args.RegisterAPIRoute(plugins.HTTPRouteRegistrationArgs{
Description: "Returns the value as a plain string",
HandlerFunc: routeActorSetVarGetValue,
Method: http.MethodGet,
Module: "setvariable",
Name: "Get Variable Value",
Path: "/{name}",
ResponseType: plugins.HTTPRouteResponseTypeTextPlain,
RouteParams: []plugins.HTTPRouteParamDocumentation{
{
Description: "Name of the variable to query",
Name: "name",
},
},
}); err != nil {
return fmt.Errorf("registering API route: %w", err)
}
if err = args.RegisterAPIRoute(plugins.HTTPRouteRegistrationArgs{
Description: "Updates the value of the variable",
HandlerFunc: routeActorSetVarSetValue,
Method: http.MethodPatch,
Module: "setvariable",
Name: "Set Variable Value",
Path: "/{name}",
QueryParams: []plugins.HTTPRouteParamDocumentation{
{
Description: "Value to set for the given variable",
Name: "value",
Required: true,
Type: "string",
},
},
RequiresWriteAuth: true,
RouteParams: []plugins.HTTPRouteParamDocumentation{
{
Description: "Name of the variable to update",
Name: "name",
},
},
}); err != nil {
return fmt.Errorf("registering API route: %w", err)
}
args.RegisterTemplateFunction("variable", plugins.GenericTemplateFunctionGetter(func(name string, defVal ...string) (string, error) {
value, err := getVariable(db, name)
if err != nil {
return "", errors.Wrap(err, "getting variable")
}
if value == "" && len(defVal) > 0 {
return defVal[0], nil
}
return value, nil
}), plugins.TemplateFuncDocumentation{
Description: "Returns the variable value or default in case it is empty",
Syntax: "variable <name> [default]",
Example: &plugins.TemplateFuncDocumentationExample{
Template: `{{ variable "foo" "fallback" }} - {{ variable "unsetvar" "fallback" }}`,
FakedOutput: "test - fallback",
},
})
return nil
}
type actorSetVariable struct{}
func (actorSetVariable) Execute(_ *irc.Client, m *irc.Message, r *plugins.Rule, eventData *fieldcollection.FieldCollection, attrs *fieldcollection.FieldCollection) (preventCooldown bool, err error) {
varName, err := formatMessage(attrs.MustString("variable", nil), m, r, eventData)
if err != nil {
return false, errors.Wrap(err, "preparing variable name")
}
if attrs.MustBool("clear", ptrBoolFalse) {
return false, errors.Wrap(
removeVariable(db, varName),
"removing variable",
)
}
value, err := formatMessage(attrs.MustString("set", ptrStringEmpty), m, r, eventData)
if err != nil {
return false, errors.Wrap(err, "preparing value")
}
return false, errors.Wrap(
setVariable(db, varName, value),
"setting variable",
)
}
func (actorSetVariable) IsAsync() bool { return false }
func (actorSetVariable) Name() string { return "setvariable" }
func (actorSetVariable) Validate(tplValidator plugins.TemplateValidatorFunc, attrs *fieldcollection.FieldCollection) (err error) {
if err = attrs.ValidateSchema(
fieldcollection.MustHaveField(fieldcollection.SchemaField{Name: "variable", NonEmpty: true, Type: fieldcollection.SchemaFieldTypeString}),
fieldcollection.CanHaveField(fieldcollection.SchemaField{Name: "clear", Type: fieldcollection.SchemaFieldTypeBool}),
fieldcollection.CanHaveField(fieldcollection.SchemaField{Name: "set", NonEmpty: true, Type: fieldcollection.SchemaFieldTypeString}),
fieldcollection.MustHaveNoUnknowFields,
helpers.SchemaValidateTemplateField(tplValidator, "set", "variable"),
); err != nil {
return fmt.Errorf("validating attributes: %w", err)
}
return nil
}
func routeActorSetVarGetValue(w http.ResponseWriter, r *http.Request) {
vc, err := getVariable(db, mux.Vars(r)["name"])
if err != nil {
http.Error(w, errors.Wrap(err, "getting value").Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text-plain")
fmt.Fprint(w, vc)
}
func routeActorSetVarSetValue(w http.ResponseWriter, r *http.Request) {
if err := setVariable(db, mux.Vars(r)["name"], r.FormValue("value")); err != nil {
http.Error(w, errors.Wrap(err, "updating value").Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}