Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 45169804e3
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 238 lines (177 sloc) 8.62 kb
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
{-# LANGUAGE OverloadedStrings #-}

module Blaaargh.Internal.Handlers ( serveBlaaargh ) where

import Control.Monad.State
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
import Data.ByteString.Char8 (ByteString)
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import Happstack.Server
import Happstack.Server.HTTP.FileServe
import Happstack.Server.Parts
import qualified Text.Atom.Feed as Atom
import Text.Printf
import Text.StringTemplate

------------------------------------------------------------------------------
import Blaaargh.Internal.Post
import Blaaargh.Internal.Templates
import Blaaargh.Internal.Types
import qualified Blaaargh.Internal.Util.ExcludeList as EL


------------------------------------------------------------------------------
{-|

The top-level happstack handler. The 'BlaaarghHandler' is a 'ServerPartT' over
a state monad; you \"run\" this handler by feeding it a BlaaarghState using
'runBlaaarghHandler'. It handles requests on its base url (defined in the
@{blaaargh_dir}/config@ file) and serves up content from the content area.

-}
serveBlaaargh :: BlaaarghHandler
serveBlaaargh = do
    methodOnly GET
    compressedResponseFilter

    cm <- lift get >>= return . blaaarghPostMap
    paths <- askRq >>= return . map B.pack . rqPaths

    serve [] paths cm `mappend` fourohfour

  where
    --------------------------------------------------------------------------
    serve :: [ByteString] -> [ByteString] -> ContentMap -> BlaaarghHandler
    serve soFar paths content = do
        case paths of
          [] -> serveIndex soFar content
          (a:[]) -> serveFile soFar a content
          (a:b) -> serveDir soFar a b content


    --------------------------------------------------------------------------
    serveFile :: [ByteString] -> ByteString -> ContentMap -> BlaaarghHandler
    serveFile soFar a content = do
        if a == "feed.xml" then
            serveFeed soFar content
          else
            maybe mzero
                  (\f -> case f of
                           (ContentStatic fp) -> serveStatic fp
                           (ContentPost post) -> servePost (soFar ++ [a]) post
                           (ContentDirectory _ d) -> serveIndex (soFar ++ [a]) d)
                  (Map.lookup a content)


    --------------------------------------------------------------------------
    serveDir :: [ByteString]
             -> ByteString
             -> [ByteString]
             -> ContentMap
             -> BlaaarghHandler
    serveDir soFar d rest content = do
        let mbD = Map.lookup d content

        maybe mzero
              (\f -> case f of
                       (ContentDirectory _ mp) -> serve (soFar ++ [d]) rest mp
                       _ -> mzero)
              mbD



------------------------------------------------------------------------------
fourohfour :: BlaaarghHandler
fourohfour = do
    state <- lift get
    mbTmpl <- findFourOhFourTemplate
    tmpl <- maybe mzero return mbTmpl

    let title = getTextContent . Atom.feedTitle . blaaarghFeedInfo $ state

    let tmpl' = setAttribute "pageTitle" title tmpl

    return $ toResponse $ HtmlResponse $ render tmpl'


------------------------------------------------------------------------------
serveStatic :: FilePath -> BlaaarghHandler
serveStatic = localRq (\r -> r { rqPaths=[]}) . fileServeStrict []


newtype HtmlResponse = HtmlResponse ByteString

instance ToMessage HtmlResponse where
    toContentType _ = "text/html"
    toMessage (HtmlResponse s) = L.fromChunks [s]


------------------------------------------------------------------------------
servePost :: [ByteString] -> Post -> BlaaarghHandler
servePost soFar post = do
    state <- lift get
    mbTmpl <- lift $ findTemplateForPost soFar
    tmpl <- maybe mzero return mbTmpl

    let title = concat
                  [ getTextContent . Atom.feedTitle . blaaarghFeedInfo $ state
                  , (let s = getTextContent . Atom.entryTitle . unPost $ post
                     in if null s then "" else ": " ++ s)
                  ]


    let tmpl' = setAttribute "post" post $
                 setAttribute "pageTitle" title tmpl

    return $ toResponse $ HtmlResponse $ render tmpl'


------------------------------------------------------------------------------
getTextContent :: Atom.TextContent -> String
getTextContent (Atom.TextString s) = s
getTextContent (Atom.HTMLString s) = s
getTextContent _ = undefined -- don't support that yet


------------------------------------------------------------------------------
getContentTitle :: ContentItem -> String
getContentTitle (ContentPost (Post p)) = getTextContent . Atom.entryTitle $ p
getContentTitle _ = ""


------------------------------------------------------------------------------
serveIndex :: [ByteString] -> ContentMap -> BlaaarghHandler
serveIndex soFar content = do
    state <- lift get
    mbTmpl <- lift $ findTemplateForDirectory soFar
    tmpl <- maybe mzero return mbTmpl

    let excludes' = blaaarghFeedExcludes state
    let excludes = foldl' (flip EL.descend) excludes' soFar

    let alpha = alphabeticalPosts excludes content
    let chron = chronologicalPosts excludes content
    let rchron = reverseChronologicalPosts excludes content
    let recent = take 5 rchron

    let postmap = [ ("alphabeticalPosts" , alpha)
                   , ("chronologicalPosts" , chron)
                   , ("reverseChronologicalPosts" , rchron)
                   , ("recentPosts" , recent) ]

    let tmpl' = setManyAttrib postmap tmpl

    let mbPost = Map.lookup "index" content

    let baseURL = B.pack $ blaaarghBaseURL state
    let fdPath = B.concat $ intersperse "/" $ soFar ++ ["feed.xml"]
    let feedURL = B.unpack $ B.concat [baseURL, "/", fdPath]


    let title = concat
                  [ getTextContent . Atom.feedTitle . blaaarghFeedInfo $ state
                  , maybe ""
                          (\x -> let s = getContentTitle x
                                 in if null s then "" else ": " ++ s)
                          mbPost
                  ]


    let tmpl'' = case mbPost of
                   (Just (ContentPost p)) -> setAttribute "post" p tmpl'
                   _ -> tmpl'

    let autoDiscovery' = printf "<link rel=\"alternate\" \
\type=\"application/atom+xml\" \
\href=\"%s\">"
                                 feedURL :: String

    let autoDiscovery = if EL.matchList soFar excludes
                          then ""
                          else autoDiscovery'

    let tmpl''' = setAttribute "pageTitle" title $
                  setAttribute "extraHead" autoDiscovery tmpl''

    return $ toResponse $ HtmlResponse $ render tmpl'''


------------------------------------------------------------------------------
addSiteURL :: String -> Post -> Post
addSiteURL siteURL (Post p) =
    Post $ p {Atom.entryId = concat [siteURL, Atom.entryId p]}


------------------------------------------------------------------------------
serveFeed :: [ByteString] -> ContentMap -> BlaaarghHandler
serveFeed soFar content = do
    state <- lift get

    let excludes' = blaaarghFeedExcludes state
    let excludes = foldl' (flip EL.descend) excludes' soFar

    let siteURL' = blaaarghSiteURL state
    let posts = map (addSiteURL siteURL') $ recentPosts excludes content 5
    hasTemplate <- lift $ liftM isJust $ findTemplateForDirectory soFar

    if null posts || not hasTemplate
      then mzero
      else do
        let siteURL = B.pack siteURL'
        let baseURL = B.pack $ blaaarghBaseURL state
        let fdPath = B.concat $ intersperse "/" $ soFar ++ ["feed.xml"]
        let feedURL = B.unpack $ B.concat
                                $ [siteURL, baseURL, "/", fdPath]
        let baseFeed = blaaarghFeedInfo state

        let feed = baseFeed {
                            Atom.feedId = feedURL
                          , Atom.feedLinks = [ Atom.nullLink feedURL ]
                          , Atom.feedEntries = map unPost posts
                          , Atom.feedUpdated = Atom.entryUpdated $ unPost (head posts)
                          }
        return $ toResponse feed
Something went wrong with that request. Please try again.