gorepost/bot/dispatcher.go

65 lines
2.1 KiB
Go
Raw Normal View History

2015-11-12 09:07:53 +00:00
// Copyright 2015 Robert S. Gerus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
2015-11-08 19:55:47 +00:00
package bot
import (
"log"
"strings"
2015-12-09 10:27:55 +00:00
"sync"
2015-11-08 19:55:47 +00:00
"github.com/arachnist/gorepost/irc"
)
var callbacks = make(map[string]map[string]func(func(irc.Message), irc.Message))
2015-12-09 10:27:55 +00:00
var callbackLock sync.RWMutex
2015-11-08 19:55:47 +00:00
2015-11-12 08:30:12 +00:00
// addCallback registers callbacks that can be later dispatched by Dispatcher
func addCallback(command, name string, callback func(func(irc.Message), irc.Message)) {
2015-12-09 10:27:55 +00:00
callbackLock.Lock()
defer callbackLock.Unlock()
2015-11-09 07:00:13 +00:00
log.Println("adding callback", command, name)
2015-11-11 20:38:33 +00:00
if _, ok := callbacks[command]; !ok {
callbacks[command] = make(map[string]func(func(irc.Message), irc.Message))
2015-11-09 07:00:13 +00:00
}
callbacks[strings.ToUpper(command)][name] = callback
}
2015-11-12 08:30:12 +00:00
// Dispatcher takes irc messages and dispatches them to registered callbacks.
//
// It will take an input message, check (based on message context), if the
// message should be dispatched, and passes it to registered callback.
func Dispatcher(output func(irc.Message), input irc.Message) {
2015-11-18 14:21:02 +00:00
if _, ok := cfg.LookupStringMap(input.Context, "Ignore")[input.Context["Source"]]; ok {
log.Println("Context:", input.Context, "Ignoring", input.Context["Source"])
return
2015-11-08 19:55:47 +00:00
}
2015-11-18 14:21:02 +00:00
2015-12-09 10:27:55 +00:00
callbackLock.RLock()
defer callbackLock.RUnlock()
if callbacks[input.Command] != nil {
if len(cfg.LookupStringMap(input.Context, "WhitelistedPlugins")) > 0 {
2015-11-18 15:24:30 +00:00
for i, f := range callbacks[input.Command] {
if _, ok := cfg.LookupStringMap(input.Context, "DisabledPlugins")[i]; ok {
log.Println("Context:", input.Context, "Plugin disabled", i)
continue
2015-11-18 15:24:30 +00:00
}
if _, ok := cfg.LookupStringMap(input.Context, "WhitelistedPlugins")[i]; ok {
go f(output, input)
} else {
log.Println("Context:", input.Context, "Plugin not whitelisted", i)
}
}
} else {
for i, f := range callbacks[input.Command] {
if _, ok := cfg.LookupStringMap(input.Context, "DisabledPlugins")[i]; ok {
log.Println("Context:", input.Context, "Plugin disabled", i)
continue
2015-11-18 15:24:30 +00:00
}
go f(output, input)
}
}
}
2015-11-08 19:55:47 +00:00
}