{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Yesod.Core.Class.Dispatch where

import Data.ByteString.Builder (toLazyByteString, byteString)
import Data.Proxy (Proxy(..))
import Data.Text (Text)
import Network.HTTP.Types (status301, status307)
import Yesod.Core.Class.Dispatch.ToParentRoute
import Yesod.Core.Class.Yesod
import Yesod.Core.Content (ToTypedContent (..))
import Yesod.Core.Handler (sendWaiApplication, RedirectUrl, notFound)
import Yesod.Core.Internal.Run
import Yesod.Core.Types
import Yesod.Routes.Class
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as BL
import qualified Network.Wai as W

-- | This class is automatically instantiated when you use the template haskell
-- mkYesod function. You should never need to deal with it directly.
class Yesod site => YesodDispatch site where
    yesodDispatch :: YesodRunnerEnv site -> W.Application

-- | This class enables you to dispatch on a route fragment without needing
-- to know how to dispatch on the entire route structure. This allows you
-- to break up route generation into multiple files.
--
-- For details on use, see 'setFocusOnNestedRoute'.
--
-- @since 1.7.0.0
class RenderRouteNested a => YesodDispatchNested a where
    -- | Dispatches a request to a nested route fragment.
    --
    -- The implementation uses the full WAI 'Request' to determine if the
    -- remaining path (after the parent route) matches any child routes.
    -- Returns 'Nothing' if no child routes match (for fallthrough to other
    -- routes), or 'Just' a continuation that handles the request.
    --
    -- The parent depth (number of path pieces consumed by the parent route)
    -- is statically known during Template Haskell generation and baked into
    -- the generated instance.
    --
    -- @since 1.7.0.0
    yesodDispatchNested
        :: (Yesod (ParentSite a))
        => Proxy a
        -- ^ Type proxy to resolve ambiguity from non-injective type families
        -> ParentArgs a
        -- ^ The dynamic arguments from the parent route
        -> (a -> Route (ParentSite a))
        -- ^ Function to wrap the nested route in the parent constructor
        -> YesodRunnerEnv (ParentSite a)
        -- ^ The runner environment
        -> W.Request
        -- ^ The full WAI request
        -> Maybe ((W.Response -> IO W.ResponseReceived) -> IO W.ResponseReceived)
        -- ^ Returns 'Nothing' for fallthrough, or 'Just' a continuation
        -- that completes the 'Application' type when given a respond callback

-- | 'YesodDispatchNested' is a more flexible class than 'YesodDispatch',
-- and this instance is the proof. Given a @'Route' site@ we can dispatch
-- on it as normal, so this code path works. This allows us to create
-- generalized helpers and reuse them, ensuring that nested and top-level
-- dispatch remain equivalent. This instance therefore always returns
-- @'Just'@ — committing to 'yesodDispatch', which itself terminates in
-- a 404 on a miss — rather than the 'Nothing' that the class haddock
-- describes for /fragment/ instances. The only intended caller is the
-- terminal authority 'toWaiAppYreNested', where that 404 is exactly the
-- right answer; do not rely on this instance to signal fallthrough.
instance YesodDispatch site => YesodDispatchNested (Route site) where
    yesodDispatchNested :: Yesod (ParentSite (Route site)) =>
Proxy (Route site)
-> ParentArgs (Route site)
-> (Route site -> Route (ParentSite (Route site)))
-> YesodRunnerEnv (ParentSite (Route site))
-> Request
-> Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
yesodDispatchNested Proxy (Route site)
_ ParentArgs (Route site)
_ Route site -> Route (ParentSite (Route site))
_ YesodRunnerEnv (ParentSite (Route site))
yre Request
req = ((Response -> IO ResponseReceived) -> IO ResponseReceived)
-> Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
forall a. a -> Maybe a
Just (((Response -> IO ResponseReceived) -> IO ResponseReceived)
 -> Maybe
      ((Response -> IO ResponseReceived) -> IO ResponseReceived))
-> ((Response -> IO ResponseReceived) -> IO ResponseReceived)
-> Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
forall a b. (a -> b) -> a -> b
$ YesodRunnerEnv site -> Application
forall site.
YesodDispatch site =>
YesodRunnerEnv site -> Application
yesodDispatch YesodRunnerEnv site
YesodRunnerEnv (ParentSite (Route site))
yre Request
req

-- | Build a WAI 'W.Application' for @site@, indexed by a @url@ type that can
-- be rendered to a route of @site@ (via 'RedirectUrl').
--
-- Note that dispatch is purely path-based: the hand-written instances below
-- discard the @url@ value (@urlToDispatch _ = yesodDispatch@) and route on the
-- request's @pathInfo@. The @url@ argument exists only to select the instance
-- and to carry the 'RedirectUrl' constraint — it is not consulted at runtime.
--
-- This is equivalent to 'YesodDispatch' but allows us to vary on the
-- @url@ type, which lets us demand additional constraints in test
-- contexts.
--
-- @since 1.7.0.0
class RedirectUrl site url => UrlToDispatch url site where
    -- | @since 1.7.0.0
    urlToDispatch :: url -> YesodRunnerEnv site -> W.Application

instance YesodDispatch site => UrlToDispatch (Route site) site where
    urlToDispatch :: Route site -> YesodRunnerEnv site -> Application
urlToDispatch Route site
_ = YesodRunnerEnv site -> Application
forall site.
YesodDispatch site =>
YesodRunnerEnv site -> Application
yesodDispatch

instance (YesodDispatch site, RedirectUrl site (Route site, a)) => UrlToDispatch (Route site, a) site where
    urlToDispatch :: (Route site, a) -> YesodRunnerEnv site -> Application
urlToDispatch (Route site, a)
_ = YesodRunnerEnv site -> Application
forall site.
YesodDispatch site =>
YesodRunnerEnv site -> Application
yesodDispatch

instance YesodDispatch site => UrlToDispatch Text site where
    urlToDispatch :: Text -> YesodRunnerEnv site -> Application
urlToDispatch Text
_ = YesodRunnerEnv site -> Application
forall site.
YesodDispatch site =>
YesodRunnerEnv site -> Application
yesodDispatch

instance YesodDispatch site => UrlToDispatch String site where
    urlToDispatch :: String -> YesodRunnerEnv site -> Application
urlToDispatch String
_ = YesodRunnerEnv site -> Application
forall site.
YesodDispatch site =>
YesodRunnerEnv site -> Application
yesodDispatch

-- | This instance is the pattern upon which 'UrlToDispatch' instances are
-- generated for subsite fragments. Given the constraints, we are able to
-- call 'toWaiAppYreNested' at the @route@ type with the correct arguments.
-- This allows us to create an application for a fragment of a site.
--
-- @since 1.7.0.0
instance
    ( ParentSite route ~ site
    , YesodDispatchNested route
    , RedirectUrl site (WithParentArgs route)
    , Yesod site
    , ToParentRoute route
    )
  =>
    UrlToDispatch (WithParentArgs route) site
  where
    urlToDispatch :: WithParentArgs route -> YesodRunnerEnv site -> Application
urlToDispatch (WithParentArgs ParentArgs route
args route
_) =
        Proxy route
-> ParentArgs route
-> YesodRunnerEnv (ParentSite route)
-> Application
forall a.
(Yesod (ParentSite a), YesodDispatchNested a, ToParentRoute a) =>
Proxy a
-> ParentArgs a -> YesodRunnerEnv (ParentSite a) -> Application
toWaiAppYreNested (Proxy route
forall {k} (t :: k). Proxy t
Proxy :: Proxy route) ParentArgs route
args

class YesodSubDispatch sub master where
    yesodSubDispatch :: YesodSubRunnerEnv sub master -> W.Application

-- | Like 'YesodDispatchNested', but for subsites. This class enables
-- class-based delegation for nested routes within subsites, allowing
-- module separation and symmetry with 'YesodDispatchNested'.
--
-- When a 'YesodSubDispatchNested' instance exists for a nested route type,
-- 'mkYesodSubDispatch' will delegate to it instead of inlining the dispatch.
-- Use 'mkYesodSubDispatchInstance' to generate both 'YesodSubDispatch' and
-- 'YesodSubDispatchNested' instances in one splice.
--
-- @since 1.7.0.0
class RenderRouteNested a => YesodSubDispatchNested a where
    -- | Dispatches a request for a nested route fragment within a subsite.
    --
    -- Similar to 'yesodDispatchNested', but works with 'YesodSubRunnerEnv'
    -- instead of 'YesodRunnerEnv', making it suitable for subsites.
    -- The @master@ type is universally quantified since it's not determined
    -- by the nested route type.
    --
    -- @since 1.7.0.0
    yesodSubDispatchNested
        :: Proxy a
        -- ^ Type proxy to resolve ambiguity from non-injective type families
        -> ParentArgs a
        -- ^ The dynamic arguments from the parent route
        -> (a -> Route (ParentSite a))
        -- ^ Function to wrap the nested route in the parent constructor
        -> YesodSubRunnerEnv (ParentSite a) master
        -- ^ The subsite runner environment
        -> W.Request
        -- ^ The full WAI request
        -> Maybe ((W.Response -> IO W.ResponseReceived) -> IO W.ResponseReceived)
        -- ^ Returns 'Nothing' for fallthrough, or 'Just' a continuation

instance YesodSubDispatch WaiSubsite master where
    yesodSubDispatch :: YesodSubRunnerEnv WaiSubsite master -> Application
yesodSubDispatch YesodSubRunnerEnv {YesodRunnerEnv master
master -> WaiSubsite
Route WaiSubsite -> Route master
ParentRunner master
ysreParentRunner :: ParentRunner master
ysreGetSub :: master -> WaiSubsite
ysreToParentRoute :: Route WaiSubsite -> Route master
ysreParentEnv :: YesodRunnerEnv master
ysreParentEnv :: forall sub parent.
YesodSubRunnerEnv sub parent -> YesodRunnerEnv parent
ysreToParentRoute :: forall sub parent.
YesodSubRunnerEnv sub parent -> Route sub -> Route parent
ysreGetSub :: forall sub parent. YesodSubRunnerEnv sub parent -> parent -> sub
ysreParentRunner :: forall sub parent.
YesodSubRunnerEnv sub parent -> ParentRunner parent
..} = Application
app
      where
        WaiSubsite Application
app = master -> WaiSubsite
ysreGetSub (master -> WaiSubsite) -> master -> WaiSubsite
forall a b. (a -> b) -> a -> b
$ YesodRunnerEnv master -> master
forall site. YesodRunnerEnv site -> site
yreSite YesodRunnerEnv master
ysreParentEnv

instance YesodSubDispatch WaiSubsiteWithAuth master where
  yesodSubDispatch :: YesodSubRunnerEnv WaiSubsiteWithAuth master -> Application
yesodSubDispatch YesodSubRunnerEnv {YesodRunnerEnv master
master -> WaiSubsiteWithAuth
Route WaiSubsiteWithAuth -> Route master
ParentRunner master
ysreParentEnv :: forall sub parent.
YesodSubRunnerEnv sub parent -> YesodRunnerEnv parent
ysreToParentRoute :: forall sub parent.
YesodSubRunnerEnv sub parent -> Route sub -> Route parent
ysreGetSub :: forall sub parent. YesodSubRunnerEnv sub parent -> parent -> sub
ysreParentRunner :: forall sub parent.
YesodSubRunnerEnv sub parent -> ParentRunner parent
ysreParentRunner :: ParentRunner master
ysreGetSub :: master -> WaiSubsiteWithAuth
ysreToParentRoute :: Route WaiSubsiteWithAuth -> Route master
ysreParentEnv :: YesodRunnerEnv master
..} Request
req =
      ParentRunner master
ysreParentRunner HandlerFor master TypedContent
handlert YesodRunnerEnv master
ysreParentEnv ((Route WaiSubsiteWithAuth -> Route master)
-> Maybe (Route WaiSubsiteWithAuth) -> Maybe (Route master)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Route WaiSubsiteWithAuth -> Route master
ysreToParentRoute Maybe (Route WaiSubsiteWithAuth)
route) Request
req
    where
      route :: Maybe (Route WaiSubsiteWithAuth)
route = Route WaiSubsiteWithAuth -> Maybe (Route WaiSubsiteWithAuth)
forall a. a -> Maybe a
Just (Route WaiSubsiteWithAuth -> Maybe (Route WaiSubsiteWithAuth))
-> Route WaiSubsiteWithAuth -> Maybe (Route WaiSubsiteWithAuth)
forall a b. (a -> b) -> a -> b
$ [Text] -> [(Text, Text)] -> Route WaiSubsiteWithAuth
WaiSubsiteWithAuthRoute (Request -> [Text]
W.pathInfo Request
req) []
      WaiSubsiteWithAuth Application
set = master -> WaiSubsiteWithAuth
ysreGetSub (master -> WaiSubsiteWithAuth) -> master -> WaiSubsiteWithAuth
forall a b. (a -> b) -> a -> b
$ YesodRunnerEnv master -> master
forall site. YesodRunnerEnv site -> site
yreSite (YesodRunnerEnv master -> master)
-> YesodRunnerEnv master -> master
forall a b. (a -> b) -> a -> b
$ YesodRunnerEnv master
ysreParentEnv
      handlert :: HandlerFor master TypedContent
handlert = Application -> HandlerFor master TypedContent
forall (m :: * -> *) b. MonadHandler m => Application -> m b
sendWaiApplication Application
set

subHelper
  :: ToTypedContent content
  => SubHandlerFor child master content
  -> YesodSubRunnerEnv child master
  -> Maybe (Route child)
  -> W.Application
subHelper :: forall content child master.
ToTypedContent content =>
SubHandlerFor child master content
-> YesodSubRunnerEnv child master
-> Maybe (Route child)
-> Application
subHelper (SubHandlerFor HandlerData child master -> IO content
f) YesodSubRunnerEnv {YesodRunnerEnv master
master -> child
Route child -> Route master
ParentRunner master
ysreParentEnv :: forall sub parent.
YesodSubRunnerEnv sub parent -> YesodRunnerEnv parent
ysreToParentRoute :: forall sub parent.
YesodSubRunnerEnv sub parent -> Route sub -> Route parent
ysreGetSub :: forall sub parent. YesodSubRunnerEnv sub parent -> parent -> sub
ysreParentRunner :: forall sub parent.
YesodSubRunnerEnv sub parent -> ParentRunner parent
ysreParentRunner :: ParentRunner master
ysreGetSub :: master -> child
ysreToParentRoute :: Route child -> Route master
ysreParentEnv :: YesodRunnerEnv master
..} Maybe (Route child)
mroute =
    ParentRunner master
ysreParentRunner HandlerFor master TypedContent
handler YesodRunnerEnv master
ysreParentEnv ((Route child -> Route master)
-> Maybe (Route child) -> Maybe (Route master)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Route child -> Route master
ysreToParentRoute Maybe (Route child)
mroute)
  where
    handler :: HandlerFor master TypedContent
handler = (content -> TypedContent)
-> HandlerFor master content -> HandlerFor master TypedContent
forall a b. (a -> b) -> HandlerFor master a -> HandlerFor master b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap content -> TypedContent
forall a. ToTypedContent a => a -> TypedContent
toTypedContent (HandlerFor master content -> HandlerFor master TypedContent)
-> HandlerFor master content -> HandlerFor master TypedContent
forall a b. (a -> b) -> a -> b
$ (HandlerData master master -> IO content)
-> HandlerFor master content
forall site a. (HandlerData site site -> IO a) -> HandlerFor site a
HandlerFor ((HandlerData master master -> IO content)
 -> HandlerFor master content)
-> (HandlerData master master -> IO content)
-> HandlerFor master content
forall a b. (a -> b) -> a -> b
$ \HandlerData master master
hd ->
      let rhe :: RunHandlerEnv master master
rhe = HandlerData master master -> RunHandlerEnv master master
forall child site.
HandlerData child site -> RunHandlerEnv child site
handlerEnv HandlerData master master
hd
          rhe' :: RunHandlerEnv child master
rhe' = RunHandlerEnv master master
rhe
            { rheRoute = mroute
            , rheChild = ysreGetSub $ yreSite ysreParentEnv
            , rheRouteToMaster = ysreToParentRoute
            }
       in HandlerData child master -> IO content
f HandlerData master master
hd { handlerEnv = rhe' }

-- | Build a WAI 'W.Application' that dispatches starting at a nested route
-- fragment @a@ (rather than the whole @'Route' site@), given a
-- 'YesodRunnerEnv' for the parent site and the parent route's 'ParentArgs'.
-- Handles @cleanPath@ redirects and a terminal 404 just like 'toWaiAppYre'.
--
-- @since 1.7.0.0
toWaiAppYreNested
    :: (Yesod (ParentSite a), YesodDispatchNested a, ToParentRoute a)
    => Proxy a
    -> ParentArgs a
    -> YesodRunnerEnv (ParentSite a)
    -> W.Application
toWaiAppYreNested :: forall a.
(Yesod (ParentSite a), YesodDispatchNested a, ToParentRoute a) =>
Proxy a
-> ParentArgs a -> YesodRunnerEnv (ParentSite a) -> Application
toWaiAppYreNested Proxy a
proxy ParentArgs a
parentArgs YesodRunnerEnv (ParentSite a)
yre Request
req =
    case ParentSite a -> [Text] -> Either [Text] [Text]
forall site. Yesod site => site -> [Text] -> Either [Text] [Text]
cleanPath ParentSite a
site ([Text] -> Either [Text] [Text]) -> [Text] -> Either [Text] [Text]
forall a b. (a -> b) -> a -> b
$ Request -> [Text]
W.pathInfo Request
req of
        Left [Text]
pieces -> ParentSite a -> [Text] -> Application
forall master. Yesod master => master -> [Text] -> Application
sendRedirect ParentSite a
site [Text]
pieces Request
req
        Right [Text]
pieces -> do
            let mapplication :: Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
mapplication =
                    Proxy a
-> ParentArgs a
-> (a -> Route (ParentSite a))
-> YesodRunnerEnv (ParentSite a)
-> Request
-> Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
forall a.
(YesodDispatchNested a, Yesod (ParentSite a)) =>
Proxy a
-> ParentArgs a
-> (a -> Route (ParentSite a))
-> YesodRunnerEnv (ParentSite a)
-> Request
-> Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
yesodDispatchNested Proxy a
proxy ParentArgs a
parentArgs (ParentArgs a -> a -> Route (ParentSite a)
forall a.
ToParentRoute a =>
ParentArgs a -> a -> Route (ParentSite a)
toParentRoute ParentArgs a
parentArgs) YesodRunnerEnv (ParentSite a)
yre Request
req
                        { W.pathInfo = pieces
                        }
            case Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
mapplication of
                Maybe ((Response -> IO ResponseReceived) -> IO ResponseReceived)
Nothing ->
                    HandlerFor (ParentSite a) ()
-> YesodRunnerEnv (ParentSite a)
-> Maybe (Route (ParentSite a))
-> Application
forall res site.
(ToTypedContent res, Yesod site) =>
HandlerFor site res
-> YesodRunnerEnv site -> Maybe (Route site) -> Application
yesodRunner (HandlerFor site ()
forall {site}. HandlerFor site ()
forall (m :: * -> *) a. MonadHandler m => m a
notFound :: HandlerFor site ()) YesodRunnerEnv (ParentSite a)
yre Maybe (Route (ParentSite a))
forall a. Maybe a
Nothing Request
req
                Just (Response -> IO ResponseReceived) -> IO ResponseReceived
k ->
                    (Response -> IO ResponseReceived) -> IO ResponseReceived
k
  where
    site :: ParentSite a
site = YesodRunnerEnv (ParentSite a) -> ParentSite a
forall site. YesodRunnerEnv site -> site
yreSite YesodRunnerEnv (ParentSite a)
yre
    sendRedirect :: Yesod master => master -> [Text] -> W.Application
    sendRedirect :: forall master. Yesod master => master -> [Text] -> Application
sendRedirect master
y [Text]
segments' Request
env Response -> IO ResponseReceived
sendResponse =
         Response -> IO ResponseReceived
sendResponse (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> ByteString -> Response
W.responseLBS Status
status
                [ (CI ByteString
"Content-Type", ByteString
"text/plain")
                , (CI ByteString
"Location", ByteString -> ByteString
BL.toStrict (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Builder -> ByteString
toLazyByteString Builder
dest')
                ] ByteString
"Redirecting"
      where
        -- Ensure that non-GET requests get redirected correctly. See:
        -- https://github.com/yesodweb/yesod/issues/951
        status :: Status
status
            | Request -> ByteString
W.requestMethod Request
env ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"GET" = Status
status301
            | Bool
otherwise                    = Status
status307

        dest :: Builder
dest = master -> Text -> [Text] -> [(Text, Text)] -> Builder
forall site.
Yesod site =>
site -> Text -> [Text] -> [(Text, Text)] -> Builder
joinPath master
y (master -> Request -> Text
forall master. Yesod master => master -> Request -> Text
resolveApproot master
y Request
env) [Text]
segments' []
        dest' :: Builder
dest' =
            if ByteString -> Bool
S.null (Request -> ByteString
W.rawQueryString Request
env)
                then Builder
dest
                else Builder
dest Builder -> Builder -> Builder
forall a. Monoid a => a -> a -> a
`mappend`
                     ByteString -> Builder
byteString (Request -> ByteString
W.rawQueryString Request
env)