| 1 |
{-# LANGUAGE OverloadedStrings #-} |
| 2 |
{-# LANGUAGE RecordWildCards #-} |
| 3 |
|
| 4 |
-- | Middleware for server push learning dependency based on Referer:. |
| 5 |
module Network.Wai.Middleware.Push.Referer ( |
| 6 |
-- * Middleware |
| 7 |
pushOnReferer |
| 8 |
-- * Making push promise |
| 9 |
, URLPath |
| 10 |
, MakePushPromise |
| 11 |
, defaultMakePushPromise |
| 12 |
-- * Settings |
| 13 |
, Settings |
| 14 |
, M.defaultSettings |
| 15 |
, makePushPromise |
| 16 |
, duration |
| 17 |
, keyLimit |
| 18 |
, valueLimit |
| 19 |
) where |
| 20 |
|
| 21 |
import Control.Monad (when) |
| 22 |
import qualified Data.ByteString as BS |
| 23 |
import Data.Maybe (isNothing) |
| 24 |
import Network.HTTP.Types (Status(..)) |
| 25 |
import Network.Wai |
| 26 |
import Network.Wai.Handler.Warp hiding (Settings, defaultSettings) |
| 27 |
import Network.Wai.Internal (Response(..)) |
| 28 |
|
| 29 |
import qualified Network.Wai.Middleware.Push.Referer.Manager as M |
| 30 |
import Network.Wai.Middleware.Push.Referer.ParseURL |
| 31 |
import Network.Wai.Middleware.Push.Referer.Types |
| 32 |
|
| 33 |
-- $setup |
| 34 |
-- >>> :set -XOverloadedStrings |
| 35 |
|
| 36 |
-- | The middleware to push files based on Referer:. |
| 37 |
-- Learning strategy is implemented in the first argument. |
| 38 |
pushOnReferer :: Settings -> Middleware |
| 39 |
pushOnReferer settings app req sendResponse = do |
| 40 |
mgr <- M.getManager settings |
| 41 |
app req $ push mgr |
| 42 |
where |
| 43 |
path = rawPathInfo req |
| 44 |
push mgr res@(ResponseFile (Status 200 "OK") _ file Nothing) |
| 45 |
-- file: /index.html |
| 46 |
-- path: / |
| 47 |
-- referer: |
| 48 |
-- refPath: |
| 49 |
| isHTML path = do |
| 50 |
xs <- M.lookup path mgr |
| 51 |
case xs of |
| 52 |
[] -> return () |
| 53 |
ps -> do |
| 54 |
let h2d = defaultHTTP2Data { http2dataPushPromise = ps } |
| 55 |
setHTTP2Data req $ Just h2d |
| 56 |
sendResponse res |
| 57 |
-- file: /style.css |
| 58 |
-- path: /style.css |
| 59 |
-- referer: /index.html |
| 60 |
-- refPath: / |
| 61 |
| otherwise = case requestHeaderReferer req of |
| 62 |
Nothing -> sendResponse res |
| 63 |
Just referer -> do |
| 64 |
(mauth,refPath) <- parseUrl referer |
| 65 |
when ((isNothing mauth || requestHeaderHost req == mauth) |
| 66 |
&& path /= refPath |
| 67 |
&& isHTML refPath) $ do |
| 68 |
let path' = BS.copy path |
| 69 |
refPath' = BS.copy refPath |
| 70 |
mpp <- makePushPromise settings refPath' path' file |
| 71 |
case mpp of |
| 72 |
Nothing -> return () |
| 73 |
Just pp -> M.insert refPath' pp mgr |
| 74 |
sendResponse res |
| 75 |
push _ res = sendResponse res |
| 76 |
|
| 77 |
isHTML :: URLPath -> Bool |
| 78 |
isHTML p = ("/" `BS.isSuffixOf` p) |
| 79 |
|| (".html" `BS.isSuffixOf` p) |
| 80 |
|| (".htm" `BS.isSuffixOf` p) |