{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.CURL.CookieJar.PrettyPrinter
( prettyCookieJar
, CookieJarHeader(..)
, prettyCookieJarHeader
, prettyCookie
, toLazyByteString
) where
import Data.Semigroup ((<>))
import Network.HTTP.Client (Cookie(..), CookieJar, destroyCookieJar)
import Data.ByteString.Builder
( Builder
, byteString
, integerDec
, char7
, toLazyByteString
)
import Data.Foldable (foldMap)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
data CookieJarHeader
= NoHeader
| HTTPHeader
| NetscapeHeader
prettyCookieJar :: CookieJarHeader -> CookieJar -> Builder
prettyCookieJar header jar =
prettyCookieJarHeader header
<> foldMap ((<> "\n") . prettyCookie) (destroyCookieJar jar)
prettyCookieJarHeader :: CookieJarHeader -> Builder
prettyCookieJarHeader NoHeader = mempty
prettyCookieJarHeader HTTPHeader = "# HTTP Cookie File\n"
prettyCookieJarHeader NetscapeHeader = "# Netscape HTTP Cookie File\n"
prettyCookie :: Cookie -> Builder
prettyCookie (Cookie {..}) =
byteString cookie_domain
<> tab
<> bool cookie_host_only
<> tab
<> byteString cookie_path
<> tab
<> bool cookie_secure_only
<> tab
<> unixTime cookie_expiry_time
<> tab
<> byteString cookie_name
<> tab
<> byteString cookie_value
where
bool True = "TRUE"
bool False = "FALSE"
unixTime = integerDec . round . utcTimeToPOSIXSeconds
tab = char7 '\t'