aboutsummaryrefslogtreecommitdiffstats
path: root/src/Reaktor.hs
blob: e35792f2f74b1ec5e223d68e3116fb6566d7275d (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Reaktor
    ( module Exports
    , privmsg
    , run
    ) where

import Blessings
import Control.Concurrent.Extended
import Control.Exception
import Data.Attoparsec.Text (feed,parse)
import Data.Attoparsec.Text (IResult(Done,Fail,Partial))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8.Extended as BS
import qualified Data.Text.Encoding as T
import qualified Data.Text.Extended as T
import Data.Foldable (toList)
import Data.Time.Clock.System
import Data.Time.Format
import qualified Network.Simple.TCP as TCP
import qualified Network.Simple.TCP.TLS as TLS
import Network.Socket as Exports (HostName,ServiceName)
import Prelude.Extended
import Reaktor.Internal
import Reaktor.Internal as Exports (Actions(..))
import Reaktor.Internal as Exports (Message(Message,Start))
import Reaktor.Internal as Exports (formatMessage)
import Reaktor.Nick as Exports
import Reaktor.Nick as Nick
import qualified Reaktor.Parser as Parser
import qualified System.IO
import System.IO (BufferMode(LineBuffering),hSetBuffering)
import System.IO (hIsTerminalDevice)
import System.Posix.Signals


run :: Config -> (Actions -> IO [Message -> IO ()]) -> IO ()
run Config{..} getPlugins =
    if cUseTLS then do
      s <- TLS.getDefaultClientSettings (cHostName, BS.pack cServiceName)
      TLS.connect s cHostName cServiceName $ \(ctx, sockAddr) ->
        withSocket sockAddr (TLS.send ctx) (TLS.recv ctx)
    else do
      TCP.connect cHostName cServiceName $ \(sock, sockAddr) ->
        withSocket sockAddr (TCP.send sock) (TCP.recv sock 512)
  where
    withSocket _sockAddr sockSend sockRecv = do

      hSetBuffering cLogHandle LineBuffering -- TODO reset
      logToTTY <- hIsTerminalDevice cLogHandle
      (putLog, takeLog0) <- newChan
      let
          takeLog1 = if cLogTime then takeLog0 >>= prefixTimestamp else takeLog0
          takeLog2 = if logToTTY then takeLog1 else stripSGR <$> takeLog1
          takeLog = takeLog2

      (putInMsg, takeInMsg) <- newChan
      (putOutMsg, takeOutMsg) <- newChan
      (shutdown, awaitShutdown) <- newSemaphore
      (aSetNick,aGetNick) <- newRef =<< maybe Nick.getRandom return cNick

      let actions = Actions{..}
          aIsSecure = cUseTLS
          aLog = putLog
          aSend msg = logMsg msg >> putOutMsg msg

          logMsg msg =
              case logMsgFilter msg of
                Just msg' -> do
                  let bs = formatMessage msg'
                  aLog $ SGR [38,5,235] "> " <> SGR [35,1] (Plain bs)
                Nothing -> return ()

      mapM_ (\(s, f) -> installHandler s (Catch f) Nothing) [
          (sigINT, shutdown)
        ]

      plugins <- getPlugins actions

      threads <- mapM (\f -> forkIO $ f `finally` shutdown) [
          receiver actions putInMsg sockRecv,
          logger cLogHandle takeLog,
          pinger aSend,
          sender takeOutMsg sockSend,
          splitter plugins takeInMsg
        ]

      putInMsg Start

      awaitShutdown
      mapM_ killThread threads
      putStrLn ""


logger :: System.IO.Handle -> IO (Blessings Text) -> IO ()
logger h takeLog = forever $ do
    s <- takeLog
    let s' = if lastChar s == '\n' then s else s <> Plain "\n"
    System.IO.hPutStr h $ pp $ fmap T.unpack s'

pinger :: (Message -> IO ()) -> IO ()
pinger aSend = forever $ do
    threadDelay time
    aSend (Message Nothing "PING" ["heartbeat"])
  where
    time = 300 * 1000000

receiver :: Actions -> (Message -> IO ()) -> IO (Maybe ByteString) -> IO ()
receiver Actions{..} putInMsg sockRecv =
    receive ""
  where
    decode :: ByteString -> Text
    decode = T.decodeUtf8With (\_err _c -> Just '?')

    receive :: Text -> IO ()
    receive "" =
        sockRecv >>= \case
          Nothing -> logErr "EOL"
          Just buf -> receive (decode buf)

    receive buf =
        go (parse Parser.message buf)
      where
        go :: IResult Text Message -> IO ()
        go = \case
            Done rest msg -> do
              logMsg msg
              putInMsg msg
              receive rest

            p@(Partial _) ->
              sockRecv >>= \case
                Nothing -> logErr ("EOF with partial " <> Plain (T.show p))
                Just buf' -> go (feed p (decode buf'))

            f@(Fail _i _errorContexts _errMessage) ->
              logErr ("failed to parse message: " <> Plain (T.show f))

    logErr s = aLog $ SGR [31,1] ("! receive: " <> s)

    logMsg msg =
        case logMsgFilter msg of
          Just msg' -> do
            let bs = formatMessage msg'
            aLog $ SGR [38,5,235] "< " <> SGR [38,5,244] (Plain bs)
          Nothing -> return ()


sender :: IO Message -> (ByteString -> IO ()) -> IO ()
sender takeOutMsg sockSend =
    forever $ takeOutMsg >>= sockSend . T.encodeUtf8 . formatMessage

splitter :: [Message -> IO ()] -> IO Message -> IO ()
splitter plugins takeInMsg =
    forever $ do
      msg <- takeInMsg
      mapM_ (\f -> forkIO (f msg)) plugins


logMsgFilter :: Message -> Maybe Message
logMsgFilter = \case
    Message _ "PING" _ -> Nothing
    Message _ "PONG" _ -> Nothing
    Message p "PRIVMSG" ["NickServ",xs] | check -> do
        Just (Message p "PRIVMSG" ["NickServ",xs'])
      where
        check = elem cmd ["IDENTIFY","REGAIN"] && length ws > 2
        ws = T.words xs
        (cmd:ws') = ws
        (nick:_) = ws'
        xs' = T.unwords [cmd, nick, "<password>"]
    msg -> Just msg


privmsg :: Text -> [Text] -> Message
privmsg msgtarget xs =
    Message Nothing "PRIVMSG" (msgtarget:T.intercalate " " xs:[])


lastChar :: Blessings Text -> Char
lastChar = T.last . last . toList

prefixTimestamp :: Blessings Text -> IO (Blessings Text)
prefixTimestamp s = do
    t <- SGR [38,5,239] . Plain . T.pack <$> getTimestamp
    return (t <> " " <> s)

stripSGR :: Blessings a -> Blessings a
stripSGR = \case
    Append t1 t2 -> Append (stripSGR t1) (stripSGR t2)
    SGR _ t -> stripSGR t
    Plain x -> Plain x
    Empty -> Empty


getTimestamp :: IO String
getTimestamp =
    formatTime defaultTimeLocale (iso8601DateFormat $ Just "%H:%M:%SZ")
    . systemToUTCTime <$> getSystemTime