2023-01-29 12:08:50 +01:00
|
|
|
{-# LANGUAGE FlexibleContexts #-}
|
|
|
|
|
2023-01-28 19:08:33 +01:00
|
|
|
module RoomDataHandler
|
|
|
|
( roomDataHandler,
|
|
|
|
)
|
|
|
|
where
|
|
|
|
|
|
|
|
import BroadcastUserData (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)
|
2023-01-28 19:08:33 +01:00
|
|
|
import Network.HTTP.Types (status200, status500)
|
|
|
|
import Network.Wai
|
|
|
|
( ResponseReceived,
|
|
|
|
consumeRequestBodyStrict,
|
|
|
|
responseLBS,
|
|
|
|
)
|
|
|
|
import Types.AppTypes (HasConnectedClientState)
|
|
|
|
import Types.RoomsState
|
|
|
|
( HasRoomsState,
|
|
|
|
roomStateDiffers,
|
|
|
|
updateRoomState,
|
|
|
|
)
|
|
|
|
import Types.WebEnv (HasWebEnv (getRequest), getRespond)
|
|
|
|
|
|
|
|
roomDataHandler ::
|
|
|
|
( MonadIO m,
|
|
|
|
HasWebEnv env,
|
|
|
|
HasConnectedClientState env,
|
|
|
|
MonadReader env m,
|
2023-01-29 12:08:50 +01:00
|
|
|
MonadError ResponseReceived m,
|
2023-01-28 19:08:33 +01:00
|
|
|
HasRoomsState env
|
|
|
|
) =>
|
|
|
|
m ResponseReceived
|
|
|
|
roomDataHandler = do
|
2023-01-29 12:08:50 +01:00
|
|
|
newRoomData <- parseBodyOrBadRequest
|
|
|
|
whenM (roomStateDiffers newRoomData) $ do
|
|
|
|
updateRoomState newRoomData
|
|
|
|
broadcastUserData
|
|
|
|
success
|
|
|
|
|
|
|
|
parseBodyOrBadRequest ::
|
|
|
|
( MonadIO m,
|
|
|
|
HasWebEnv env,
|
|
|
|
MonadReader env m,
|
|
|
|
MonadError ResponseReceived m,
|
|
|
|
FromJSON a
|
|
|
|
) =>
|
|
|
|
m a
|
|
|
|
parseBodyOrBadRequest = do
|
2023-01-28 19:08:33 +01:00
|
|
|
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
|
2023-01-28 19:08:33 +01:00
|
|
|
|
|
|
|
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
|
|
|
|
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")]
|
|
|
|
""
|