breve/src/Application.hs

67 lines
1.8 KiB
Haskell
Raw Normal View History

2015-05-09 22:24:33 +02:00
{-# LANGUAGE OverloadedStrings, NamedFieldPuns #-}
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-04-09 17:11:27 +02:00
import Control.Monad.IO.Class (liftIO)
import Text.Printf (printf)
2015-05-09 23:04:14 +02:00
import Data.Aeson hiding (json)
2015-05-09 22:24:33 +02:00
import Data.Monoid
import Data.Text (pack, unpack)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Data.Text.Lazy (toStrict)
import Web.Spock.Safe
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
logStr :: String -> ActionT IO ()
logStr = liftIO . putStrLn
2015-05-10 03:29:59 +02:00
serveStatic :: FilePath -> Middleware
serveStatic = staticPolicy . addBase
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
Nothing -> html (render $ message "404: this one does not exist")
Just url -> do
logStr (printf "Resolved %s -> %s" name url)
redirect (pack url)
2015-05-09 23:04:14 +02:00
post "/" $ do
2015-05-09 22:24:33 +02:00
url <- fmap unpack <$> param "url"
case url of
Nothing -> html (render $ message "bad request")
Just url -> do
name <- liftIO (insert table url)
logStr (printf "Registered %s -> %s " url name)
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
url <- fmap unpack <$> param "url"
case url of
Nothing -> text "bad request"
Just url -> do
name <- liftIO (insert table url)
logStr (printf "Registered %s -> %s " url name)
2015-05-09 23:04:14 +02:00
json $ object [ "link" .= pack (url' <> name)
, "name" .= name
, "original" .= url ]