-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBackend.elm
613 lines (511 loc) · 22.7 KB
/
Backend.elm
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
module Backend exposing (..)
import Api.Article exposing (Article, ArticleStore, Slug)
import Api.Article.Filters as Filters exposing (Filters(..))
import Api.Data exposing (Data(..))
import Api.Profile exposing (Profile)
import Api.User exposing (Email, UserFull)
import Bridge exposing (..)
import Dict
import Dict.Extra as Dict
import Gen.Msg
import Lamdera exposing (..)
import List.Extra as List
import Pages.Article.Slug_
import Pages.Editor
import Pages.Editor.ArticleSlug_
import Pages.Home_
import Pages.Login
import Pages.Profile.Username_
import Pages.Register
import Pages.Settings
import Task
import Time
import Time.Extra as Time
import Types exposing (BackendModel, BackendMsg(..), FrontendMsg(..), ToFrontend(..))
type alias Model =
BackendModel
app =
Lamdera.backend
{ init = init
, update = update
, updateFromFrontend = updateFromFrontend
, subscriptions = \m -> onConnect CheckSession
}
init : ( Model, Cmd BackendMsg )
init =
( { sessions = Dict.empty
, users = Dict.empty
, articles = Dict.empty
, comments = Dict.empty
}
, Cmd.none
)
update : BackendMsg -> Model -> ( Model, Cmd BackendMsg )
update msg model =
case msg of
CheckSession sid cid ->
model
|> getSessionUser sid
|> Maybe.map (\user -> ( model, sendToFrontend cid (ActiveSession (Api.User.toUser user)) ))
|> Maybe.withDefault ( model, Cmd.none )
RenewSession uid sid cid now ->
( { model | sessions = model.sessions |> Dict.update sid (always (Just { userId = uid, expires = now |> Time.add Time.Day 30 Time.utc })) }
, Time.now |> Task.perform (always (CheckSession sid cid))
)
ArticleCreated t userM clientId article ->
case userM of
Just user ->
let
article_ =
{ slug = uniqueSlug model article.title 1
, title = article.title
, description = article.description
, body = article.body
, tags = article.tags
, createdAt = t
, updatedAt = t
, userId = user.id
}
res =
Success <| loadArticleFromStore model userM article_
in
( { model | articles = model.articles |> Dict.insert article_.slug article_ }
, sendToFrontend clientId (PageMsg (Gen.Msg.Editor (Pages.Editor.GotArticle res)))
)
Nothing ->
( model
, sendToFrontend clientId (PageMsg (Gen.Msg.Editor (Pages.Editor.GotArticle (Failure [ "invalid session" ]))))
)
ArticleCommentCreated t userM clientId slug commentBody ->
case userM of
Just user ->
let
comment =
{ id = Time.posixToMillis t
, createdAt = t
, updatedAt = t
, body = commentBody.body
, author = Api.User.toProfile user
}
newComments =
model.comments
|> Dict.update slug
(\commentsM ->
case commentsM of
Just comments ->
Just (comments |> Dict.insert comment.id comment)
Nothing ->
Just <| Dict.singleton comment.id comment
)
in
( { model | comments = newComments }
, sendToFrontend clientId (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.CreatedComment (Success comment))))
)
Nothing ->
( model
, sendToFrontend clientId (PageMsg (Gen.Msg.Editor (Pages.Editor.GotArticle (Failure [ "invalid session" ]))))
)
NoOpBackendMsg ->
( model, Cmd.none )
updateFromFrontend : SessionId -> ClientId -> ToBackend -> Model -> ( Model, Cmd BackendMsg )
updateFromFrontend sessionId clientId msg model =
let
send v =
( model, send_ v )
send_ v =
sendToFrontend clientId v
onlyWhenArticleOwner slug fn =
onlyWhenArticleOwner_ slug (\r -> ( model, sendToFrontend clientId (fn r) ))
onlyWhenArticleOwner_ slug fn =
let
res =
model |> loadArticleBySlug slug sessionId
userM =
model |> getSessionUser sessionId
in
fn <|
case ( res, userM ) of
( Success article, Just user ) ->
if article.author.username == user.email then
res
else
Failure [ "you do not have permission for this article" ]
_ ->
Failure [ "you do not have permission for this article" ]
in
case msg of
SignedOut user ->
( { model | sessions = model.sessions |> Dict.remove sessionId }, Cmd.none )
GetTags_Home_ ->
let
allTags =
model.articles |> Dict.foldl (\slug article tags -> tags ++ article.tags) [] |> List.unique
in
send (PageMsg (Gen.Msg.Home_ (Pages.Home_.GotTags (Success allTags))))
ArticleList_Home_ { filters, page } ->
let
articleList =
getListing model sessionId filters page
in
send (PageMsg (Gen.Msg.Home_ (Pages.Home_.GotArticles (Success articleList))))
ArticleFeed_Home_ { page } ->
let
userM =
model |> getSessionUser sessionId
articleList =
case userM of
Just user ->
let
filtered =
model.articles
|> Dict.filter (\slug article -> List.member article.userId user.following)
enriched =
filtered |> Dict.map (\slug article -> loadArticleFromStore model userM article)
grouped =
enriched |> Dict.values |> List.greedyGroupsOf Api.Article.itemsPerPage
articles =
grouped |> List.getAt (page - 1) |> Maybe.withDefault []
in
{ articles = articles
, page = page
, totalPages = grouped |> List.length
}
Nothing ->
{ articles = [], page = 0, totalPages = 0 }
in
send (PageMsg (Gen.Msg.Home_ (Pages.Home_.GotArticles (Success articleList))))
ArticleList_Username_ { filters, page } ->
let
articleList =
getListing model sessionId filters page
in
send (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.GotArticles (Success articleList))))
ArticleGet_Editor__ArticleSlug_ { slug } ->
onlyWhenArticleOwner slug
(\r -> PageMsg (Gen.Msg.Editor__ArticleSlug_ (Pages.Editor.ArticleSlug_.LoadedInitialArticle r)))
ArticleUpdate_Editor__ArticleSlug_ { slug, updates } ->
let
articles =
model.articles
|> Dict.update slug
(Maybe.map
(\a -> { a | title = updates.title, body = updates.body, tags = updates.tags })
)
res =
articles
|> Dict.get slug
|> Maybe.map Success
|> Maybe.withDefault (Failure [ "no article with slug: " ++ slug ])
|> Api.Data.map (loadArticleFromStore model (model |> getSessionUser sessionId))
in
( { model | articles = articles }, send_ (PageMsg (Gen.Msg.Editor__ArticleSlug_ (Pages.Editor.ArticleSlug_.UpdatedArticle res))) )
ArticleGet_Article__Slug_ { slug } ->
let
res =
model |> loadArticleBySlug slug sessionId
in
send (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotArticle res)))
ArticleCreate_Editor { article } ->
let
userM =
model |> getSessionUser sessionId
in
( model, Time.now |> Task.perform (\t -> ArticleCreated t userM clientId article) )
ArticleDelete_Article__Slug_ { slug } ->
onlyWhenArticleOwner_ slug
(\r ->
( { model | articles = model.articles |> Dict.remove slug }
, send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.DeletedArticle r)))
)
)
ArticleFavorite_Profile__Username_ { slug } ->
favoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.UpdatedArticle r))))
ArticleUnfavorite_Profile__Username_ { slug } ->
unfavoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.UpdatedArticle r))))
ArticleFavorite_Home_ { slug } ->
favoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Home_ (Pages.Home_.UpdatedArticle r))))
ArticleUnfavorite_Home_ { slug } ->
unfavoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Home_ (Pages.Home_.UpdatedArticle r))))
ArticleFavorite_Article__Slug_ { slug } ->
favoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotArticle r))))
ArticleUnfavorite_Article__Slug_ { slug } ->
unfavoriteArticle sessionId
slug
model
(\r -> send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotArticle r))))
ArticleCommentGet_Article__Slug_ { articleSlug } ->
let
res =
model.comments
|> Dict.get articleSlug
|> Maybe.map Dict.values
|> Maybe.map (List.sortBy .id)
|> Maybe.map List.reverse
|> Maybe.map Success
|> Maybe.withDefault (Success [])
in
send (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotComments res)))
ArticleCommentCreate_Article__Slug_ { articleSlug, comment } ->
let
userM =
model |> getSessionUser sessionId
in
( model, Time.now |> Task.perform (\t -> ArticleCommentCreated t userM clientId articleSlug comment) )
ArticleCommentDelete_Article__Slug_ { articleSlug, commentId } ->
let
newComments =
model.comments
|> Dict.update articleSlug (Maybe.map (\comments -> Dict.remove commentId comments))
in
( { model | comments = newComments }
, send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.DeletedComment (Success commentId))))
)
ProfileGet_Profile__Username_ { username } ->
let
res =
profileByUsername username model
|> Maybe.map Success
|> Maybe.withDefault (Failure [ "user not found" ])
in
send (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.GotProfile res)))
ProfileFollow_Profile__Username_ { username } ->
followUser sessionId
username
model
(\r -> send_ (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.GotProfile r))))
ProfileUnfollow_Profile__Username_ { username } ->
unfollowUser sessionId
username
model
(\r -> send_ (PageMsg (Gen.Msg.Profile__Username_ (Pages.Profile.Username_.GotProfile r))))
ProfileFollow_Article__Slug_ { username } ->
followUser sessionId
username
model
(\r -> send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotAuthor r))))
ProfileUnfollow_Article__Slug_ { username } ->
unfollowUser sessionId
username
model
(\r -> send_ (PageMsg (Gen.Msg.Article__Slug_ (Pages.Article.Slug_.GotAuthor r))))
UserAuthentication_Login { params } ->
let
( response, cmd ) =
model.users
|> Dict.find (\k u -> u.email == params.email)
|> Maybe.map
(\( k, u ) ->
if u.password == params.password then
( Success (Api.User.toUser u), renewSession u.id sessionId clientId )
else
( Failure [ "email or password is invalid" ], Cmd.none )
)
|> Maybe.withDefault ( Failure [ "email or password is invalid" ], Cmd.none )
in
( model, Cmd.batch [ send_ (PageMsg (Gen.Msg.Login (Pages.Login.GotUser response))), cmd ] )
UserRegistration_Register { params } ->
let
( model_, cmd, res ) =
if model.users |> Dict.any (\k u -> u.email == params.email) then
( model, Cmd.none, Failure [ "email address already taken" ] )
else
let
user_ =
{ id = Dict.size model.users
, email = params.email
, username = params.username
, bio = Nothing
, image = "https://static.productionready.io/images/smiley-cyrus.jpg"
, password = params.password
, favorites = []
, following = []
}
in
( { model | users = model.users |> Dict.insert user_.id user_ }
, renewSession user_.id sessionId clientId
, Success (Api.User.toUser user_)
)
in
( model_, Cmd.batch [ cmd, send_ (PageMsg (Gen.Msg.Register (Pages.Register.GotUser res))) ] )
UserUpdate_Settings { params } ->
let
( model_, res ) =
case model |> getSessionUser sessionId of
Just user ->
let
user_ =
{ user
| username = params.username
-- , email = params.email
, password = params.password |> Maybe.withDefault user.password
, image = params.image
, bio = Just params.bio
}
in
( model |> updateUser user_, Success (Api.User.toUser user_) )
Nothing ->
( model, Failure [ "you do not have permission for this user" ] )
in
( model_, send_ (PageMsg (Gen.Msg.Settings (Pages.Settings.GotUser res))) )
NoOpToBackend ->
( model, Cmd.none )
getSessionUser : SessionId -> Model -> Maybe UserFull
getSessionUser sid model =
model.sessions
|> Dict.get sid
|> Maybe.andThen (\session -> model.users |> Dict.get session.userId)
renewSession email sid cid =
Time.now |> Task.perform (RenewSession email sid cid)
getListing : Model -> SessionId -> Filters -> Int -> Api.Article.Listing
getListing model sessionId (Filters { tag, author, favorited }) page =
let
filtered =
model.articles
|> Filters.byFavorite favorited model.users
|> Filters.byTag tag
|> Filters.byAuthor author model.users
enriched =
filtered |> Dict.map (\slug article -> loadArticleFromStore model (model |> getSessionUser sessionId) article)
grouped =
enriched |> Dict.values |> List.greedyGroupsOf Api.Article.itemsPerPage
articles =
grouped |> List.getAt (page - 1) |> Maybe.withDefault []
in
{ articles = articles
, page = page
, totalPages = grouped |> List.length
}
loadArticleBySlug : String -> SessionId -> Model -> Data Article
loadArticleBySlug slug sid model =
model.articles
|> Dict.get slug
|> Maybe.map Success
|> Maybe.withDefault (Failure [ "no article with slug: " ++ slug ])
|> Api.Data.map (loadArticleFromStore model (model |> getSessionUser sid))
uniqueSlug : Model -> String -> Int -> String
uniqueSlug model title i =
let
slug =
title |> String.replace " " "-"
in
if not (model.articles |> Dict.member slug) then
slug
else if not (model.articles |> Dict.member (slug ++ "-" ++ String.fromInt i)) then
slug ++ "-" ++ String.fromInt i
else
uniqueSlug model title (i + 1)
favoriteArticle : SessionId -> Slug -> Model -> (Data Article -> Cmd msg) -> ( Model, Cmd msg )
favoriteArticle sessionId slug model toResponseCmd =
let
res =
model
|> loadArticleBySlug slug sessionId
|> Api.Data.map (\a -> { a | favorited = True })
in
case model |> getSessionUser sessionId of
Just user ->
( if model.articles |> Dict.member slug then
model |> updateUser { user | favorites = (slug :: user.favorites) |> List.unique }
else
model
, toResponseCmd res
)
Nothing ->
( model, toResponseCmd <| Failure [ "invalid session" ] )
unfavoriteArticle : SessionId -> Slug -> Model -> (Data Article -> Cmd msg) -> ( Model, Cmd msg )
unfavoriteArticle sessionId slug model toResponseCmd =
let
res =
model
|> loadArticleBySlug slug sessionId
|> Api.Data.map (\a -> { a | favorited = False })
in
case model |> getSessionUser sessionId of
Just user ->
( model |> updateUser { user | favorites = user.favorites |> List.remove slug }
, toResponseCmd res
)
Nothing ->
( model, toResponseCmd <| Failure [ "invalid session" ] )
followUser : SessionId -> Email -> Model -> (Data Profile -> Cmd msg) -> ( Model, Cmd msg )
followUser sessionId email model toResponseCmd =
let
res =
profileByEmail email model
|> Maybe.map (\a -> Success { a | following = True })
|> Maybe.withDefault (Failure [ "invalid user" ])
in
case model |> getSessionUser sessionId of
Just user ->
( case model.users |> Dict.find (\l u -> u.email == email) of
Just ( _, follow ) ->
model |> updateUser { user | following = (follow.id :: user.following) |> List.unique }
Nothing ->
model
, toResponseCmd res
)
Nothing ->
( model, toResponseCmd <| Failure [ "invalid session" ] )
unfollowUser : SessionId -> Email -> Model -> (Data Profile -> Cmd msg) -> ( Model, Cmd msg )
unfollowUser sessionId email model toResponseCmd =
case model.users |> Dict.find (\k u -> u.email == email) of
Just ( _, followed ) ->
let
res =
followed
|> Api.User.toProfile
|> (\a -> Success { a | following = False })
in
case model |> getSessionUser sessionId of
Just user ->
( model |> updateUser { user | following = user.following |> List.remove followed.id }
, toResponseCmd res
)
Nothing ->
( model, toResponseCmd <| Failure [ "invalid session" ] )
Nothing ->
( model, toResponseCmd <| Failure [ "invalid user" ] )
updateUser : UserFull -> Model -> Model
updateUser user model =
{ model | users = model.users |> Dict.update user.id (Maybe.map (always user)) }
profileByUsername username model =
model.users |> Dict.find (\k u -> u.username == username) |> Maybe.map (Tuple.second >> Api.User.toProfile)
profileByEmail email model =
model.users |> Dict.find (\k u -> u.email == email) |> Maybe.map (Tuple.second >> Api.User.toProfile)
loadArticleFromStore : Model -> Maybe UserFull -> ArticleStore -> Article
loadArticleFromStore model userM store =
let
favorited =
userM |> Maybe.map (\user -> user.favorites |> List.member store.slug) |> Maybe.withDefault False
author =
model.users
|> Dict.get store.userId
|> Maybe.map Api.User.toProfile
|> Maybe.withDefault { username = "error: unknown user", bio = Nothing, image = "", following = False }
in
{ slug = store.slug
, title = store.title
, description = store.description
, body = store.body
, tags = store.tags
, createdAt = store.createdAt
, updatedAt = store.updatedAt
, favorited = favorited
, favoritesCount = model.users |> Dict.filter (\_ user -> user.favorites |> List.member store.slug) |> Dict.size
, author = author
}