This repository has been archived by the owner on Aug 8, 2021. It is now read-only.
forked from Bios-Marcel/cordless
-
Notifications
You must be signed in to change notification settings - Fork 6
/
javascript.go
373 lines (324 loc) · 10.7 KB
/
javascript.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
// This package is the Engine implementation for a javascript scripting
// interface. All callbacks are optional and the overhead for checking
// callback-existence is rather low, as it happens on script initialisation.
// All invocations of callbacks perform locking on the instance that they
// are being called on. Each instance has their own lock.
package js
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/cainy-a/discordgo"
"github.com/pkg/errors"
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
"github.com/yellowsink/gord/scripting"
)
var (
// This declaration makes sure that JavaScriptEngine complies with the
// Engine interface.
_ scripting.Engine = &JavaScriptEngine{}
// We cache the null and undefined value, since it's wasteful to keep
// reallocating those.
nullValue = otto.NullValue()
undefinedValue = otto.UndefinedValue()
)
// JavaScriptEngine stores scripting engine state
type JavaScriptEngine struct {
scriptInstances []*ScriptInstance
errorOutput io.Writer
// globalInstance is used for actions that don't require to be run on a
// specific VM, but any VM. An example for this is converting a Go-struct
// into a valid Otto-Value.
globalInstance *otto.Otto
}
// ScriptInstance represents a usable and already loaded javascript. The
// callbacks are pre-evaluated and the instance can be locked as soon as any
// of the requested callbacks are available.
type ScriptInstance struct {
vm *otto.Otto
lock sync.Mutex
onMessageSend *otto.Value
onMessageReceive *otto.Value
onMessageEdit *otto.Value
onMessageDelete *otto.Value
}
// New instantiates a new scripting engine. The resulting object doesn't hold
// any data or VMs initially. Only upon loading scripts, VMs are created.
func New() *JavaScriptEngine {
return &JavaScriptEngine{}
}
// LoadScripts implements Engine. Each script gets a designated Otto-VM in
// order to avoid scripts modifying each others state by accident. All
// available callbacks get eagerly evaluated in the beginning. Locking of the
// instances when calling one of the callbacks only happens, if a callback
// actually exists.
func (engine *JavaScriptEngine) LoadScripts(dirname string) (err error) {
_, statError := os.Stat(dirname)
if os.IsNotExist(statError) {
return nil
} else if statError != nil {
return errors.Wrapf(statError, "Error loading scripts '%s'", statError.Error())
}
return engine.readScriptsRecursively(dirname)
}
func (engine *JavaScriptEngine) readScriptsRecursively(dirname string) error {
files, err := ioutil.ReadDir(dirname)
if err != nil {
return err
}
for _, file := range files {
path := filepath.Join(dirname, file.Name())
//Skip dot-folders and read non-dot-folders.
if file.IsDir() {
if !strings.HasPrefix(file.Name(), ".") {
readError := engine.readScriptsRecursively(path)
if readError != nil {
return readError
}
}
continue
}
//Only javascript files
if !strings.HasSuffix(file.Name(), ".js") {
continue
}
file, err := os.Open(path)
if err != nil {
return errors.Wrap(err, path)
}
vm := otto.New()
_, err = vm.Run(file)
if err != nil {
return errors.Wrapf(err, "failed to run script '%s'", path)
}
instance := &ScriptInstance{
vm: vm,
lock: sync.Mutex{},
}
initFunction, resolveError := vm.Get("init")
if !initFunction.IsUndefined() {
initFunction.Call(nullValue)
// We attempt clearing the init function, as it's not supposed to
// be called again after initialisation and therefore only wastes
// precious memory.
clearError := vm.Set("init", undefinedValue)
if clearError != nil {
return errors.Wrap(resolveError, "error clearing init function from VM.")
}
}
onMessageSendJS, resolveError := vm.Get("onMessageSend")
if !onMessageSendJS.IsUndefined() {
instance.onMessageSend = &onMessageSendJS
}
if resolveError != nil {
return errors.Wrap(resolveError, "error resolving function onMessageSend")
}
onMessageReceiveJS, resolveError := vm.Get("onMessageReceive")
if !onMessageReceiveJS.IsUndefined() {
instance.onMessageReceive = &onMessageReceiveJS
}
if resolveError != nil {
return errors.Wrap(resolveError, "error resolving function onMessageReceive")
}
onMessageEditJS, resolveError := vm.Get("onMessageEdit")
if !onMessageEditJS.IsUndefined() {
instance.onMessageEdit = &onMessageEditJS
}
if resolveError != nil {
return errors.Wrap(resolveError, "error resolving function onMessageEdit")
}
onMessageDeleteJS, resolveError := vm.Get("onMessageDelete")
if !onMessageDeleteJS.IsUndefined() {
instance.onMessageDelete = &onMessageDeleteJS
}
if resolveError != nil {
return errors.Wrap(resolveError, "error resolving function onMessageDelete")
}
engine.scriptInstances = append(engine.scriptInstances, instance)
}
//Avoid unnecessarily creating an unused VM.
if len(engine.scriptInstances) > 0 {
engine.globalInstance = otto.New()
}
return nil
}
// SetErrorOutput sets the writer to which errors can be written from inside
// the JavaScript engines.
func (engine *JavaScriptEngine) SetErrorOutput(errorOutput io.Writer) {
engine.errorOutput = errorOutput
}
// OnMessageSend implements Engine
func (engine *JavaScriptEngine) OnMessageSend(oldText string) (newText string) {
newText = oldText
for _, instance := range engine.scriptInstances {
func() {
if instance.onMessageSend != nil {
defer instance.lock.Unlock()
instance.lock.Lock()
jsValue, jsError := instance.onMessageSend.Call(nullValue, newText)
if jsError != nil {
if engine.errorOutput != nil {
fmt.Fprintf(engine.errorOutput, "Error occurred during execution of javascript: %s\n", jsError.Error())
}
//This script failed, go to next one
return
}
newText = jsValue.String()
}
}()
}
return
}
// OnMessageReceive implements Engine
func (engine *JavaScriptEngine) OnMessageReceive(message *discordgo.Message) {
if len(engine.scriptInstances) == 0 {
return
}
messageToJS, toValueError := engine.globalInstance.ToValue(*message)
if toValueError != nil {
log.Printf("Error converting message to Otto value: %s\n", toValueError)
return
}
for _, instance := range engine.scriptInstances {
func() {
if instance.onMessageReceive != nil {
instance.lock.Lock()
defer instance.lock.Unlock()
_, callError := instance.onMessageReceive.Call(nullValue, messageToJS)
if callError != nil {
log.Printf("Error calling onMessageReceive: %s\n", callError)
}
}
}()
}
}
// OnMessageEdit implements Engine
func (engine *JavaScriptEngine) OnMessageEdit(message *discordgo.Message) {
if len(engine.scriptInstances) == 0 {
return
}
messageToJS, toValueError := engine.globalInstance.ToValue(*message)
if toValueError != nil {
log.Printf("Error converting message to Otto value: %s\n", toValueError)
return
}
for _, instance := range engine.scriptInstances {
func() {
if instance.onMessageEdit != nil {
instance.lock.Lock()
defer instance.lock.Unlock()
_, callError := instance.onMessageEdit.Call(nullValue, messageToJS)
if callError != nil {
log.Printf("Error calling onMessageEdit: %s\n", callError)
}
}
}()
}
}
// OnMessageDelete implements Engine
func (engine *JavaScriptEngine) OnMessageDelete(message *discordgo.Message) {
if len(engine.scriptInstances) == 0 {
return
}
messageToJS, toValueError := engine.globalInstance.ToValue(*message)
if toValueError != nil {
log.Printf("Error converting message to Otto value: %s\n", toValueError)
return
}
for _, instance := range engine.scriptInstances {
func() {
if instance.onMessageDelete != nil {
instance.lock.Lock()
defer instance.lock.Unlock()
_, callError := instance.onMessageDelete.Call(nullValue, messageToJS)
if callError != nil {
log.Printf("Error calling onMessageDelete: %s\n", callError)
}
}
}()
}
}
// SetTriggerNotificationFunction implements Engine
func (engine *JavaScriptEngine) SetTriggerNotificationFunction(function func(title, text string)) {
triggerNotification := func(call otto.FunctionCall) otto.Value {
title, argError := call.Argument(0).ToString()
if argError != nil {
log.Printf("Error invoking triggerNotification in JS engine: %s\n", argError)
return nullValue
}
text, argError := call.Argument(1).ToString()
if argError != nil {
log.Printf("Error invoking triggerNotification in JS engine: %s\n", argError)
return nullValue
}
function(title, text)
return nullValue
}
engine.setFunctionOnVMs("triggerNotification", triggerNotification)
}
// SetPrintToConsoleFunction implements Engine
func (engine *JavaScriptEngine) SetPrintToConsoleFunction(function func(text string)) {
printToConsole := func(call otto.FunctionCall) otto.Value {
text, argError := call.Argument(0).ToString()
if argError != nil {
log.Printf("Error invoking printToConsole in JS engine: %s\n", argError)
} else {
function(text)
}
return undefinedValue
}
engine.setFunctionOnVMs("printToConsole", printToConsole)
}
// SetPrintLineToConsoleFunction implements Engine
func (engine *JavaScriptEngine) SetPrintLineToConsoleFunction(function func(text string)) {
printLineToConsole := func(call otto.FunctionCall) otto.Value {
text, argError := call.Argument(0).ToString()
if argError != nil {
log.Printf("Error invoking printLineToConsole in JS engine: %s\n", argError)
} else {
function(text)
}
return undefinedValue
}
engine.setFunctionOnVMs("printLineToConsole", printLineToConsole)
}
// SetGetCurrentGuildFunction implements Engine
func (engine *JavaScriptEngine) SetGetCurrentGuildFunction(function func() string) {
getCurrentGuild := func(call otto.FunctionCall) otto.Value {
guildID, callError := call.Otto.ToValue(function())
if callError != nil {
log.Printf("Error calling getCurrentGuild: %s\n", callError)
return nullValue
} else {
return guildID
}
}
engine.setFunctionOnVMs("getCurrentGuild", getCurrentGuild)
}
// SetGetCurrentChannelFunction implements Engine
func (engine *JavaScriptEngine) SetGetCurrentChannelFunction(function func() string) {
getCurrentChannel := func(call otto.FunctionCall) otto.Value {
guildID, callError := call.Otto.ToValue(function())
if callError != nil {
log.Printf("Error calling getCurrentChannel: %s\n", callError)
return nullValue
} else {
return guildID
}
}
engine.setFunctionOnVMs("getCurrentChannel", getCurrentChannel)
}
func (engine *JavaScriptEngine) setFunctionOnVMs(name string, function func(call otto.FunctionCall) otto.Value) {
for _, instance := range engine.scriptInstances {
setError := instance.vm.Set(name, function)
if setError != nil {
log.Printf("Error setting function %s: %s", name, setError)
}
}
}