summaryrefslogtreecommitdiff
path: root/Hsbot/Irc/Command.hs
blob: 3f5c8c1d1a3a97f27788c212cd92564a86e449b6 (plain)
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
module Hsbot.Irc.Command
    ( processInternalCommand
    , registerCommand
    , unregisterCommand
    ) where

import Control.Monad.State
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe

import Hsbot.Irc.Message
import Hsbot.Irc.Plugin
import Hsbot.Irc.Types

-- | Registers a plugin's command
registerCommand :: String -> String -> IrcBot ()
registerCommand cmd pluginName' = do
    ircBot  <- get
    let cmds    = ircBotCommands ircBot
        plugins = ircBotPlugins ircBot
    case M.lookup pluginName' plugins of
        Just _  -> let pluginNames = pluginName' : fromMaybe [] (M.lookup cmd cmds) -- TODO : remove/check for duplicates ?
                       newCmds     = M.insert cmd pluginNames cmds
                   in  put $ ircBot { ircBotCommands = newCmds }
        Nothing -> return ()

-- | Unregisters a plugin's command
unregisterCommand :: String -> String -> IrcBot ()
unregisterCommand cmd pluginName' = do
    ircBot    <- get
    let cmds    = ircBotCommands ircBot
        newCmds = M.adjust (L.delete pluginName') cmd cmds
    put $ ircBot { ircBotCommands = newCmds }

-- | Processes an internal command
processInternalCommand :: IrcBotMsg -> IrcBot ()
processInternalCommand (IntIrcCmd ircCmd)
  | ircCmdTo ircCmd == "CORE" = processCoreCommand ircCmd
  | otherwise = do
      plugins <- gets ircBotPlugins
      case M.lookup (ircCmdTo ircCmd) plugins of
          Just plugin -> sendToPlugin (IntIrcCmd ircCmd) plugin
          Nothing     -> return ()
processInternalCommand _ = return ()

-- | Processes a core command
processCoreCommand :: IrcCmd -> IrcBot ()
processCoreCommand ircCmd = do
    let command' = ircCmdCmd ircCmd
        originalRequest = ircCmdBotMsg ircCmd
    case command' of
        "LIST"       -> listPlugins originalRequest (ircCmdFrom ircCmd)
        "LOAD"       -> loadIrcPlugin $ ircCmdMsg ircCmd
        "UNLOAD"     -> unloadPlugin $ ircCmdMsg ircCmd
        "REGISTER"   -> registerCommand (ircCmdMsg ircCmd) (ircCmdFrom ircCmd)
        "UNREGISTER" -> unregisterCommand (ircCmdMsg ircCmd) (ircCmdFrom ircCmd)
        _            -> return ()