packages feed

htalkat-0.1.2: User.hs

-- This file is part of htalkat
-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of version 3 of the GNU General Public License as
-- published by the Free Software Foundation, or any later version.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see http://www.gnu.org/licenses/.

{-# LANGUAGE Safe #-}

module User
    ( User(..)
    , parseUser
    , showUser
    ) where

import           Control.Monad  (guard, msum)
import           Data.List      (stripPrefix)

import           Fingerprint
import           Host

#if !(MIN_VERSION_base(4,11,0))
import           Data.Semigroup
#endif

data User = User
    { userFP   :: Fingerprint
    , userHost :: Maybe Host
    }

parseUser,parseUser' :: String -> Maybe User
parseUser s | Just s' <- stripPrefix "talkat:" s = parseUser' s'
parseUser s = parseUser' s
parseUser' s = do
    let (fpStr,rest) = splitAt 32 s
    fp <- parseFingerprint fpStr
    msum [ guard (null rest) >> pure (User fp Nothing)
        , do
            '@':hostStr <- pure rest
            host <- parseHost hostStr
            pure . User fp $ Just host
        ]

showUser :: User -> String
showUser (User fp Nothing)     = showFingerprint fp
showUser (User fp (Just host)) = showFingerprint fp <> "@" <> showHost host