jitsi-roomsv2/backend/src/RoomDataHandler.hs

106 lines
2.3 KiB
Haskell
Raw Normal View History

2023-01-29 12:08:50 +01:00
{-# LANGUAGE FlexibleContexts #-}
module RoomDataHandler
( roomDataHandler,
)
where
2023-02-19 11:41:32 +01:00
import BroadcastUserData (MonadBroadcast, broadcastUserData)
import ClassyPrelude
2023-01-29 12:08:50 +01:00
import Control.Monad.Except (MonadError, throwError)
import Data.Aeson (eitherDecodeStrict)
import Data.Aeson.Types (FromJSON)
import Network.HTTP.Types (status200, status500)
import Network.Wai
( ResponseReceived,
consumeRequestBodyStrict,
responseLBS,
)
2023-02-19 11:41:32 +01:00
import State.RoomDataState
( MonadRoomDataStateModify (setRoomDataState),
MonadRoomDataStateRead,
)
import Types.RoomsState
2023-08-01 10:21:12 +02:00
( roomStateDiffers,
)
2023-02-19 11:41:32 +01:00
import Types.WebEnv
( HasWebEnv (getRequest),
getRespond,
)
roomDataHandler ::
( MonadIO m,
HasWebEnv env,
MonadReader env m,
2023-01-29 12:08:50 +01:00
MonadError ResponseReceived m,
2023-02-19 11:41:32 +01:00
MonadRoomDataStateRead m,
MonadRoomDataStateModify m,
MonadBroadcast m
) =>
m ResponseReceived
roomDataHandler = do
2023-01-29 12:08:50 +01:00
newRoomData <- parseBodyOrBadRequest
2023-06-19 19:04:53 +02:00
liftIO $ putStrLn "Got triggered from prosody"
2023-01-29 12:08:50 +01:00
whenM (roomStateDiffers newRoomData) $ do
2023-02-19 11:41:32 +01:00
setRoomDataState newRoomData
2023-01-29 12:08:50 +01:00
broadcastUserData
success
parseBodyOrBadRequest ::
( MonadIO m,
HasWebEnv env,
MonadReader env m,
MonadError ResponseReceived m,
FromJSON a
) =>
m a
parseBodyOrBadRequest = do
body <- getRequestBody
case eitherDecodeStrict body of
2023-01-29 12:08:50 +01:00
Left errorMessage -> do
response <- badRequest errorMessage
throwError response
Right newState -> return newState
getRequestBody ::
( MonadIO m,
HasWebEnv env,
MonadReader env m
) =>
m ByteString
getRequestBody = do
request <- getRequest <$> ask
liftIO $ toStrict <$> consumeRequestBodyStrict request
badRequest ::
( MonadIO m,
HasWebEnv env,
MonadReader env m
) =>
String ->
m ResponseReceived
badRequest errorMessage = do
respond' <- getRespond <$> ask
2023-02-07 20:30:25 +01:00
liftIO $ print errorMessage
liftIO $
respond' $
responseLBS
status500
[("Content-Type", "text/plain")]
2023-01-29 12:08:50 +01:00
(fromString ("Bad request. Reason: " <> errorMessage))
success ::
( MonadIO m,
HasWebEnv env,
MonadReader env m
) =>
m ResponseReceived
success = do
respond' <- getRespond <$> ask
liftIO $
respond' $
responseLBS
status200
[("Content-Type", "text/plain")]
""