summaryrefslogtreecommitdiff
path: root/lib/Postdelay/TimeSpec.hs
blob: 676dabf7240a43fad33c2f523edf0beb25fd144d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, ViewPatterns, ConstraintKinds, TupleSections, RecordWildCards #-}

module Postdelay.TimeSpec
  ( pTimeSpec
  , pTimeZone
  , TimeCtx(..)
  ) where

import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Reader.Class
import Control.Monad.Error.Class

import Text.Parsec.Char hiding (digit)
import qualified Text.Parsec.Char as Parsec (digit)
import Text.Parsec.Prim
import Text.Parsec.Combinator
import Text.Parsec.Error (ParseError(..))
import Text.Read (readMaybe)

import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI

import Data.Time
import Data.Time.Calendar.WeekDate
import Data.Time.Zones
import Data.Function
import Data.Maybe
import Data.Foldable
import Data.Ord
import Data.List
import Data.Tuple
import Data.Bool

import Control.Exception (IOException)

import Debug.Trace


type MonadTP m = (MonadIO m, MonadReader TimeCtx m)

data TimeCtx = TimeCtx
               { baseTime :: UTCTime
               , tz :: Either TimeZone TZ
               }


spaced :: Stream s m Char => ParsecT s u m a -> ParsecT s u m a
spaced p = spaces *> p <* spaces

string' :: Stream s m Char => String -> ParsecT s u m String
string' = mapM $ satisfy . ((==) `on` CI.mk)

choice' :: (Stream s m t, Foldable f) => f (ParsecT s u m a) -> ParsecT s u m a
choice' (toList -> f)
  | [p]    <- f = p
  | (p:ps) <- f = try p <|> choice' ps
  | otherwise   = mzero

strChoice' :: Stream s m Char => [String] -> ParsecT s u m String
strChoice' = choice' . map string' . sortBy (comparing $ Down . length)

natural :: (Stream s m Char, Num a) => ParsecT s u m a
natural = foldl' (\init last -> init * 10 + last) 0 <$> many1 digit

decimal :: (Stream s m Char, Num a, Fractional a) => ParsecT s u m a
decimal = do
  w <- foldl' (\init last -> init * 10 + last) 0 <$> many1 digit
  f <- option 0 $ do
    char '.'
    foldr' (\head tail -> head + tail / 10) 0 <$> many1 digit
  return $ w + f / 10
  
digit :: (Stream s m Char, Num a) => ParsecT s u m a
digit = fromIntegral . (\c -> fromEnum c - fromEnum '0') <$> Parsec.digit

ensure :: MonadPlus m => (a -> Bool) -> a -> m a
ensure p x = bool (const mzero) return (p x) $ x


pTimeSpec :: MonadTP m => ParsecT String () m UTCTime
pTimeSpec = choice' [ flip addUTCTime <$> spaced pSpecBase <*> spaced pSpecOffset <?> "Absolute time + offset"
                    , flip addUTCTime <$> asks baseTime <*> spaced pSpecOffset <?> "Time offset"
                    , spaced pSpecBase <?> "Absolute time"
                    ]
            <* eof <?> "Time specification"

pSpecBase :: forall m. MonadTP m => ParsecT String () m UTCTime
pSpecBase = choice'
  [ utcTime <$> spaced pDate <*> spaced pTime
  , flip utcTime <$> spaced pTime <*> spaced pDate
  , do
      proto@(UTCTime{..}) <- utcTime <$> (utctDay <$> asks baseTime) <*> spaced pTime
      now <- asks baseTime
      return $ if proto < now
               then UTCTime (succ utctDay) utctDayTime
               else proto
  , utcTime <$> spaced pDate <*> ((dayFractionToTimeOfDay 0, ) <$> asks tz) 
  , spaced (string' "now") *> asks baseTime
  ] <?> "Base specification"
  where
    utcTime :: Day -> (TimeOfDay, Either TimeZone TZ) -> UTCTime
    utcTime d (t, Right tz) = localTimeToUTCTZ tz (LocalTime d t)
    utcTime d (t, Left  tz) = localTimeToUTC   tz (LocalTime d t)

pSpecOffset :: MonadTP m => ParsecT String () m NominalDiffTime
pSpecOffset = (+) <$> pSpecOffset' <*> option 0 (try (many $ space <|> char ',' <|> char ';') >> pSpecOffset)
  where
    pSpecOffset' = option id (spaced pSign) <*> ((*) <$> spaced pNumber <*> spaced pSpecOffsetConst) <?> "Time offset"
    pNumber = fromInteger <$> natural <?> "Offset multiplier"

pSign :: MonadTP m => ParsecT String () m (NominalDiffTime -> NominalDiffTime)
pSign = choice [ id     <$ char '+'
               , negate <$ char '-'
               ] <?> "Offset sign"

pSpecOffsetConst :: MonadTP m => ParsecT String () m NominalDiffTime
pSpecOffsetConst = choice' [ 1e-12           <$ strChoice' [ "ps"
                                                           , "picosecond"
                                                           , "picoseconds"
                                                           ]
                           , 1e-9            <$ strChoice' [ "ns"
                                                           , "nanosecond"
                                                           , "nanoseconds"
                                                           ]
                           , 1e-6            <$ strChoice' [ "us", "µs"
                                                           , "microsecond"
                                                           , "microseconds"
                                                           ]
                           , 1e-3            <$ strChoice' [ "ms"
                                                           , "millisecond"
                                                           , "milliseconds"
                                                           ]
                           , 1e-2            <$ strChoice' [ "ds"
                                                           , "decisecond"
                                                           , "deciseconds"
                                                           ]
                           , 1e-1            <$ strChoice' [ "cs"
                                                           , "centisecond"
                                                           , "centiseconds"
                                                           ]
                           , 1               <$ strChoice' [ "s"
                                                           , "second"
                                                           , "seconds"
                                                           ]
                           , 60              <$ strChoice' [ "min"
                                                           , "minute"
                                                           , "minutes"
                                                           ]
                           , 3600            <$ strChoice' [ "h"
                                                           , "hour"
                                                           , "hours"
                                                           ]
                           , 24 * 3600       <$ strChoice' [ "d"
                                                           , "day"
                                                           , "days"
                                                           ]
                           , 7 * 24 * 3600   <$ strChoice' [ "week"
                                                           , "weeks"
                                                           ]
                           , 30 * 24 * 3600  <$ strChoice' [ "month"
                                                           , "months"
                                                           ]
                           , 365 * 24 * 3600 <$ strChoice' [ "year"
                                                           , "years"
                                                           ]
                           ] <?> "Offset unit"

pDate :: MonadTP m => ParsecT String () m Day
pDate = choice' [ do
                    (m, d) <- choice' [ do
                                          m <- spaced pMonthName
                                          d <- spaced natural
                                          optional . spaced $ char ','
                                          return (m, d)
                                      , fmap swap . (,) <$> spaced natural <*> spaced pMonthName
                                      ]
                    y <- spaced natural
                    fromGregorian' y m d
                , do
                    now <- asks baseTime
                    (m, d) <- choice' [ (,) <$> spaced pMonthName <*> spaced natural
                                      , fmap swap . (,) <$> spaced natural <*> spaced pMonthName
                                      ]
                    let
                      (y, _, _) = toGregorian $ utctDay now
                    proto <- fromGregorian' y m d
                    if proto < utctDay now
                      then fromGregorian' (y + 1) m d
                      else return proto
                , do
                    now <- asks baseTime
                    optional $ spaces *> pNext <* many1 space
                    d <- spaced pWeekdayName
                    let
                      (y, w, _) = toWeekDate $ utctDay now
                    proto <- fromWeekDate' y w d
                    if proto < utctDay now
                      then maybe (fromWeekDate' (y + 1) 1 d) return $ fromWeekDateValid y (w + 1) d
                      else return proto
                , do
                    spaced $ string' "today"
                    utctDay <$> asks baseTime
                , do
                    spaced $ string' "tomorrow"
                    succ . utctDay <$> asks baseTime
                , do
                    y <- natural
                    char '-'
                    m <- natural
                    char '-'
                    d <- natural
                    fromGregorian' y m d
                , do
                    d <- natural
                    char '.'
                    m <- natural
                    char '.'
                    y <- natural
                    fromGregorian' y m d
                , do
                    m <- natural
                    char '/'
                    d <- natural
                    char '/'
                    y <- natural
                    fromGregorian' y m d
                , do
                    ds <- many1 digit
                    when (length ds < 5) $ fail "Insufficient digits to interpret as concatenated date"
                    let
                      d2 : d1 : m2 : m1 : ys = reverse ds
                      d = 10 * d1 + d2
                      m = 10 * m1 + m2
                      y = foldl' (\init last -> init * 10 + last) 0 . map fromIntegral $ reverse ys
                    fromGregorian' y m d
                , do
                    pNext
                    many1 space
                    fmap utctDay . addUTCTime <$> pSpecOffsetConst <*> asks baseTime
               ] <?> "Day specification"
  where
    fromGregorian' y m d = maybe (fail "Invalid gregorian date") return $ fromGregorianValid y m d
    fromWeekDate' y w d = maybe (fail "Invalid iso8601 date") return $ fromWeekDateValid y w d
    pNext = string' "next"

pMonthName :: MonadTP m => ParsecT String () m Int
pMonthName = choice' (zipWith (<$) [1..] [ strChoice' [ "January", "Jan" ]
                                         , strChoice' [ "Febuary", "Feb" ]
                                         , strChoice' [ "March", "Mar" ]
                                         , strChoice' [ "April", "Apr" ]
                                         , strChoice' [ "May" ]
                                         , strChoice' [ "June", "Jun" ]
                                         , strChoice' [ "July", "Jul" ]
                                         , strChoice' [ "August", "Aug" ]
                                         , strChoice' [ "September", "Sep" ]
                                         , strChoice' [ "October", "Oct" ]
                                         , strChoice' [ "November", "Nov" ]
                                         , strChoice' [ "December", "Dec" ]
                                         ]) <?> "Month name"

pWeekdayName :: MonadTP m => ParsecT String () m Int
pWeekdayName = choice' (zipWith (<$) [1..] [ strChoice' [ "Monday", "Mon" ]
                                           , strChoice' [ "Tuesday", "Tue" ]
                                           , strChoice' [ "Wednesday", "Wed" ]
                                           , strChoice' [ "Thursday", "Thu" ]
                                           , strChoice' [ "Friday", "Fri" ]
                                           , strChoice' [ "Saturday", "Sat" ]
                                           , strChoice' [ "Sunday", "Sun" ]
                                           ])

pTime :: MonadTP m => ParsecT String () m (TimeOfDay, Either TimeZone TZ)
pTime = choice' [ (,) <$> spaced pTimeBase <*> spaced pTimeZone
                , (,) <$> spaced pTimeBase <*> asks tz
                ] <?> "Time of day and timezone specification"

data AMPM = AM | PM
  deriving (Eq, Ord, Enum)

pTimeBase :: MonadTP m => ParsecT String () m TimeOfDay
pTimeBase = choice' [ do
                        h <- pHour12
                        m <- option 0 $ char ':' >> pMinute
                        s <- option 0 $ char ':' >> pSecond
                        amPM <- spaced pAMPM
                        let h' = h + fromEnum amPM * 12
                        return $ TimeOfDay h' m s
                    , do
                        h <- pHour
                        m <- option 0 $ char ':' >> pMinute
                        s <- option 0 $ char ':' >> pSecond
                        return $ TimeOfDay h m s
                    , do
                        h <- ensure (<= 24) =<< (\d u -> 10 * d + u) <$> digit <*> digit
                        m <- option 0 $ ensure (< 60) =<< (\d u -> 10 * d + u) <$> digit <*> digit
                        s <- option 0 $ pSecond
                        return $ TimeOfDay h m s
                    , TimeOfDay 0 0 0 <$ string' "midnight"
                    , TimeOfDay 12 0 0 <$ string' "noon"
                    , TimeOfDay 16 0 0 <$ string' "teatime"
                    ] <?> "Time of day specification"
  where
    pAMPM = choice [ AM <$ string' "AM"
                   , PM <$ string' "PM"
                   ]
    pHour12 = (`rem` 12) <$> (ensure (<= 12) =<< natural)

    pHour = (`rem` 24) <$> (ensure (<= 24) =<< natural)
    pMinute = ensure (< 60) =<< natural
    pSecond = decimal

pTimeZone :: MonadIO m => ParsecT String () m (Either TimeZone TZ)
pTimeZone = choice' [ do
                        sgn <- choice [ id <$ char '+'
                                      , negate <$ char '-'
                                      ]
                        hs <- (\d u -> 10 * d + u) <$> digit <*> digit
                        ms <- option 0 $ (\d u -> 10 * d + u) <$> digit <*> digit
                        return . Left . minutesToTimeZone $ hs * 60 + ms
                    , do
                        let
                          ident = (++) <$> many1 alphaNum <*> option "" ((:) <$> oneOf "_-/.+" <*> ident)
                        n <- ident
                        tz <- liftIO $ do
                          let
                            fbHandler :: IO a -> (IOException -> IO a)
                            fbHandler fb _ = fb
                          foldl (\fb a -> a `catchError` fbHandler fb) (return Nothing)
                            [ Just <$> loadSystemTZ n
                            , Just <$> loadTZFromDB n
                            ]
                        case tz of
                          Nothing   -> fail $ "Could not resolve timezone: " ++ n
                          (Just tz) -> return $ Right tz
                    ]