module Network.IRC.Client.Utils
(
setNick
, leaveChannel
, delChan
, addHandler
, reply
, replyTo
, ctcp
, ctcpReply
, isConnected
, isDisconnecting
, isDisconnected
, snapConnState
, fork
, snapshot
, snapshotModify
, get
, set
, modify
) where
import Control.Concurrent (ThreadId, myThreadId, forkFinally)
import Control.Concurrent.STM (TVar, STM, atomically, modifyTVar)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Network.IRC.Conduit (Event(..), Message(..), Source(..))
import Network.IRC.CTCP (toCTCP)
import Network.IRC.Client.Internal
import Network.IRC.Client.Lens
setNick :: Text -> IRC s ()
setNick new = do
tvarI <- get instanceConfig <$> getIRCState
liftIO . atomically $
modifyTVar tvarI (set nick new)
send $ Nick new
leaveChannel :: Text -> Maybe Text -> IRC s ()
leaveChannel chan reason = do
tvarI <- get instanceConfig <$> getIRCState
liftIO . atomically $ delChan tvarI chan
send $ Part chan reason
delChan :: TVar (InstanceConfig s) -> Text -> STM ()
delChan tvarI chan =
modifyTVar tvarI (modify channels (filter (/=chan)))
addHandler :: EventHandler s -> IRC s ()
addHandler handler = do
tvarI <- get instanceConfig <$> getIRCState
liftIO . atomically $
modifyTVar tvarI (modify handlers (handler:))
reply :: Event Text -> Text -> IRC s ()
reply = replyTo . _source
replyTo :: Source Text -> Text -> IRC s ()
replyTo (Channel c _) = mapM_ (send . Privmsg c . Right) . T.lines
replyTo (User n) = mapM_ (send . Privmsg n . Right) . T.lines
replyTo _ = const $ pure ()
ctcp :: Text -> Text -> [Text] -> Message Text
ctcp t command args = Privmsg t . Left $ toCTCP command args
ctcpReply :: Text -> Text -> [Text] -> Message Text
ctcpReply t command args = Notice t . Left $ toCTCP command args
isConnected :: IRC s Bool
isConnected = (==Connected) <$> snapConnState
isDisconnecting :: IRC s Bool
isDisconnecting = (==Disconnecting) <$> snapConnState
isDisconnected :: IRC s Bool
isDisconnected = (==Disconnected) <$> snapConnState
snapConnState :: IRC s ConnectionState
snapConnState = liftIO . atomically . getConnectionState =<< getIRCState
fork :: IRC s () -> IRC s ThreadId
fork ma = do
s <- getIRCState
liftIO $ do
tid <- forkFinally (runIRCAction ma s) $ \_ -> do
tid <- myThreadId
atomically $ modifyTVar (_runningThreads s) (S.delete tid)
atomically $ modifyTVar (_runningThreads s) (S.insert tid)
pure tid