Command line frontend for video metadata tagging tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Date.hs 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-
  3. This file is part of the Haskell package themoviedb. It is subject to
  4. the license terms in the LICENSE file found in the top-level directory
  5. of this distribution and at git://pmade.com/themoviedb/LICENSE. No
  6. part of themoviedb package, including this file, may be copied,
  7. modified, propagated, or distributed except according to the terms
  8. contained in the LICENSE file.
  9. -}
  10. --------------------------------------------------------------------------------
  11. -- | Utility type for working with release dates.
  12. module Network.API.TheMovieDB.Internal.Date
  13. ( Date (..)
  14. , parseDay
  15. , (.::)
  16. ) where
  17. --------------------------------------------------------------------------------
  18. import Control.Applicative
  19. import Data.Aeson
  20. import Data.Aeson.Types (Parser, typeMismatch)
  21. import Data.Text (Text)
  22. import qualified Data.Text as T
  23. import Data.Time (Day(..), parseTimeM)
  24. import Data.Time.Locale.Compat (defaultTimeLocale)
  25. --------------------------------------------------------------------------------
  26. -- | A simple type wrapper around 'Day' in order to parse a movie's
  27. -- release date, which may be null or empty.
  28. newtype Date = Date {day :: Maybe Day} deriving (Eq, Show)
  29. --------------------------------------------------------------------------------
  30. -- | Aeson helper function to parse dates in TheMovieDB API.
  31. parseDay :: Object -> Text -> Parser (Maybe Day)
  32. parseDay v key =
  33. do m <- date
  34. return $ case m of
  35. Nothing -> Nothing
  36. Just d -> day d
  37. where
  38. date :: Parser (Maybe Date)
  39. date = v .:? key <|> pure Nothing
  40. --------------------------------------------------------------------------------
  41. (.::) :: Object -> Text -> Parser (Maybe Day)
  42. (.::) = parseDay
  43. --------------------------------------------------------------------------------
  44. -- | Parse release dates in JSON.
  45. instance FromJSON Date where
  46. parseJSON Null = return (Date Nothing)
  47. parseJSON (String t)
  48. | T.null t = return (Date Nothing)
  49. | otherwise = do d <- parseTimeM True defaultTimeLocale "%Y-%m-%d" (T.unpack t)
  50. return $ Date (Just d)
  51. parseJSON v = typeMismatch "Date" v