{-# LANGUAGE BlockArguments #-} {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE OverloadedStrings #-} -- For documentation purposes, I find it clearer to ignore eta reduce as it feels more natural for me in this context module Server where import Data.ByteString.Lazy qualified as BL import Data.ByteString.Lazy.Char8 qualified as L8 import Data.Text qualified as T import Data.Text.Encoding qualified as TE import Data.Text.IO qualified as TIO import Data.Text.Lazy qualified as TL import Data.Text.Lazy.Encoding qualified as TLE import FileActions qualified as FA import Network.HTTP.Types import Network.HTTP.Types.URI (urlDecode) import Network.Wai import Network.Wai.Handler.Warp (run) application req respond = case (requestMethod req, pathInfo req) of ("GET", []) -> do content <- TIO.readFile "./app/res/b" -- TODO: move that in fileActions respond $ responseLBS status200 [("Content-Type", "text/html")] $ TLE.encodeUtf8 $ TL.fromStrict $ simpleSite content ("GET", ["edit"]) -> do content <- TIO.readFile "./app/res/b" -- TODO: move that in fileActions respond $ responseLBS status200 [("Content-Type", "text/html")] $ TLE.encodeUtf8 $ TL.fromStrict $ editPage content ("POST", ["edit"]) -> do -- TODO: refactor this shit, add sanitisation, make sure text ends with \n putStrLn "overwriting list" body <- strictRequestBody req print body let args = L8.split '&' body case args of [newList] -> f newList _ -> error "should have exactly one arg" where f newList = do let pair = BL.splitAt 5 newList case pair of ("list=", t) -> do let text = TE.decodeUtf8 (urlDecode True (BL.toStrict t)) FA.write "./app/res/" "b" text _ -> error "incorrect args" respond $ responseLBS status303 [(hLocation, "/")] "Redirecting..." ("POST", ["check", name]) -> do FA.check "./app/res/" "b" name respond $ responseLBS status303 [(hLocation, "/")] "Redirecting..." -- TODO: refactor this using where better and creating meaningfull local functions ("POST", ["add"]) -> do putStrLn "adding item" body <- strictRequestBody req let args = L8.split '&' body case args of [item] -> f item _ -> error "should have exactly one arg" where f item = do let pair = BL.splitAt 5 item case pair of ("text=", t) -> do let text = TE.decodeUtf8 (urlDecode True (BL.toStrict t)) FA.add "./app/res/" "b" text _ -> error "incorrect args" respond $ responseLBS status303 [(hLocation, "/")] "Redirecting..." (method, array) -> do respond $ responseLBS status303 [(hLocation, "/")] "Redirecting..." splitKeyValue bs = case L8.break (== '=') bs of (key, rest) -> (key, L8.drop 1 rest) openingTag tag = "<" <> tag <> ">" closingTag tag = "" <> tag <> ">" wrapContent tag content = openingTag tag <> content <> closingTag tag wrapContentWithArgs tag arg content = openingTag (tag <> " " <> arg) <> content <> closingTag tag singleWrap content = "<" <> content <> "/>" headHtml lang title = " lang <> "\">