| 1 |
{-# LANGUAGE LambdaCase #-} |
| 2 |
{-# LANGUAGE NamedFieldPuns #-} |
| 3 |
{-# LANGUAGE OverloadedStrings #-} |
| 4 |
{-# LANGUAGE QuasiQuotes #-} |
| 5 |
{-# LANGUAGE TemplateHaskell #-} |
| 6 |
|
| 7 |
module Hledger.Web.Handler.UploadR |
| 8 |
( getUploadR |
| 9 |
, postUploadR |
| 10 |
) where |
| 11 |
|
| 12 |
import Control.Monad.Except (runExceptT) |
| 13 |
import Data.ByteString.Lazy qualified as BL |
| 14 |
import Data.Conduit (connect) |
| 15 |
import Data.Conduit.Binary (sinkLbs) |
| 16 |
import Data.Text.Encoding qualified as TE |
| 17 |
|
| 18 |
import Hledger.Web.Import |
| 19 |
import Hledger.Web.Widget.Common (fromFormSuccess, journalFile404, writeJournalTextIfValidAndChanged) |
| 20 |
|
| 21 |
uploadForm :: FilePath -> Markup -> MForm Handler (FormResult FileInfo, Widget) |
| 22 |
uploadForm f = |
| 23 |
identifyForm "upload" $ \extra -> do |
| 24 |
(res, _) <- mreq fileField fs Nothing |
| 25 |
-- Ignoring the view - setting the name of the element is enough here |
| 26 |
pure (res, $(widgetFile "upload-form")) |
| 27 |
where |
| 28 |
fs = FieldSettings "file" Nothing (Just "file") (Just "file") [] |
| 29 |
|
| 30 |
getUploadR :: FilePath -> Handler () |
| 31 |
getUploadR f = do |
| 32 |
checkServerSideUiEnabled |
| 33 |
postUploadR f |
| 34 |
|
| 35 |
postUploadR :: FilePath -> Handler () |
| 36 |
postUploadR f = do |
| 37 |
checkServerSideUiEnabled |
| 38 |
VD {j} <- getViewData |
| 39 |
require EditPermission |
| 40 |
|
| 41 |
(f', _) <- journalFile404 f j |
| 42 |
((res, view), enctype) <- runFormPost (uploadForm f') |
| 43 |
fi <- fromFormSuccess (showForm view enctype) res |
| 44 |
lbs <- BL.toStrict <$> connect (fileSource fi) sinkLbs |
| 45 |
|
| 46 |
-- Try to parse as UTF-8 |
| 47 |
-- XXX Unfortunate - how to parse as system locale? |
| 48 |
newtxt <- case TE.decodeUtf8' lbs of |
| 49 |
Left e -> do |
| 50 |
setMessage $ |
| 51 |
"Encoding error: '" <> toHtml (show e) <> "'. " <> |
| 52 |
"If your file is not UTF-8 encoded, try the 'edit form', " <> |
| 53 |
"where the transcoding should be handled by the browser." |
| 54 |
showForm view enctype |
| 55 |
Right newtxt -> return newtxt |
| 56 |
runExceptT (writeJournalTextIfValidAndChanged f newtxt) >>= \case |
| 57 |
Left e -> do |
| 58 |
setMessage $ "Failed to load journal: " <> toHtml e |
| 59 |
showForm view enctype |
| 60 |
Right () -> do |
| 61 |
setMessage $ "File " <> toHtml f <> " uploaded successfully" |
| 62 |
redirect JournalR |
| 63 |
where |
| 64 |
showForm view enctype = |
| 65 |
sendResponse <=< defaultLayout $ do |
| 66 |
setTitle "Upload journal" |
| 67 |
[whamlet|<form method=post enctype=#{enctype}>^{view}|] |