Debian Codegraph @

Hledger/Web/App.hs

raw
1 {-|
2 Most of the definition of the web app is here.
3 In the usual Yesod style, this defines the web app's core types and configuration,
4 and then Application.hs completes the job.
5 -}
6
7 {-# OPTIONS_GHC -fno-warn-orphans #-}
8 {-# LANGUAGE CPP #-}
9 {-# LANGUAGE FlexibleInstances #-}
10 {-# LANGUAGE LambdaCase #-}
11 {-# LANGUAGE MultiParamTypeClasses #-}
12 {-# LANGUAGE NamedFieldPuns #-}
13 {-# LANGUAGE OverloadedStrings #-}
14 {-# LANGUAGE QuasiQuotes #-}
15 {-# LANGUAGE TemplateHaskell #-}
16 {-# LANGUAGE TypeFamilies #-}
17 {-# LANGUAGE ViewPatterns #-}
18
19 module Hledger.Web.App where
20
21 import Control.Applicative ((<|>))
22 import Control.Monad (join, when, unless)
23 -- import Control.Monad.Except (runExceptT) -- now re-exported by Hledger
24 import Data.ByteString.Char8 qualified as BC
25 import Data.Traversable (for)
26 import Data.IORef (IORef, readIORef, writeIORef)
27 import Data.Maybe (fromMaybe)
28 import Data.Text (Text)
29 import Data.Text qualified as T
30 import Data.Time.Calendar (Day)
31 import Network.HTTP.Conduit (Manager)
32 import Network.HTTP.Types (status403)
33 import Network.Wai (requestHeaders)
34 import System.Directory (XdgDirectory (..), createDirectoryIfMissing,
35 getXdgDirectory)
36 import System.FilePath (takeFileName, (</>))
37 import Text.Blaze (Markup)
38 import Text.Hamlet (hamletFile)
39 import Yesod
40 import Yesod.Static
41 import Yesod.Default.Config
42
43 #ifndef DEVELOPMENT
44 import Hledger.Web.Settings (staticDir)
45 import Text.Jasmine (minifym)
46 import Yesod.Default.Util (addStaticContentExternal)
47 #endif
48
49 import Hledger
50 import Hledger.Cli (CliOpts(..), journalReloadIfChanged)
51 import Hledger.Web.Settings (Extra(..), widgetFile)
52 import Hledger.Web.Settings.StaticFiles
53 import Hledger.Web.WebOptions
54 import Hledger.Web.Widget.Common (balanceReportAsHtml)
55 import Data.List (isPrefixOf)
56
57 -- | The site argument for your application. This can be a good place to
58 -- keep settings and values requiring initialization before your application
59 -- starts running, such as database connections. Every handler will have
60 -- access to the data present here.
61 data App = App
62 { settings :: AppConfig DefaultEnv Extra
63 , getStatic :: Static -- ^ Settings for static file serving.
64 , httpManager :: Manager
65 --
66 , appOpts :: WebOpts
67 , appJournal :: IORef Journal
68 -- ^ the current journal, filtered by the initial command line query
69 -- but ignoring any depth limit.
70 }
71
72
73 -- This is where we define all of the routes in our application. For a full
74 -- explanation of the syntax, please see:
75 -- http://www.yesodweb.com/book/handler
76 --
77 -- This function does three things:
78 --
79 -- * Creates the route datatype AppRoute. Every valid URL in your
80 -- application can be represented as a value of this type.
81 -- * Creates the associated type:
82 -- type instance Route App = AppRoute
83 -- * Creates the value resourcesApp which contains information on the
84 -- resources declared below. This is used in Handler.hs by the call to
85 -- mkYesodDispatch
86 --
87 -- What this function does *not* do is create a YesodSite instance for App.
88 -- AppCreating that instance requires all of the handler functions
89 -- for our application to be in scope. However, the handler functions
90 -- usually require access to the AppRoute datatype. Therefore, we
91 -- split these actions into two functions and place the other in a
92 -- separate file (Application.hs).
93 -- mkYesodData defines things like:
94 --
95 -- * type Handler = HandlerFor App -- HandlerT App IO, https://www.yesodweb.com/book/routing-and-handlers#routing-and-handlers_handler_monad
96 -- * type Widget = WidgetFor App () -- WidgetT App IO (), https://www.yesodweb.com/book/widgets
97 --
98 mkYesodData "App" $(parseRoutesFile "config/routes")
99
100 type AppRoute = Route App
101 type Form a = Html -> MForm Handler (FormResult a, Widget)
102
103 -- Please see the documentation for the Yesod typeclass. There are a number
104 -- of settings which can be configured by overriding methods here.
105 instance Yesod App where
106
107 -- Configure the app root, AKA base url, which is prepended to relative hyperlinks.
108 -- 1. when a --base-url was specified, use that
109 -- 2. otherwise, guess it from request headers, which helps us respond from the same hostname/IP address when accessible via multiple IPs
110 -- 3. otherwise, leave it empty (relative links stay relative).
111 -- Past issues: #2099, #2100, #2127, #hledger-2024-07-18
112 approot
113 | hasbaseurl = ApprootMaster (T.pack . base_url_ . appOpts)
114 | otherwise = guessApprootOr (ApprootMaster (appRoot . settings))
115 where
116 hasbaseurl = any ("--base-url" `isPrefixOf`) progArgs
117 -- needs unsafePerformIO; does not detect abbreviations like --base
118
119 makeSessionBackend _ = do
120 hledgerdata <- getXdgDirectory XdgCache "hledger"
121 createDirectoryIfMissing True hledgerdata
122 let sessionexpirysecs = 120
123 Just <$> defaultClientSessionBackend sessionexpirysecs (hledgerdata </> "hledger-web_client_session_key.aes")
124
125 -- defaultLayout :: WidgetFor site () -> HandlerFor site Html
126 defaultLayout widget = do
127
128 -- Don't run if server-side UI is disabled.
129 -- This single check probably covers all the HTML-returning handlers,
130 -- but for now they do the check as well.
131 checkServerSideUiEnabled
132
133 master <- getYesod
134 here <- fromMaybe RootR <$> getCurrentRoute
135 VD{opts, j, qparam, q, qopts, perms} <- getViewData
136 msg <- getMessage
137 showSidebar <- shouldShowSidebar
138
139 let rspec = reportspec_ (cliopts_ opts)
140 ropts = _rsReportOpts rspec
141 ropts' = (_rsReportOpts rspec)
142 {accountlistmode_ = ALTree -- force tree mode for sidebar
143 ,empty_ = True -- show zero items by default
144 }
145 rspec' = rspec{_rsQuery=q,_rsReportOpts=ropts'}
146
147 hideEmptyAccts <- if empty_ ropts
148 then return True
149 else (== Just "1") . lookup "hideemptyaccts" . reqCookies <$> getRequest
150
151 let accounts =
152 balanceReportAsHtml (JournalR, RegisterR) here hideEmptyAccts j qparam qopts $
153 styleAmounts (journalCommodityStylesWith HardRounding j) $
154 balanceReport rspec' j
155
156 topShowmd = if showSidebar then "col-md-4" else "col-any-0" :: Text
157 topShowsm = if showSidebar then "col-sm-4" else "" :: Text
158 sideShowmd = if showSidebar then "col-md-4" else "col-any-0" :: Text
159 sideShowsm = if showSidebar then "col-sm-4" else "" :: Text
160 mainShowmd = if showSidebar then "col-md-8" else "col-md-12" :: Text
161 mainShowsm = if showSidebar then "col-sm-8" else "col-sm-12" :: Text
162
163 -- We break up the default layout into two components:
164 -- default-layout is the contents of the body tag, and
165 -- default-layout-wrapper is the entire page. Since the final
166 -- value passed to hamletToRepHtml cannot be a widget, this allows
167 -- you to use normal widget features in default-layout.
168 pc <- widgetToPageContent $ do
169 addStylesheet $ StaticR css_bootstrap_min_css
170 addStylesheet $ StaticR css_bootstrap_datepicker_standalone_min_css
171 -- load these things early, in HEAD:
172 toWidgetHead [hamlet|
173 <script type="text/javascript" src="@{StaticR js_jquery_min_js}">
174 <script type="text/javascript" src="@{StaticR js_typeahead_bundle_min_js}">
175 |]
176 addScript $ StaticR js_bootstrap_min_js
177 addScript $ StaticR js_bootstrap_datepicker_min_js
178 addScript $ StaticR js_jquery_url_js
179 addScript $ StaticR js_jquery_cookie_js
180 addScript $ StaticR js_jquery_hotkeys_js
181 addScript $ StaticR js_jquery_flot_min_js
182 addScript $ StaticR js_jquery_flot_selection_min_js
183 addScript $ StaticR js_jquery_flot_time_min_js
184 addScript $ StaticR js_jquery_flot_tooltip_min_js
185 toWidget [hamlet| \<!--[if lte IE 8]> <script type="text/javascript" src="@{StaticR js_excanvas_min_js}"></script> <![endif]--> |]
186 addStylesheet $ StaticR hledger_css
187 addScript $ StaticR hledger_js
188 $(widgetFile "default-layout")
189
190 withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
191
192 -- XXX why disabled during development ? Affects ghci, ghcid, tests, #2139 ?
193 #ifndef DEVELOPMENT
194 -- This function creates static content files in the static folder
195 -- and names them based on a hash of their content. This allows
196 -- expiration dates to be set far in the future without worry of
197 -- users receiving stale content.
198 addStaticContent = addStaticContentExternal minifym base64md5 staticDir (StaticR . flip StaticRoute [])
199 #endif
200
201 -- This instance is required to use forms. You can modify renderMessage to
202 -- achieve customized and internationalized form validation messages.
203 instance RenderMessage App FormMessage where
204 renderMessage _ _ = defaultFormMessage
205
206
207 ----------------------------------------------------------------------
208 -- template and handler utilities
209
210 -- view data, used by the add form and handlers
211 -- XXX Parameter p - show/hide postings
212
213 -- | A bundle of data useful for hledger-web request handlers and templates.
214 data ViewData = VD
215 { opts :: WebOpts -- ^ the command-line options at startup
216 , today :: Day -- ^ today's date (for queries containing relative dates)
217 , j :: Journal -- ^ the up-to-date parsed unfiltered journal -- XXX rename
218 , qparam :: Text -- ^ the current "q" request parameter
219 , q :: Query -- ^ a query parsed from the q parameter
220 , qopts :: [QueryOpt] -- ^ query options parsed from the q parameter
221 , perms :: [Permission] -- ^ permissions enabled for this request (by --allow and/or X-Sandstorm-Permissions)
222 } deriving (Show)
223
224 instance Show Text.Blaze.Markup where show _ = "<blaze markup>"
225
226 -- | Gather data used by handlers and templates in the current request.
227 getViewData :: Handler ViewData
228 getViewData = do
229 App{
230 appOpts=opts@WebOpts{ cliopts_=copts@CliOpts{ reportspec_=rspec@ReportSpec{_rsReportOpts, _rsQuery} } },
231 appJournal
232 } <- getYesod
233 let today = _rsDay rspec
234
235 -- try to read the latest journal content, keeping the old content
236 -- if there's an error
237 (j, mjerr) <- getCurrentJournal
238 appJournal
239 copts{reportspec_=rspec{_rsReportOpts=_rsReportOpts{no_elide_=True}}}
240 today
241
242 -- Get the query specified by the q request parameter, or no query if this fails.
243 qparam <- fromMaybe "" <$> lookupGetParam "q"
244 (q1, qopts, mqerr) <- do
245 case parseQuery today qparam of
246 Right (q0, qopts) -> return (q0, qopts, Nothing)
247 Left err -> return (Any, [], Just err)
248 -- To this, add any depth limit from the initial startup query, preserving that.
249 let
250 initialdepthq = filterQuery queryIsDepth _rsQuery
251 q = simplifyQuery $ And [q1, initialdepthq]
252
253 -- if either of the above gave an error, display it
254 maybe (pure ()) (setMessage . toHtml) $ mjerr <|> mqerr
255
256 -- find out which permissions are enabled
257 perms <- case allow_ opts of
258 -- if started with --allow=sandstorm, take permissions from X-Sandstorm-Permissions header
259 SandstormAccess -> do
260 let h = "X-Sandstorm-Permissions"
261 hs <- fmap (BC.split ',' . snd) . filter ((== h) . fst) . requestHeaders <$> waiRequest
262 fmap join . for (join hs) $ \x -> case parsePermission x of
263 Left e -> [] <$ addMessage "" ("Unknown permission: " <> toHtml e)
264 Right p -> pure [p]
265 -- otherwise take them from the access level specified by --allow's access level
266 cliaccess -> pure $ accessLevelToPermissions cliaccess
267
268 return VD{opts, today, j, qparam, q, qopts, perms}
269
270 checkServerSideUiEnabled :: Handler ()
271 checkServerSideUiEnabled = do
272 VD{opts=WebOpts{server_mode_}} <- getViewData
273 when (server_mode_ == ServeJson) $
274 -- this one gives 500 internal server error when called from defaultLayout:
275 -- permissionDenied "server-side UI is disabled due to --serve-api"
276 sendResponseStatus status403 ("server-side UI is disabled due to --serve-api" :: Text)
277
278 -- | Find out if the sidebar should be visible. Show it, unless there is a
279 -- showsidebar cookie set to "0", or a ?sidebar=0 query parameter.
280 shouldShowSidebar :: Handler Bool
281 shouldShowSidebar = do
282 msidebarparam <- lookupGetParam "sidebar"
283 msidebarcookie <- lookup "showsidebar" . reqCookies <$> getRequest
284 return $
285 let disablevalues = ["","0"]
286 in maybe True (`notElem` disablevalues) $ msidebarparam <|> msidebarcookie
287
288 -- | Update our copy of the journal if the file changed. If there is an
289 -- error while reloading, keep the old one and return the error, and set a
290 -- ui message.
291 getCurrentJournal :: IORef Journal -> CliOpts -> Day -> Handler (Journal, Maybe String)
292 getCurrentJournal jref opts d = do
293 -- re-apply any initial filter specified at startup
294 let depthlessinitialq = filterQuery (not . queryIsDepth) $ _rsQuery $ reportspec_ opts
295 -- XXX put this inside atomicModifyIORef' for thread safety
296 j <- liftIO (readIORef jref)
297 ej <- liftIO . runExceptT $ journalReloadIfChanged opts d j
298 case ej of
299 Left e -> do
300 setMessage "error while reading journal"
301 return (j, Just e)
302 Right (j', True) -> do
303 liftIO . writeIORef jref $ filterJournalTransactions depthlessinitialq j'
304 return (j',Nothing)
305 Right (_, False) -> return (j, Nothing)
306
307 -- | In a request handler, check for the given permission
308 -- and fail with a message if it's not present.
309 require :: Permission -> Handler ()
310 require p = do
311 VD{perms} <- getViewData
312 unless (p `elem` perms) $ permissionDenied $
313 "Missing the '" <> T.pack (showPermission p) <> "' permission"