@@ -7,12 +7,14 @@ module HTTP (
77
88#ifdef TEST
99, app
10+ , stripAnsi
1011#endif
1112) where
1213
1314import Imports
1415
1516import System.Directory
17+ import qualified Data.ByteString.Lazy as L
1618import Data.Text.Lazy.Encoding (encodeUtf8 )
1719import Network.Wai
1820import Network.HTTP.Types
@@ -58,11 +60,46 @@ withThread asyncAction action = do
5860 return r
5961
6062app :: IO (Trigger. Result , String ) -> Application
61- app trigger _ respond = trigger >>= textPlain
63+ app trigger request respond = trigger >>= textPlain
6264 where
63- textPlain (result, xs) = respond $ responseLBS status [(hContentType, " text/plain" )] (encodeUtf8 . fromString $ xs)
64- where
65- status = case result of
66- Trigger. HookFailed -> internalServerError500
67- Trigger. Failure -> internalServerError500
68- Trigger. Success -> ok200
65+ color :: Either ByteString Bool
66+ color = case join $ lookup " color" $ queryString request of
67+ Nothing -> Right True
68+ Just " false" -> Right False
69+ Just " true" -> Right True
70+ Just value -> Left $ " invalid value for color: " <> urlEncode True value
71+
72+ textPlain :: (Trigger. Result , FilePath ) -> IO ResponseReceived
73+ textPlain (result, xs) = case color of
74+ Left err -> respond $ responseLBS status400 [(hContentType, " text/plain" )] (L. fromStrict err)
75+ Right c -> respond $ responseLBS status [(hContentType, " text/plain" )] (encodeUtf8 . fromString $ strip xs)
76+ where
77+ strip :: String -> String
78+ strip
79+ | c = id
80+ | otherwise = stripAnsi
81+
82+ status = case result of
83+ Trigger. HookFailed -> status500
84+ Trigger. Failure -> status500
85+ Trigger. Success -> status200
86+
87+ -- |
88+ -- Remove terminal sequences.
89+ stripAnsi :: String -> String
90+ stripAnsi = go
91+ where
92+ go input = case input of
93+ ' \ESC ' : ' [' : (dropNumericParameters -> c : xs) | isCommand c -> go xs
94+ ' \ESC ' : ' [' : ' ?' : (dropNumericParameters -> c : xs) | isCommand c -> go xs
95+ x : xs -> x : go xs
96+ [] -> []
97+
98+ dropNumericParameters :: FilePath -> FilePath
99+ dropNumericParameters = dropWhile (`elem` (" 0123456789;" :: [Char ]))
100+
101+ isCommand :: Char -> Bool
102+ isCommand = (`elem` commands)
103+
104+ commands :: FilePath
105+ commands = [' A' .. ' Z' ] <> [' a' .. ' z' ]
0 commit comments