82 lines
1.5 KiB
Go
82 lines
1.5 KiB
Go
package action
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.sr.ht/~cco/go-scopes/lib"
|
|
"git.sr.ht/~cco/go-scopes/lib/message"
|
|
)
|
|
|
|
type baseSpec struct {
|
|
handler lib.ActionHandler
|
|
receivers []string
|
|
}
|
|
|
|
func (spec *baseSpec) Handler() lib.ActionHandler {
|
|
return spec.handler
|
|
}
|
|
|
|
func (spec *baseSpec) Receivers() []string {
|
|
return spec.receivers
|
|
}
|
|
|
|
func Base(hdlr lib.ActionHandler, rcvrs []string) *baseSpec {
|
|
return &baseSpec{hdlr, rcvrs}
|
|
}
|
|
|
|
// action selection
|
|
|
|
func Select(ctx lib.Context, msg lib.Message) []lib.Action {
|
|
var acts []lib.Action
|
|
for _, ac := range ctx.Config().Actions() {
|
|
if match(ac, msg) {
|
|
for _, spec := range ac.Specs() {
|
|
act := action{ctx, spec, msg}
|
|
acts = append(acts, &act)
|
|
}
|
|
}
|
|
}
|
|
return acts
|
|
}
|
|
|
|
func match(ac lib.ActionConfig, msg lib.Message) bool {
|
|
fmt.Println("action.match", ac.Pattern(), msg.Action())
|
|
return ac.Pattern() == msg.Action()
|
|
//return false
|
|
}
|
|
|
|
// action
|
|
|
|
type action struct {
|
|
ctx lib.Context
|
|
spec lib.ActionSpec
|
|
msg lib.Message
|
|
}
|
|
|
|
func (act *action) Context() lib.Context {
|
|
return act.ctx
|
|
}
|
|
|
|
func (act *action) Spec() lib.ActionSpec {
|
|
return act.spec
|
|
}
|
|
|
|
func (act *action) Message() lib.Message {
|
|
return act.msg
|
|
}
|
|
|
|
func (act *action) Handle() bool {
|
|
return act.spec.Handler()(act)
|
|
}
|
|
|
|
// predefined action handlers
|
|
|
|
func Forward(act lib.Action) bool {
|
|
ctx := act.Context()
|
|
msg := act.Message()
|
|
for _, rcvr := range act.Spec().Receivers() {
|
|
addr := message.SimpleAddress(rcvr)
|
|
lib.Send(ctx, addr, msg)
|
|
}
|
|
return true
|
|
}
|