-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFoundation.hs
280 lines (242 loc) · 9.21 KB
/
Foundation.hs
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
{-# LANGUAGE ScopedTypeVariables #-}
-- TODO: "SET client_encoding = 'UTF8'"
module Foundation
( BitloveEnv (..)
, UIApp (..)
, Route (..)
, UIAppMessage (..)
, resourcesUIApp
, Handler
, Widget
, getFullUrlRender
, isMiro
, generateETag
, addFilterScript
, withDB, withDBPool, DBPool, HasDB (..), Transaction
, getPopularInfoHashes
, scrapeTorrent
, Period (..)
--, maybeAuth
--, requireAuth
, module Settings
, module Model
, Database
) where
import Prelude
import System.IO (stderr, hPrint)
import Yesod
import Yesod.Static
import Control.Monad
import Control.Monad.Trans.Resource
--import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings (widgetFile, Extra (..), BitloveEnv (..))
import Model
import Text.Jasmine (minifym)
import Text.Hamlet (hamletFile)
import Data.Pool
import Settings.StaticFiles
import Data.Text (Text)
import qualified Data.Text as T
import qualified Control.Exception as E
import qualified Network.Wai as Wai
import Data.ByteString.Char8 (isInfixOf)
import qualified Data.ByteString.Lazy as LB
import qualified Crypto.Hash.SHA1 as SHA1
import Database.PostgreSQL.LibPQ (Connection)
import System.Systemd.Daemon (notifyWatchdog)
import Utils
import PathPieces
import BitloveAuth
import Model.Query
import Tracked
type Database = Connection
type DBPool = Pool Connection
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data UIApp = UIApp
{ settings :: AppConfig BitloveEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, uiDBPool :: DBPool -- ^ Database connection pool.
, httpManager :: Manager
, tracked :: Tracked
}
-- Set up i18n messages. See the message folder.
mkMessage "UIApp" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "UIApp" $(parseRoutesFileNoCheck "config/routes")
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod UIApp where
approot = ApprootRelative
{-
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
-}
makeSessionBackend app =
do let withDB' :: Transaction a -> IO a
withDB' = runResourceT . withDBPool (uiDBPool app)
return $ Just $ sessionBackend withDB'
defaultLayout widget = do
mmsg <- getMessage
msu <- sessionUser
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
addScript $ StaticR js_jquery_1_12_4_min_js
addScript $ StaticR js_jquery_flot_js
addScript $ StaticR js_jquery_flot_time_js
addScript $ StaticR js_graphs_js
addScript $ StaticR js_webtorrent_min_js
addScript $ StaticR js_webtorrent_int_js
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
urlRenderOverride y s =
Just $ uncurry (joinPath y "") $ renderRoute s
errorHandler = errorHandler'
-- The page to be redirected to when authentication is required.
--authRoute _ = Just $ AuthR LoginR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- Grant any read request
isAuthorized _ False = return Authorized
-- Handlers.Auth: for everyone
isAuthorized SignupR _ = return Authorized
isAuthorized LoginR _ = return Authorized
isAuthorized (ActivateR _) _ = return Authorized
isAuthorized ReactivateR _ = return Authorized
-- Handlers.Edit: for respective owners
isAuthorized (UserDetailsR user) _ = authorizeFor user
isAuthorized (UserFeedDetailsR user _) _ = authorizeFor user
isAuthorized (UserFeedR user _) _ = authorizeFor user
isAuthorized (TorrentFileR user _ _) _ = authorizeFor user
-- Forbid by default
isAuthorized _ True = return $ Unauthorized "Cannot modify this resource"
authorizeFor :: MonadHandler m => UserName -> m AuthResult
authorizeFor user = do
canEdit' <- canEdit user
return $ if canEdit'
then Authorized
else Unauthorized "Authorization denied"
-- We want full http://host URLs only in a few cases (feeds, API)
getFullUrlRender :: HandlerT UIApp IO (Route UIApp -> Text)
getFullUrlRender =
do approot' <- appRoot <$> settings <$> getYesod
(T.append approot' .) <$> getUrlRender
isMiro :: MonadHandler m => m Bool
isMiro = let
userAgent = lookup "User-Agent" <$> Wai.requestHeaders <$> waiRequest
in maybe False (isInfixOf "Miro/") <$> userAgent
errorHandler' :: ErrorResponse -> HandlerT UIApp IO TypedContent
errorHandler' NotFound =
fmap toTypedContent $ defaultLayout $ do
setTitle "Bitlove: Not found"
let img = StaticR $ StaticRoute ["404.jpg"] []
toWidget [hamlet|$newline always
<article>
<h2>Not Found
<img src=@{img}>
<p class="hint">Here's a kitten instead.
|]
errorHandler' (PermissionDenied _) =
fmap toTypedContent $ defaultLayout $ do
setTitle "Bitlove: Permission denied"
toWidget [hamlet|$newline always
<h2>Permission denied
|]
errorHandler' e = do
liftIO $ hPrint stderr e
fmap toTypedContent $ defaultLayout $
do setTitle "Bitlove: Error"
let img = StaticR $ StaticRoute ["500.jpg"] []
toWidget [hamlet|$newline always
<article>
<h2>Oops
<img src=@{img}>
|]
generateETag :: MonadHandler m => LB.ByteString -> m ()
generateETag = addHeader "ETag" .
quote .
toHex .
SHA1.hashlazy
where quote t = T.concat ["\"", t, "\""]
addFilterScript :: WidgetT UIApp IO ()
addFilterScript =
addScript $ StaticR js_filter_js
-- | Database interface
class HasDB y where
getDBPool :: HandlerT y IO DBPool
instance HasDB UIApp where
getDBPool = uiDBPool <$> getYesod
type Transaction a = Connection -> IO a
-- How to run database actions.
withDB :: HasDB y => Transaction a -> HandlerT y IO a
withDB f = do
pool <- getDBPool
liftIO $ runResourceT $ withDBPool pool f
-- TODO: could use more of ResourceT
withDBPool :: DBPool -> Transaction a -> ResourceT IO a
withDBPool pool f = liftIO $ do
(db, localPool) <- takeResource pool
let f' = do
txBegin db
a <- f db
txCommit db
return $ Right a
ea <- liftIO $
E.catch f' $ \e -> do
txRollback db
return $ Left e
case ea of
Left (e :: E.SomeException) ->
do destroyResource pool localPool db
E.throw e
Right a ->
do putResource localPool db
-- A successfully finished transaction is our heartbeat
-- for systemd watchdog functionality
void $ liftIO notifyWatchdog
return a
getPopularInfoHashes :: HandlerT UIApp IO [InfoHash]
getPopularInfoHashes =
getYesod >>=
liftIO . trackedPopular . tracked
scrapeTorrent :: InfoHash -> HandlerT UIApp IO (TrackedScrape, TrackedScrape)
scrapeTorrent infoHash = do
tracked <- tracked <$> getYesod
d <- liftIO $ trackedGetData tracked infoHash
return (dataBittorrentScrape d, dataWebtorrentScrape d)