packages feed

okf-core-0.14.0.0: src/Okf/Timestamp.hs

-- | Timestamp parsing shared by verification, freshness and profile checks.
module Okf.Timestamp (parseTimestamp) where

import Control.Applicative ((<|>))
import Control.Monad (replicateM)
import Data.Attoparsec.Text qualified as Atto
import Data.Char (digitToInt, isDigit)
import Data.Fixed (Pico)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Time (Day, LocalTime (..), UTCTime (..), fromGregorianValid, localTimeToUTC, makeTimeOfDayValid, minutesToTimeZone, utc)

-- | Parse an RFC 3339 date-time with a mandatory offset, or a date representing
-- midnight UTC. Compare the returned instants independently of their spelling.
parseTimestamp :: Text -> Maybe UTCTime
parseTimestamp = either (const Nothing) Just . Atto.parseOnly (timestamp <* Atto.endOfInput)
  where
    timestamp = do
      day <- calendarDay
      Atto.option (UTCTime day 0) (dateTime day)

    dateTime day = do
      _ <- Atto.satisfy (\c -> c == 'T' || c == 't')
      hours <- twoDigits
      _ <- Atto.char ':'
      minutes <- twoDigits
      _ <- Atto.char ':'
      seconds <- twoDigits
      fraction <- Atto.option 0 (Atto.char '.' *> fractionalSeconds)
      zone <- (utc <$ Atto.satisfy (\c -> c == 'Z' || c == 'z')) <|> utcOffset
      clock <- maybe (fail "invalid time") pure (makeTimeOfDayValid hours minutes (fromIntegral seconds + fraction))
      pure (localTimeToUTC zone (LocalTime day clock))

    utcOffset = do
      sign <- (negate <$ Atto.char '-') <|> (id <$ Atto.char '+')
      hours <- twoDigits
      _ <- Atto.char ':'
      minutes <- twoDigits
      if hours < 24 && minutes < 60
        then pure (minutesToTimeZone (sign (hours * 60 + minutes)))
        else fail "invalid UTC offset"

calendarDay :: Atto.Parser Day
calendarDay = do
  year <- fixedDigits 4
  _ <- Atto.char '-'
  month <- twoDigits
  _ <- Atto.char '-'
  day <- twoDigits
  maybe (fail "invalid date") pure (fromGregorianValid (fromIntegral year) month day)

twoDigits :: Atto.Parser Int
twoDigits = fixedDigits 2

fixedDigits :: Int -> Atto.Parser Int
fixedDigits width = foldl' addDigit 0 <$> replicateM width (Atto.satisfy isDigit)
  where
    addDigit n digit = n * 10 + digitToInt digit

fractionalSeconds :: Atto.Parser Pico
fractionalSeconds = do
  digits <- Text.take 12 <$> Atto.takeWhile1 isDigit
  let numerator = Text.foldl' (\n digit -> n * 10 + fromIntegral (digitToInt digit)) (0 :: Integer) digits
  pure (fromRational (toRational numerator / 10 ^ Text.length digits))