breve/src/Application.hs

70 lines
1.8 KiB
Haskell
Raw Normal View History

2015-05-10 15:40:56 +02:00
{-# LANGUAGE OverloadedStrings #-}
2015-04-08 12:47:56 +02:00
module Application where
2015-05-09 22:24:33 +02:00
import Breve.Generator
2015-04-08 22:13:02 +02:00
import Breve.UrlTable
2015-04-09 17:11:27 +02:00
import Paths_breve (getDataFileName)
2015-05-09 22:24:33 +02:00
import Views
2015-04-08 12:47:56 +02:00
2015-08-11 04:02:10 +02:00
import Data.Monoid
2015-04-09 17:11:27 +02:00
import Control.Monad.IO.Class (liftIO)
2015-05-09 23:04:14 +02:00
import Data.Aeson hiding (json)
2015-08-11 04:02:10 +02:00
import Data.Text (Text)
import qualified Data.Text.Format as F
2015-05-09 22:24:33 +02:00
import Web.Spock.Safe
2015-05-10 15:37:59 +02:00
import Network.HTTP.Types.Status
2015-05-10 03:29:59 +02:00
import Network.Wai (Middleware)
2015-05-09 22:24:33 +02:00
import Network.Wai.Middleware.Static
2015-05-10 03:29:59 +02:00
import Network.Wai.Middleware.RequestLogger
2015-05-09 22:24:33 +02:00
2015-05-10 03:29:59 +02:00
serveStatic :: FilePath -> Middleware
serveStatic = staticPolicy . addBase
2015-05-09 22:24:33 +02:00
2015-08-11 04:02:10 +02:00
reply :: Status -> Text -> ActionT IO ()
2015-05-10 15:37:59 +02:00
reply code text = setStatus code >> render (message text)
2015-05-09 22:24:33 +02:00
app :: Url -> UrlTable -> SpockT IO ()
app url' table = do
2015-05-10 03:29:59 +02:00
static <- liftIO (getDataFileName "static/")
middleware (serveStatic static)
middleware logStdout
2015-05-09 22:24:33 +02:00
2015-05-10 15:37:33 +02:00
get "/" $ render index
2015-05-09 22:24:33 +02:00
get var $ \name -> do
url <- liftIO (extract table name)
case url of
2015-05-10 15:37:59 +02:00
Nothing -> reply status404 "404: does not exist"
2015-05-09 22:24:33 +02:00
Just url -> do
2015-08-11 04:02:10 +02:00
F.print "Resolved {} -> {} " (name, url)
redirect url
2015-05-09 22:24:33 +02:00
2015-05-09 23:04:14 +02:00
post "/" $ do
2015-05-10 15:37:59 +02:00
url <- param "url"
2015-08-11 04:02:10 +02:00
case url of
2015-05-10 15:37:59 +02:00
Nothing -> reply status400 "400: bad request"
2015-05-09 22:24:33 +02:00
Just url -> do
name <- liftIO (insert table url)
2015-08-11 04:02:10 +02:00
F.print "Registered {} -> {} " (url, name)
2015-05-09 22:24:33 +02:00
let link = url' <> name
2015-05-10 15:37:33 +02:00
render (done link)
2015-05-09 22:24:33 +02:00
post "api" $ do
2015-05-10 15:37:59 +02:00
url <- param "url"
2015-08-11 04:02:10 +02:00
case url of
2015-05-10 15:37:59 +02:00
Nothing -> do
setStatus status400
2015-08-11 04:02:10 +02:00
json $ object [ "error" .= ("bad request" :: Text )
, "msg" .= ("missing url field" :: Text ) ]
2015-05-09 22:24:33 +02:00
Just url -> do
name <- liftIO (insert table url)
2015-08-11 04:02:10 +02:00
F.print "Registered {} -> {} " (url, name)
json $ object [ "link" .= (url' <> name)
2015-05-09 23:04:14 +02:00
, "name" .= name
, "original" .= url ]