module Yesod.EventSource
( repEventSource
, pollingEventSource
, ioToRepEventSource
, EventSourcePolyfill(..)
) where
import Blaze.ByteString.Builder (Builder)
import Control.Monad (when)
import Data.Functor ((<$>))
import Data.Monoid (Monoid (..))
import Yesod.Core
import Data.Conduit
import qualified Network.Wai as W
import qualified Network.Wai.EventSource as ES
import qualified Network.Wai.EventSource.EventStream as ES
prepareForEventSource :: MonadHandler m => m EventSourcePolyfill
prepareForEventSource = do
reqWith <- lookup "X-Requested-With" . W.requestHeaders Data.Functor.<$> waiRequest
let polyfill | reqWith == Just "XMLHttpRequest" = Remy'sESPolyfill
| otherwise = NoESPolyfill
addHeader "Cache-Control" "no-cache"
return polyfill
respondEventStream :: ConduitT () (Flush Builder) (HandlerFor site) ()
-> HandlerFor site TypedContent
respondEventStream = respondSource "text/event-stream"
repEventSource :: (EventSourcePolyfill -> ConduitT () ES.ServerEvent (HandlerFor site) ())
-> HandlerFor site TypedContent
repEventSource src =
prepareForEventSource >>=
respondEventStream . sourceToSource . src
sourceToSource
:: Monad m
=> ConduitT () ES.ServerEvent m ()
-> ConduitT () (Flush Builder) m ()
sourceToSource src =
src .| awaitForever eventToFlushBuilder
where
eventToFlushBuilder event =
case ES.eventToBuilder event of
Nothing -> return ()
Just x -> yield (Chunk x) >> yield Flush
pollingEventSource :: s
-> (EventSourcePolyfill -> s -> HandlerFor site ([ES.ServerEvent], s))
-> HandlerFor site TypedContent
pollingEventSource initial act = do
polyfill <- prepareForEventSource
let
getEvents s = do
(evs, s') <- lift (act polyfill s)
case evs of
[] -> getEvents s'
_ -> do
let (builder, continue) = joinEvents evs mempty
yield (Chunk builder)
yield Flush
when continue (getEvents s')
joinEvents (ev:evs) acc =
case ES.eventToBuilder ev of
Just b -> joinEvents evs (acc `Data.Monoid.mappend` b)
Nothing -> (fst $ joinEvents [] acc, False)
joinEvents [] acc = (acc, True)
respondEventStream (getEvents initial)
ioToRepEventSource :: s
-> (EventSourcePolyfill -> s -> IO ([ES.ServerEvent], s))
-> HandlerFor site TypedContent
ioToRepEventSource initial act = pollingEventSource initial act'
where act' p s = liftIO (act p s)
data EventSourcePolyfill =
NoESPolyfill
| Remy'sESPolyfill
deriving (Eq, Ord, Show, Enum)