~alcinnz/amphiarao

ref: 505d1225cb268cff416cc3a01cc55f2932f92861 amphiarao/src/Webdriver.hs -rw-r--r-- 1.7 KiB
505d1225 — Adrian Cochrane init 3 years ago
                                                                                
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
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, DeriveGeneric #-}
module Webdriver(serveWebdriver, WDSession(..)) where

import Happstack.Lite
import Happstack.Server.Types (unBody, takeRequestBody)
import Happstack.Server (askRq)
import Control.Concurrent.MVar
import Data.Aeson
import Data.Text (Text)
import GHC.Generics
import Data.ByteString.Lazy (ByteString)

import qualified Data.Map.Strict as M
import Data.UUID
import Data.UUID.V4

import Control.Monad.IO.Class (liftIO)
import Data.Maybe (fromMaybe)

data WDSession = WDSession -- TODO: Add fields

serveWebdriver :: MVar (M.Map UUID WDSession) -> ServerPart Response
serveWebdriver sessions = msum [
    dir "status" serveStatus,
    dir "session" $ postSession sessions
  ]

data Status = Status {ready :: Bool, message :: Text} deriving Generic
instance ToJSON Status
serveStatus = okJSON $ Status True "Always ready to open new sessions"

data NewSession = NewSession {sessionId :: UUID, capabilities :: Value} deriving Generic
instance ToJSON NewSession
postSession sessions = do
    method POST
    caps <- fromMaybe Null <$> getJSON
    -- FIXME: Validate provided capabilities.
    uuid <- liftIO nextRandom
    let session = WDSession
    liftIO $ modifyMVar_ sessions (return . M.insert uuid session)
    okJSON $ NewSession uuid caps

--------
---- Utils
--------
getBody :: ServerPart ByteString
getBody = do
    req  <- askRq 
    body <- liftIO $ takeRequestBody req 
    case body of 
        Just rqbody -> return . unBody $ rqbody 
        Nothing     -> return "" 

getJSON :: FromJSON x => ServerPart (Maybe x)
getJSON = decode <$> getBody

okJSON :: ToJSON x => x -> ServerPart Response
okJSON x = do
    setHeaderM "Content-Type" "application/json"
    ok $ toResponse $ encode x