aboutsummaryrefslogtreecommitdiffstats
path: root/src/Reaktor/Plugins/System.hs
blob: f31f64060e164e03d0fc154f6f72d117568b068a (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
202
203
204
205
206
207
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Reaktor.Plugins.System (new) where

import Blessings
import Control.Applicative
import Control.Concurrent (forkIO)
import Control.Exception
import qualified Data.HashMap.Lazy as M
import qualified Data.List as L
import qualified Data.Text.Extended as T
import qualified Data.Text.IO as T
import qualified Data.Vector as V
import Prelude.Extended
import Reaktor
import Reaktor.Plugins.System.Internal
import System.Environment (getEnvironment)
import System.Exit
import System.FilePath.Posix (takeBaseName)
import System.IO (BufferMode(LineBuffering),hSetBuffering)
import System.IO (Handle,hClose,hPutStr,hIsEOF)
import System.Process
import qualified Text.Regex.PCRE.Heavy as RE
import qualified Text.Regex.PCRE.Light as RE


new :: Config -> Actions -> IO (Message -> IO ())
new config@Config{..} actions@Actions{..} = do
    pure $ \case
        Message (Just prefix) cmd (msgtarget:text:[]) | elem cmd ["PRIVMSG", "JOIN"] -> do
          let hooks = maybe [] id (M.lookup cmd cHooks)
          mapM_ (\h -> run1 config actions h prefix msgtarget text) hooks

        Message (Just prefix) "JOIN" (channel:[]) -> do
          let hooks = maybe [] id (M.lookup "JOIN" cHooks)
          mapM_ (\h -> run1 config actions h prefix channel "") hooks

        _ -> pure ()


run1 :: Config -> Actions -> Hook -> Text -> Text -> Text -> IO ()
run1 Config{..} Actions{..} Hook{..} prefix msgtarget text = do
    nick <- aGetNick

    let
        isActivated =
          case hActivate of
            Always -> Just ""
            Match ->
              case hPattern of
                Nothing -> Nothing
                Just pat ->
                  let
                      result = RE.scan patternRE text
                      patternRE = RE.compile pat [RE.utf8]
                  in
                    if null result
                      then Nothing
                      else Just ""
            Query ->
              if
                | T.isPrefixOf (nick <> ":") text ->
                  Just (nick <> ":")
                | T.isPrefixOf "*:" text ->
                  Just "*:"
                | isQuery ->
                  Just ""
                | otherwise ->
                  Nothing

        audience = if isQuery then from else msgtarget

        from = T.takeWhile (/='!') prefix

        -- TODO check if msgtarget is one of our channels?
        --      what if our nick has changed?
        isQuery = msgtarget == nick

    case isActivated of
      Just trigger -> do
        let
            cmdline = T.dropWhile (==' ') $ T.drop (T.length trigger) text
            resultPrefix = if isQuery then [] else [from <> ":"]

            parseCommandLine' pat s =
                if null result then [] else snd (head result)
              where
                result = RE.scan patternRE s
                patternRE = RE.compile pat [RE.utf8]

            captures =
              V.fromList $
                case hPattern of
                  Nothing -> [] -- TODO everything?
                  Just pat -> parseCommandLine' pat cmdline

            capture i = captures V.!? (i - 1)

            name =
              case hCommand of
                Capture i -> fromMaybe "<unnamed>" (capture i)
                CaptureOr Command{..} -> T.pack $ takeBaseName $ commandPath

            command =
              case hCommand of
                Capture i -> (`M.lookup` hCommands) =<< capture i
                CaptureOr c -> Just c

            args =
              map (maybe "" T.unpack)
                $ L.dropWhileEnd isNothing
                -- $ map getArgument hArguments
                $ flip map hArguments
                $ \case
                  Capture i -> capture i
                  CaptureOr s -> Just s

        case command of
          Just Command{..} -> do
            baseEnv <- getEnvironment

            let
                onExit code = do
                  let s = T.show code
                      (sig, col) =
                        if code == ExitSuccess
                          then (SGR [38,5,235] "* ", SGR [38,5,107])
                          else (SGR [38,5,235] "! ", SGR [31,1])
                  aLog $ sig <> col (Plain $ name <> ": " <> s)

                onExcept :: SomeException -> IO ()
                onExcept e = do
                  let s0 = T.show e
                      s = T.replace (T.pack commandPath) name s0
                  aLog $ SGR [38,5,235] "! "
                      <> SGR [31,1] (Plain $ name <> ": " <> s0)
                  aSend (privmsg audience (resultPrefix <> [s]))

                -- TODO use differenct colors
                onErrLine s = aSend (privmsg audience [s])
                onOutLine s = aSend (privmsg audience [s])

                extraEnv =
                    [ ("_prefix", T.unpack prefix)
                    , ("_from", T.unpack from)
                    ]

                env =
                  M.toList $ mconcat
                    [ M.fromList extraEnv
                    , maybe mempty id commandEnv
                    , M.fromList baseEnv
                    ]

                cwd = commandWorkDir <|> hWorkDir <|> cWorkDir

            fork commandPath args cwd (Just env) "" onOutLine onErrLine onExit
              `catch` onExcept

          Nothing -> do
            let s = name <> ": command not found"
            aSend (privmsg audience (resultPrefix <> [s]))

      Nothing -> return ()

fork :: FilePath
     -> [String]
     -> Maybe FilePath
     -> Maybe [(String, String)]
     -> String
     -> (Text -> IO ())
     -> (Text -> IO ())
     -> (ExitCode -> IO ())
     -> IO ()
fork path args cwd env input onOutLine onErrLine onExit = do
    let
        p = (proc path args)
              { cwd = cwd
              , env = env
              , std_in = CreatePipe
              , std_out = CreatePipe
              , std_err = CreatePipe
              , close_fds = True
              , create_group = True
              , new_session = True
              }
    withCreateProcess p $ \(Just inh) (Just outh) (Just errh) ph -> do
      mapM_ forkIO [
          hPutStr inh input `finally` hClose inh,
          hWithLines outh onOutLine,
          hWithLines errh onErrLine
        ]
      waitForProcess ph >>= onExit


hWithLines :: Handle -> (Text -> IO ()) -> IO ()
hWithLines h f = do
    hSetBuffering h LineBuffering
    go `finally` hClose h
  where
    go =
      hIsEOF h >>= \case
        True -> return ()
        False -> T.hGetLine h >>= f >> go