Add a session module to save and restore the playerID sent by the server (and make hannah persistent accross her reboots)

This commit is contained in:
Tissevert 2019-11-20 18:30:59 +01:00
parent 064606ae83
commit 4529d19301
3 changed files with 50 additions and 0 deletions

View File

@ -21,15 +21,19 @@ executable hannah
other-modules: AI other-modules: AI
, Automaton , Automaton
, Config , Config
, Session
-- other-extensions: -- other-extensions:
build-depends: aeson build-depends: aeson
, base >=4.9 && <4.13 , base >=4.9 && <4.13
, bytestring , bytestring
, containers , containers
, directory
, filepath
, hanafuda , hanafuda
, hanafuda-APILanguage , hanafuda-APILanguage
, mtl , mtl
, text , text
, websockets , websockets
hs-source-dirs: src hs-source-dirs: src
ghc-options: -Wall
default-language: Haskell2010 default-language: Haskell2010

View File

@ -1,5 +1,6 @@
module Config ( module Config (
host host
, libDir
, path , path
, port , port
) where ) where
@ -7,6 +8,9 @@ module Config (
host :: String host :: String
host = "koikoi.menf.in" host = "koikoi.menf.in"
libDir :: FilePath
libDir = "/var/lib/hannah"
path :: String path :: String
path = "/play/" path = "/play/"

42
src/Session.hs Normal file
View File

@ -0,0 +1,42 @@
{-# LANGUAGE NamedFieldPuns #-}
module Session (
State(..)
, initial
, store
) where
import Config (libDir)
import Data.Map (Map)
import qualified Data.Map as Map (empty)
import Hanafuda.KoiKoi (PlayerID)
import qualified Hanafuda.Message as Message (PublicGame)
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath ((</>))
data State =
New
| Connected {
playerID :: PlayerID
, games :: Map PlayerID Message.PublicGame
}
deriving Show
stateFile :: FilePath
stateFile = libDir </> "state"
ifM :: IO Bool -> IO a -> IO a -> IO a
ifM condition caseTrue caseFalse =
condition >>= (\b -> if b then caseTrue else caseFalse)
initial :: IO State
initial = do
createDirectoryIfMissing True libDir
ifM (doesFileExist stateFile)
(do
playerID <- read <$> readFile stateFile
return $ Connected {playerID, games = Map.empty}
)
(return New)
store :: PlayerID -> IO ()
store = writeFile stateFile . show