hask-irc/Network/IRC/Protocol.hs

66 lines
2.9 KiB
Haskell
Raw Normal View History

2014-05-13 00:00:33 +05:30
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
2014-05-04 02:57:43 +05:30
2014-05-04 07:43:37 +05:30
module Network.IRC.Protocol (msgFromLine, lineFromCommand) where
2014-05-04 02:57:43 +05:30
2014-05-10 21:45:16 +05:30
import ClassyPrelude
import Data.List ((!!))
import Data.Text (split)
2014-05-04 02:57:43 +05:30
import Network.IRC.Types
2014-05-10 21:45:16 +05:30
msgFromLine :: BotConfig -> UTCTime -> Text -> Message
2014-05-04 04:28:44 +05:30
msgFromLine (BotConfig { .. }) time line
| "PING :" `isPrefixOf` line = PingMsg time (drop 6 line) line
2014-05-04 02:57:43 +05:30
| otherwise = case command of
"PONG" -> PongMsg time message line
"JOIN" -> JoinMsg time user line
"QUIT" -> QuitMsg time user quitMessage line
"PART" -> PartMsg time user message line
"KICK" -> KickMsg time user kicked kickReason line
2014-05-04 02:57:43 +05:30
"MODE" -> if source == botNick
2014-05-20 02:40:08 +05:30
then ModeMsg time Self target message [] line
else ModeMsg time user target mode modeArgs line
"NICK" -> NickMsg time user (drop 1 target) line
"353" -> NamesMsg time namesNicks
"433" -> NickInUseMsg time line
2014-05-20 02:40:08 +05:30
"PRIVMSG" | target /= channel -> PrivMsg time user message line
| isActionMsg -> ActionMsg time user (initDef . drop 8 $ message) line
| otherwise -> ChannelMsg time user message line
_ -> OtherMsg time source command target message line
2014-05-04 02:57:43 +05:30
where
isSpc = (== ' ')
isNotSpc = not . isSpc
splits = split isSpc line
source = drop 1 . takeWhile isNotSpc $ line
target = splits !! 2
command = splits !! 1
message = drop 1 . unwords . drop 3 $ splits
quitMessage = drop 1 . unwords . drop 2 $ splits
user = uncurry User . break (== '!') $ source
mode = splits !! 3
modeArgs = drop 4 splits
kicked = splits !! 3
kickReason = drop 1 . unwords . drop 4 $ splits
nickPrefixes :: String
nickPrefixes = "~&@%+"
namesNicks = map stripNickPrefix . words . drop 1 . unwords . drop 5 $ splits
stripNickPrefix = pack . dropWhile (`elem` nickPrefixes) . unpack
2014-05-04 02:57:43 +05:30
2014-05-20 02:40:08 +05:30
isActionMsg = "\SOH" `isPrefixOf` message && "ACTION" `isPrefixOf` drop 1 message
lineFromCommand :: BotConfig -> Command -> Maybe Text
lineFromCommand BotConfig { .. } command = case command of
PongCmd { .. } -> Just $ "PONG :" ++ rmsg
PingCmd { .. } -> Just $ "PING :" ++ rmsg
NickCmd -> Just $ "NICK " ++ botNick
UserCmd -> Just $ "USER " ++ botNick ++ " 0 * :" ++ botNick
JoinCmd -> Just $ "JOIN " ++ channel
QuitCmd -> Just "QUIT"
ChannelMsgReply { .. } -> Just $ "PRIVMSG " ++ channel ++ " :" ++ rmsg
2014-05-22 03:23:57 +05:30
PrivMsgReply (User { .. }) rmsg -> Just $ "PRIVMSG " ++ userNick ++ " :" ++ rmsg
2014-05-20 02:40:08 +05:30
NamesCmd -> Just $ "NAMES " ++ channel
_ -> Nothing