summary refs log tree commit diff
path: root/src/Main.hs
blob: 58de3221837e99d051ad0d2f812dc81df2f774e0 (plain) (blame)
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
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, GeneralizedNewtypeDeriving,
    DeriveDataTypeable, FlexibleContexts, MultiParamTypeClasses, TemplateHaskell, 
    TypeFamilies, RecordWildCards, BangPatterns #-}

module Main where

import           Control.Applicative ((<$>), (<*>), optional, pure)
import           Control.Exception (bracket)
import           Control.Monad (msum, mzero, when, unless)
import           Control.Monad.State (get, put)
import           Control.Monad.Reader (ask)
import qualified Crypto.Hash.SHA512 as SHA
import           Data.Acid
import           Data.Acid.Advanced
import           Data.Acid.Local
import qualified Data.ByteString.Base64 as B64 (encode)
import           Data.ByteString.Char8 (ByteString, pack)
import           Data.Data (Data, Typeable)
import           Data.Monoid (mempty)
import           Data.Text (Text)
import qualified Data.Text as T
import           Data.Time
import           Data.SafeCopy (base, deriveSafeCopy)
import           Happstack.Server hiding (Session)
import           Network.CGI (liftIO)
import           System.Environment(getEnv)
import           System.Locale (defaultTimeLocale)

import           Blog
import           BlogDB hiding (addComment)
import           Locales

{- Server -}

tmpPolicy :: BodyPolicy
tmpPolicy = (defaultBodyPolicy "./tmp/" 0 1000 1000)

main :: IO()
main = do
    putStrLn ("TazBlog " ++ version ++ " in Haskell starting")
    tbDir <- getEnv "TAZBLOG"
    bracket (openLocalStateFrom (tbDir ++ "/BlogState") initialBlogState)
            (createCheckpointAndClose)
            (\acid -> simpleHTTP nullConf $ tazBlog acid)

tazBlog :: AcidState Blog -> ServerPart Response
tazBlog acid = do
    msum [ dir (show DE) $ blogHandler acid DE
         , dir (show EN) $ blogHandler acid EN
         , do nullDir
              showIndex acid DE
         , do dir " " $ nullDir
              seeOther ("https://plus.google.com/115916629925754851590" :: String) (toResponse ())
         , path $ \(year :: Int) -> path $ \(month :: Int) -> path $ \(id_ :: String) -> formatOldLink year month id_
         , dir "res" $ serveDirectory DisableBrowsing [] "../res"
         , dir "notice" $ ok $ toResponse showSiteNotice
         , do dir "admin" $ guardSession acid
              adminHandler
         , dir "admin" $ ok $ toResponse $ adminTemplate adminLogin "Login"
         , dir "dologin" $ processLogin acid
         , serveDirectory DisableBrowsing [] "../res"
         ]

blogHandler :: AcidState Blog -> BlogLang -> ServerPart Response
blogHandler acid lang = 
    msum [ path $ \(eId :: Integer) -> showEntry acid lang $ EntryId eId
         , do
            decodeBody tmpPolicy
            dir "postcomment" $ path $ 
              \(eId :: Integer) -> addComment acid $ EntryId eId
         , do nullDir
              showIndex acid lang
         ]

guardSession :: AcidState Blog -> ServerPartT IO ()
guardSession acid = do
    (sId :: Text) <- readCookieValue "session"
    (Just Session{..}) <- query' acid (GetSession $ SessionID sId)
    (uName :: Text) <- readCookieValue "sUser"
    now <- liftIO $ getCurrentTime
    unless (and [uName == username user, sessionTimeDiff now sdate])
      mzero
  where
    sessionTimeDiff :: UTCTime -> UTCTime -> Bool
    sessionTimeDiff now sdate = (diffUTCTime now sdate) > 43200

adminHandler :: ServerPart Response
adminHandler = undefined

formatOldLink :: Int -> Int -> String -> ServerPart Response
formatOldLink y m id_ = 
  flip seeOther (toResponse ()) $ 
    concat $ intersperse' "/"  ["de", show y, show m, replace '.' '/' id_]

showEntry :: AcidState Blog -> BlogLang -> EntryId -> ServerPart Response
showEntry acid lang eId = do
    entry <- query' acid (GetEntry eId)
    ok $ tryEntry entry lang

tryEntry :: Maybe Entry -> BlogLang -> Response
tryEntry Nothing lang = toResponse $ showError NotFound lang
tryEntry (Just entry) _ = toResponse $ blogTemplate eLang eTitle $ renderEntry entry
    where
        eTitle = T.append ": " (title entry)
        eLang = lang entry

showIndex :: AcidState Blog -> BlogLang -> ServerPart Response
showIndex acid lang = do
    entries <- query' acid (LatestEntries lang)
    (page :: Maybe Int) <- optional $ lookRead "page"
    ok $ toResponse $ blogTemplate lang "" $ 
        renderEntries False (eDrop page entries) (topText lang) (Just $ showLinks page lang)
  where
    eDrop :: Maybe Int -> [a] -> [a]
    eDrop (Just i) = drop ((i-1) * 6)
    eDrop Nothing = drop 0 

addComment :: AcidState Blog -> EntryId -> ServerPart Response
addComment acid eId = do
  now <- liftIO $ getCurrentTime >>= return
  nComment <- Comment <$> lookText' "cname"
                      <*> lookText' "ctext"
                      <*> pure now
  update' acid (AddComment eId nComment)
  seeOther ("/" ++ show eId) (toResponse())

processLogin :: AcidState Blog -> ServerPart Response
processLogin acid = do
    decodeBody tmpPolicy
    account <- lookText' "account"
    password <- look "password"
    login <- query' acid (CheckUser (Username account) password)
    if' login
      (addSessionCookie account)
      (ok $ toResponse $ ("Fail?" :: Text))
  where
    addSessionCookie = undefined