aboutsummaryrefslogtreecommitdiff
path: root/hoarder-server/src/Hoarder/Server/Handler/Movie.hs
blob: 84ae2d5d3f3448044f55e6059bc2fd85048967b5 (plain)
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TypeFamilies          #-}
module Hoarder.Server.Handler.Movie where

import           Protolude                            hiding (get, replace)
import           Control.Monad.Catch                  (throwM)
import           Control.Lens
import           Data.Time                            (getCurrentTime)
import qualified Database.Esqueleto                   as E
import qualified Database.Esqueleto.Internal.Internal as EL
import           Database.Persist                     (Entity (..),
                                                       SelectOpt (..), delete,
                                                       deleteCascade,
                                                       deleteWhere, get,
                                                       getBy, insert,
                                                       selectList, (==.),
                                                       replace)
import           Database.Persist.Sqlite              (fromSqlKey, toSqlKey)
import           Hoarder.Model
import           Hoarder.Server.DB
import           Hoarder.Server.Handler
import           Hoarder.Server.Handler.File
import           Hoarder.Server.Handler.Image
import           Path
import           Servant                              (NoContent (..))
import           Servant.Server                       (ServerError (..), err404,
                                                       err409)
import           System.FilePath                      (takeFileName)


searchQueryToSql :: E.SqlExpr (Entity SimpleMovie) -> MovieSearchQuery -> E.SqlExpr (EL.Value Bool)
searchQueryToSql m (MovieSearchQueryFile Nothing) =
    E.notExists $ E.from $ \mf ->
    E.where_ (mf E.^. MovieMovieFileMovie E.==. m E.^. SimpleMovieId)
searchQueryToSql m (MovieSearchQueryFile (Just fp)) =
    E.exists $ E.from $ \(f, mf) ->
    E.where_
        (     f E.^. SimpleMovieFileName E.==. E.val fpt
        E.&&. mf E.^. MovieMovieFileFile E.==. f E.^. SimpleMovieFileId
        E.&&. mf E.^. MovieMovieFileMovie E.==. m E.^. SimpleMovieId
        )
  where
    fpt = toS fp
searchQueryToSql m (MovieSearchQueryMaxRuntime r) =
    m E.^. SimpleMovieRuntime E.<=. E.just (E.val r)
searchQueryToSql m (MovieSearchQueryMinYear y) =
    m E.^. SimpleMovieYear E.>=. E.just (E.val y)
searchQueryToSql m (MovieSearchQueryMinIMDbScore s) =
    m E.^. SimpleMovieIMDbScore E.>=. E.just (E.val s)
searchQueryToSql m (MovieSearchQueryMinMetacriticScore s) =
    m E.^. SimpleMovieMetacriticScore E.>=. E.just (E.val s)
searchQueryToSql m (MovieSearchQueryUnseenBy un') =
    E.not_ $ searchQueryToSql m (MovieSearchQuerySeenBy un')
searchQueryToSql m (MovieSearchQuerySeenBy un') =
    E.exists $ E.from $ \(usm, su) ->
    E.where_
        (     su E.^. SimpleUserName E.==. E.val un'
        E.&&. usm E.^. UserSeenMovieUser E.==. su E.^. SimpleUserId
        E.&&. usm E.^. UserSeenMovieMovie E.==. m E.^. SimpleMovieId
        )
searchQueryToSql m (MovieSearchQuerySeenBefore ud) =
    E.exists $ E.from $ \(usm, su) ->
    E.where_
        (     su E.^. SimpleUserName E.==. E.val u
        E.&&. usm E.^. UserSeenMovieUser E.==. su E.^. SimpleUserId
        E.&&. usm E.^. UserSeenMovieMovie E.==. m E.^. SimpleMovieId
        E.&&. usm E.^. UserSeenMovieMovie E.==. m E.^. SimpleMovieId
        E.&&. usm E.^. UserSeenMovieDatetime E.<=. E.val d
        )
  where
    UserDateTime u d = ud
searchQueryToSql m (MovieSearchQuerySeenAfter ud) =
    E.exists $ E.from $ \(usm, su) ->
    E.where_
        (     su E.^. SimpleUserName E.==. E.val u
        E.&&. usm E.^. UserSeenMovieUser E.==. su E.^. SimpleUserId
        E.&&. usm E.^. UserSeenMovieMovie E.==. m E.^. SimpleMovieId
        E.&&. usm E.^. UserSeenMovieMovie E.==. m E.^. SimpleMovieId
        E.&&. usm E.^. UserSeenMovieDatetime E.>=. E.val d
        )
  where
    UserDateTime u d = ud
searchQueryToSql m (MovieSearchQueryMovieIds mids) =
    E.exists $
    E.where_ $ m E.^. SimpleMovieId `E.in_` E.valList (map toSqlKey mids)

searchQueriesToSql :: E.SqlExpr (Entity SimpleMovie) -> [MovieSearchQuery] -> E.SqlExpr (EL.Value Bool)
searchQueriesToSql m = foldr (\a b -> b E.&&. searchQueryToSql m a) (E.val True)

searchSortByToSql :: E.SqlExpr (Entity SimpleMovie) -> MovieSearchSortBy -> E.SqlExpr EL.OrderBy
searchSortByToSql m AscMovieTitle = E.asc (m E.^. SimpleMovieTitle)
searchSortByToSql m AscIMDbScore = E.asc (m E.^. SimpleMovieIMDbScore)
searchSortByToSql m AscMetacriticScore = E.asc (m E.^. SimpleMovieMetacriticScore)
searchSortByToSql m AscRuntime = E.asc (m E.^. SimpleMovieRuntime)

searchSortBysToSql :: E.SqlExpr (Entity SimpleMovie) -> [MovieSearchSortBy] -> [E.SqlExpr EL.OrderBy]
searchSortBysToSql m = map (searchSortByToSql m)

searchToSql :: MonadIO m => MovieSearch -> E.SqlPersistT m [(Entity SimpleMovie, Maybe (Entity ImageDB))]
searchToSql ms =
    E.select $
    E.from $ \(m `E.LeftOuterJoin` maybemi `E.LeftOuterJoin` maybei) -> do
    E.where_ $ searchQueriesToSql m (ms ^. movieSearchQueries)
    E.on ((maybemi E.?. MovieImageImage) E.==. maybei E.?. ImageDBId)
    E.on ((maybemi E.?. MovieImageMovie) E.==. E.just (m E.^. SimpleMovieId))
    E.orderBy $ searchSortBysToSql m (ms ^. movieSearchSortBys)
    return (m, maybei)

filterFst :: Eq a => [(a, b)] -> [(a, b)]
filterFst [] = []
filterFst (x1 : []) = [x1]
filterFst (x1 : x2 : xs) = if (fst x1 == fst x2) then filterFst (x2 : xs) else x1 : (filterFst (x2 : xs))

getResponseMovies :: MovieSearch -> App [ResponseSimpleMovie]
getResponseMovies ms = do
    movies <- runDB (searchToSql ms)
    return $ map getresponsemovieaux (filterFst movies)
  where
    getresponsemovieaux (Entity mid m, mei) = ResponseSimpleMovie
        (fromSqlKey mid)
        m
        (maybeimage mei)
    maybeimage Nothing = Nothing
    maybeimage (Just ei) = Just (imageDBToImage $ entityVal ei)

getEntitySimpleMovieFromIMDbId :: Text -> App (Entity SimpleMovie)
getEntitySimpleMovieFromIMDbId imdbid = do
    moviedbs <- runDB $ selectList [ SimpleMovieIMDbid ==. Just imdbid ] [ Asc SimpleMovieTitle ]
    case moviedbs of
        [] -> throwM err404 { errBody = "Can't find movie with imdbid " <> toUtf8Lazy (show imdbid :: Text) }
        em : _ -> return em

getMovieFromIMDbId :: Text -> App ResponseMovie
getMovieFromIMDbId imdbid = entitySimpleMovieToResponseMovie =<< getEntitySimpleMovieFromIMDbId imdbid

entitySimpleMovieToResponseMovie :: Entity SimpleMovie -> App ResponseMovie
entitySimpleMovieToResponseMovie esm = do
    m <- entitySimpleMovieToMovie esm
    return $ ResponseMovie (fromSqlKey $ entityKey esm) m

getEntitySimpleMovieFromFile :: Maybe FilePath -> App (Entity SimpleMovie)
getEntitySimpleMovieFromFile mfp = do
    mf <- case mfp of
        Nothing -> return Nothing
        Just fp -> Just <$> fileWithBaseDirFromFilePath fp
    moviedbs <- runDB (searchToSql (ms $ toFilePath . filename <$> mf))
    case moviedbs of
        [] -> case mf of
            Just f -> throwM err404 { errBody = "Can't find movie with file " <> toUtf8Lazy (toFilePath f) }
            Nothing -> throwM err404 { errBody = "Can't find movie with no file" }
        (em, _) : _ -> return em
        -- ^ TODO: return image too
  where
    ms mfilename = MovieSearch
        { _movieSearchQueries = [MovieSearchQueryFile mfilename]
        , _movieSearchSortBys = [AscMovieTitle]
        }

getMovieFromFile :: Maybe FilePath -> App ResponseMovie
getMovieFromFile mfp = entitySimpleMovieToResponseMovie =<< getEntitySimpleMovieFromFile mfp

getMovie :: Int64 -> App ResponseMovie
getMovie movieID = do
    moviedb <- getSimpleMovie movieID
    entitySimpleMovieToResponseMovie (Entity (toSqlKey movieID) moviedb)

getSimpleMovie :: Int64 -> App SimpleMovie
getSimpleMovie mid = do
    maybeMovie <- runDB $ get $ toSqlKey mid
    case maybeMovie of
        Just m -> return m
        Nothing -> throwM err404

deleteMovie :: Int64 -> App NoContent
deleteMovie movieID = do
    maybeMovie <- runDB $ get dbmid
    case maybeMovie of
        Nothing -> throwM $ err404 { errBody = "Could not find movie " <> toUtf8Lazy (show movieID :: Text) }
        Just _ -> do
            ems <- runDB $ E.select $
                E.from $ \(mm, m') -> do
                E.where_
                    (     mm E.^. MovieMovieFileMovie E.==. E.val dbmid
                    E.&&. mm E.^. MovieMovieFileFile E.==. m' E.^. SimpleMovieFileId
                    )
                return m'
            deleteImages dbmid
            runDB $ do
                mapM_ (deleteCascade . entityKey) ems
                deleteCascade dbmid
                -- ^ TODO: use deleteCascade from esqueleto
                -- see https://github.com/prowdsponsor/esqueleto/issues/147
            return NoContent
  where
    dbmid :: SimpleMovieId
    dbmid = toSqlKey movieID

deleteImages :: SimpleMovieId -> App ()
deleteImages dbmid = do
    eis <- runDB $ E.select $
        E.from $ \(mi, i) -> do
        E.where_
            (     mi E.^. MovieImageMovie E.==. E.val dbmid
            E.&&. mi E.^. MovieImageImage E.==. i E.^. ImageDBId
            )
        return i
    runDB $ mapM_ (deleteCascade . entityKey) eis
    mapM_ (removeImage . imageDBToImage . entityVal) eis
    -- ^ removeImage handle case of image which does not exist

getAllEntitySimpleMovieFiles :: App [Entity SimpleMovieFile]
getAllEntitySimpleMovieFiles = runDB $ selectList [] [ Asc SimpleMovieFileName ]

getEntitySimpleMovieFiles :: SimpleMovieId -> App [Entity SimpleMovieFile]
getEntitySimpleMovieFiles dbmid = runDB $
    E.select $
    E.from $ \(mm, m') -> do
    E.where_
        (     mm E.^. MovieMovieFileMovie E.==. E.val dbmid
        E.&&. mm E.^. MovieMovieFileFile E.==. m' E.^. SimpleMovieFileId
        )
    E.orderBy [ E.asc (m' E.^. SimpleMovieFileName) ]
    return m'

insertPerson :: Person -> App PersonId
insertPerson person' = do
    mp <- runDB $ getBy $ UniquePerson (person' ^. personName) (person' ^. personIdentificator)
    case mp of
        Nothing -> runDB $ insert person'
        Just (Entity pid _) -> return pid

insertDirectors :: SimpleMovieId -> [Person] -> App [PersonId]
insertDirectors mid ds = do
    directors' <- mapM insertPerson ds
    mapM_ (insertMovieDirector . MovieDirector mid) directors'
    return directors'
  where
    insertMovieDirector moviedirector = do
        mm <- runDB $ getBy $ UniqueMovieDirector (moviedirector ^. movieDirectorMovie) (moviedirector ^. movieDirectorDirector)
        case mm of
            Nothing -> runDB $ insert moviedirector
            Just (Entity mid' _) -> return mid'

insertWriters :: SimpleMovieId -> [Person] -> App [PersonId]
insertWriters mid ds = do
    writers' <- mapM insertPerson ds
    mapM_ (insertMovieWriter . MovieWriter mid) writers'
    return writers'
  where
    insertMovieWriter moviewriter = do
        mm <- runDB $ getBy $ UniqueMovieWriter (moviewriter ^. movieWriterMovie) (moviewriter ^. movieWriterWriter)
        case mm of
            Nothing -> runDB $ insert moviewriter
            Just (Entity mid' _) -> return mid'

insertActors :: SimpleMovieId -> [Actor] -> App [ActorDBId]
insertActors mid ds = do
    actors' <- mapM insertActor ds
    mapM_ (insertMovieActor . MovieActor mid) actors'
    return actors'
  where
    insertActor actor = do
        pid <- insertPerson (actor ^. actorPerson)
        runDB $ insert (ActorDB pid (actor ^. actorRoles))
    insertMovieActor movieactor = do
        mm <- runDB $ getBy $ UniqueMovieActor (movieactor ^. movieActorMovie) (movieactor ^. movieActorActor)
        case mm of
            Nothing -> runDB $ insert movieactor
            Just (Entity mid' _) -> return mid'

insertCountries :: SimpleMovieId -> [Country] -> App [CountryId]
insertCountries mid ds = do
    countries' <- mapM insertCountry ds
    mapM_ (insertMovieCountry . MovieCountry mid) countries'
    return countries'
  where
    insertCountry country = do
        mc <- runDB $ getBy $ UniqueCountry (country ^. countryName)
        case mc of
            Nothing -> runDB $ insert country
            Just (Entity cid _) -> return cid
    insertMovieCountry moviecountry = do
        mm <- runDB $ getBy $ UniqueMovieCountry (moviecountry ^. movieCountryMovie) (moviecountry ^. movieCountryCountry)
        case mm of
            Nothing -> runDB $ insert moviecountry
            Just (Entity mid' _) -> return mid'

insertLanguages :: SimpleMovieId -> [Language] -> App [LanguageId]
insertLanguages mid ds = do
    languages' <- mapM insertLanguage ds
    mapM_ (insertMovieLanguage . MovieLanguage mid) languages'
    return languages'
  where
    insertLanguage language = do
        ml <- runDB $ getBy $ UniqueLanguage (language ^. languageName)
        case ml of
            Nothing -> runDB $ insert language
            Just (Entity lid _) -> return lid
    insertMovieLanguage movielanguage = do
        mm <- runDB $ getBy $ UniqueMovieLanguage (movielanguage ^. movieLanguageMovie) (movielanguage ^. movieLanguageLanguage)
        case mm of
            Nothing -> runDB $ insert movielanguage
            Just (Entity mid' _) -> return mid'

insertGenres :: SimpleMovieId -> [Genre] -> App [GenreId]
insertGenres mid ds = do
    genres' <- mapM insertGenre ds
    mapM_ (insertMovieGenre . MovieGenre mid) genres'
    return genres'
  where
    insertGenre genre = do
        mg <- runDB $ getBy $ UniqueGenre (genre ^. genreName)
        case mg of
            Nothing -> runDB $ insert genre
            Just (Entity gid _) -> return gid
    insertMovieGenre moviegenre = do
        mm <- runDB $ getBy $ UniqueMovieGenre ( moviegenre ^. movieGenreMovie) (moviegenre ^. movieGenreGenre)
        case mm of
            Nothing -> runDB $ insert moviegenre
            Just (Entity mid' _) -> return mid'

insertImages :: SimpleMovieId -> [Image] -> App [ImageDBId]
insertImages mid ds = do
    images' <- mapM insertImage ds
    mapM_ (insertMovieImage . MovieImage mid) images'
    return images'
  where
    insertImage :: Image -> App ImageDBId
    insertImage image = do
        fi <- imageToTextFilePath image
        mi <- runDB $ getBy $ UniqueImage fi
        case mi of
            Nothing -> do
                copyImageFromCache image
                runDB $ insert $ ImageDB fi
            Just (Entity iid _) -> return iid
      where
        imageToTextFilePath i = do
            f <- filenameCustom (i ^. imageFile)
            return (toS $ toFilePath f)
    insertMovieImage movieimage = do
        mm <- runDB $ getBy $ UniqueMovieImage ( movieimage ^. movieImageMovie) (movieimage ^. movieImageImage)
        case mm of
            Nothing -> runDB $ insert movieimage
            Just (Entity mid' _) -> return mid'

getResponseMovieFiles :: App [ResponseMovieFile]
getResponseMovieFiles = do
    em <- getAllEntitySimpleMovieFiles
    return $ map (\(Entity mid m) -> ResponseMovieFile (fromSqlKey mid) m) em

postMovieFiles :: MovieFile -> App Int64
postMovieFiles moviefile = do
    mm <- runDB $ getBy $ UniqueMovieFile name'
    case mm of
        Nothing -> do
            vs <- mapM insertVideo (moviefile ^. movieFileVideos)
            as <- mapM insertAudio (moviefile ^. movieFileAudios)
            ss <- mapM insertSubtitle (moviefile ^. movieFileSubtitles)
            let moviefiledb = SimpleMovieFile
                    name'
                    (moviefile ^. movieFileFormat)
                    (moviefile ^. movieFileDuration)
                    (sizeToInt $ moviefile ^. movieFileSize)
            fid <- insertSimpleMovieFile moviefiledb
            mapM_ (insertMovieFileMovieFileVideo . MovieFileMovieFileVideo fid) vs
            mapM_ (insertMovieFileMovieFileAudio . MovieFileMovieFileAudio fid) as
            mapM_ (insertMovieFileMovieFileSubtitle . MovieFileMovieFileSubtitle fid) ss
            return $ fromSqlKey fid
        Just _ -> throwM err409 { errBody = "MovieFile \"" <> toUtf8Lazy name' <> "\" is already present in the database." }
  where
    name' = toS $ takeFileName (moviefile ^. movieFileName)
    insertVideo video = runDB $ insert video
    insertAudio audio = runDB $ insert audio
    insertSubtitle subtitle = runDB $ insert subtitle
    insertSimpleMovieFile moviefiledb = do
        mm <- runDB $ getBy $ UniqueMovieFile (moviefiledb ^. simpleMovieFileName)
        case mm of
            Nothing -> runDB $ insert moviefiledb
            Just _ -> throwM err409 { errBody = "SimpleMovieFile \"" <> toUtf8Lazy (moviefiledb ^. simpleMovieFileName) <> "\" is already present in the database." }
    insertMovieFileMovieFileVideo m = do
        mm <- runDB $ getBy $ UniqueMovieFileVideo (m ^. movieFileMovieFileVideoFile) (m ^. movieFileMovieFileVideoVideo)
        case mm of
            Nothing -> runDB $ insert m
            Just (Entity mid _) -> return mid
    insertMovieFileMovieFileAudio m = do
        mm <- runDB $ getBy $ UniqueMovieFileAudio (m ^. movieFileMovieFileAudioFile) (m ^. movieFileMovieFileAudioAudio)
        case mm of
            Nothing -> runDB $ insert m
            Just (Entity mid _) -> return mid
    insertMovieFileMovieFileSubtitle m = do
        mm <- runDB $ getBy $ UniqueMovieFileSubtitle (m ^. movieFileMovieFileSubtitleFile) (m ^. movieFileMovieFileSubtitleSubtitle)
        case mm of
            Nothing -> runDB $ insert m
            Just (Entity mid _) -> return mid

postMovies :: Movie -> App Int64
postMovies m = do
    mm <- runDB $ getBy $ UniqueMovie (m ^. movieTitle) (m ^. movieIdentificator)
    case mm of
        Nothing -> do
            let moviedb = SimpleMovie
                    (m ^. movieTitle)
                    (m ^. movieYear)
                    (m ^. movieCriticScore)
                    (m ^. movieAudienceScore)
                    (m ^. movieIMDbScore)
                    (m ^. movieMetacriticScore)
                    (m ^. movieSynopsis)
                    (m ^. movieRating)
                    (m ^. movieRuntime)
                    (m ^. movieStudio)
                    (m ^. movieIMDbid)
                    (m ^. movieRtid)
                    (m ^. movieMcid)
                    (m ^. movieWikidataid)
                    (m ^. movieIdentificator)
            mid <- insertMovie moviedb
            let dbmid = fromSqlKey mid
            _ <- putMovieMovieFile dbmid (m ^. movieFiles)
            _ <- insertDirectors mid (m ^. movieDirectors)
            _ <- insertWriters mid (m ^. movieWriters)
            _ <- insertActors mid (m ^. movieActors)
            _ <- insertCountries mid (m ^. movieCountries)
            _ <- insertLanguages mid (m ^. movieLanguages)
            _ <- insertGenres mid (m ^. movieGenres)
            _ <- insertImages mid (m ^. movieImages)
            return dbmid
        Just _ -> throwM err409 { errBody = "Movie \"" <> toUtf8Lazy (m ^. movieTitle) <> "\" is already present in the database." }
  where
    insertMovie moviedb = do
        mm <- runDB $ getBy $ UniqueMovie (moviedb ^. simpleMovieTitle) (moviedb ^. simpleMovieIdentificator)
        case mm of
            Nothing -> runDB $ insert moviedb
            Just _ -> throwM err409 {
                    errBody = "SimpleMovie \"" <> toUtf8Lazy (moviedb ^. simpleMovieTitle) <> "\" is already present in the database."
                }

entitySimpleMovieToMovie :: Entity SimpleMovie -> App Movie
entitySimpleMovieToMovie (Entity mid m) = Movie
    <$> pure (m ^. simpleMovieTitle)
    <*> getMovieFiles
    <*> pure (m ^. simpleMovieYear)
    <*> pure (m ^. simpleMovieCriticScore)
    <*> pure (m ^. simpleMovieAudienceScore)
    <*> pure (m ^. simpleMovieIMDbScore)
    <*> pure (m ^. simpleMovieMetacriticScore)
    <*> pure (m ^. simpleMovieSynopsis)
    <*> pure (m ^. simpleMovieRating)
    <*> pure (m ^. simpleMovieRuntime)
    <*> getDirectors
    <*> getWriters
    <*> getActors
    <*> getCountries
    <*> getLanguages
    <*> getGenres
    <*> pure (m ^. simpleMovieStudio)
    <*> pure (m ^. simpleMovieIMDbid)
    <*> pure (m ^. simpleMovieRtid)
    <*> pure (m ^. simpleMovieMcid)
    <*> pure (m ^. simpleMovieWikidataid)
    <*> pure (m ^. simpleMovieIdentificator)
    <*> getImages
  where
    getMovieFiles = mapM entitySimpleMovieFileToMovieFile =<< getEntitySimpleMovieFiles mid
    getDirectors = do
        ed <- runDB $
            E.select $
            E.from $ \(md, d) -> do
            E.where_
                (     md E.^. MovieDirectorMovie E.==. E.val mid
                E.&&. md E.^. MovieDirectorDirector E.==. d E.^. PersonId
                )
            E.orderBy [ E.asc (d E.^. PersonName) ]
            return d
        return $ map entityVal ed
    getWriters = do
        ew <- runDB $
            E.select $
            E.from $ \(mw, w) -> do
            E.where_
                (     mw E.^. MovieWriterMovie E.==. E.val mid
                E.&&. mw E.^. MovieWriterWriter E.==. w E.^. PersonId
                )
            E.orderBy [ E.asc (w E.^. PersonName) ]
            return w
        return $ map entityVal ew
    getActors = do
        ea <- runDB $
            E.select $
            E.from $ \(ma, a, p) -> do
            E.where_
                (     ma E.^. MovieActorMovie E.==. E.val mid
                E.&&. ma E.^. MovieActorActor E.==. a E.^. ActorDBId
                E.&&. a E.^. ActorDBPerson E.==. p E.^. PersonId
                )
            E.orderBy [ E.asc (p E.^. PersonName) ]
            return a
        mapM (actorDBToActor . entityVal) ea
    getCountries = do
        ec <- runDB $
            E.select $
            E.from $ \(mc, c) -> do
            E.where_
                (     mc E.^. MovieCountryMovie E.==. E.val mid
                E.&&. mc E.^. MovieCountryCountry E.==. c E.^. CountryId
                )
            E.orderBy [ E.asc (c E.^. CountryName) ]
            return c
        return $ map entityVal ec
    getLanguages = do
        el <- runDB $
            E.select $
            E.from $ \(ml, l) -> do
            E.where_
                (     ml E.^. MovieLanguageMovie E.==. E.val mid
                E.&&. ml E.^. MovieLanguageLanguage E.==. l E.^. LanguageId
                )
            E.orderBy [ E.asc (l E.^. LanguageName) ]
            return l
        return $ map entityVal el
    getGenres = do
        eg <- runDB $
            E.select $
            E.from $ \(mg, g) -> do
            E.where_
                (     mg E.^. MovieGenreMovie E.==. E.val mid
                E.&&. mg E.^. MovieGenreGenre E.==. g E.^. GenreId
                )
            E.orderBy [ E.asc (g E.^. GenreName) ]
            return g
        return $ map entityVal eg
    getImages = do
        ei <- runDB $
            E.select $
            E.from $ \(mm, i) -> do
            E.where_
                (     mm E.^. MovieImageMovie E.==. E.val mid
                E.&&. mm E.^. MovieImageImage E.==. i E.^. ImageDBId
                )
            E.orderBy [ E.asc (i E.^. ImageDBFile) ]
            return i
        return $ map (imageDBToImage . entityVal) ei

entitySimpleMovieFileToMovieFile :: Entity SimpleMovieFile -> App MovieFile
entitySimpleMovieFileToMovieFile (Entity mid m) = MovieFile
    <$> name'
    <*> pure format'
    <*> getVideos
    <*> getAudios
    <*> getSubtitles
    <*> pure duration'
    <*> pure size'
  where
    name' = do
        p <- fileWithBaseDirFromFilePath (toS $ m ^. simpleMovieFileName)
        return (toFilePath p)
    format' = m ^. simpleMovieFileFormat
    getVideos = do
        ev <- runDB $
            E.select $
            E.from $ \(m', v) -> do
            E.where_
                (     m' E.^. MovieFileMovieFileVideoFile E.==. E.val mid
                E.&&. m' E.^. MovieFileMovieFileVideoVideo E.==. v E.^. MovieFileVideoId
                )
            E.orderBy [ E.asc (v E.^. MovieFileVideoIndex) ]
            return v
        return $ map entityVal ev
    getAudios = do
        ea <- runDB $
            E.select $
            E.from $ \(m', a) -> do
            E.where_
                (     m' E.^. MovieFileMovieFileAudioFile E.==. E.val mid
                E.&&. m' E.^. MovieFileMovieFileAudioAudio E.==. a E.^. MovieFileAudioId
                )
            E.orderBy [ E.asc (a E.^. MovieFileAudioIndex) ]
            return a
        return $ map entityVal ea
    getSubtitles = do
        es <- runDB $
            E.select $
            E.from $ \(m', s) -> do
            E.where_
                (     m' E.^. MovieFileMovieFileSubtitleFile E.==. E.val mid
                E.&&. m' E.^. MovieFileMovieFileSubtitleSubtitle E.==. s E.^. MovieFileSubtitleId
                )
            E.orderBy [ E.asc (s E.^. MovieFileSubtitleIndex) ]
            return s
        return $ map entityVal es
    duration' = m ^. simpleMovieFileDuration
    size' = intToSize (m ^. simpleMovieFileSize)

actorDBToActor :: ActorDB -> App Actor
actorDBToActor a = Actor
    <$> getPerson (a ^. actorDBPerson)
    <*> pure roles'
  where
    getPerson pid = do
        mp <- runDB $ get pid
        case mp of
            Nothing -> throwM err404 { errBody = "Can't find person " <> toUtf8Lazy (show $ fromSqlKey pid :: Text) }
            Just p -> return p
    roles' = a ^. actorDBRoles

checkSeenMovie :: Text -> Int64 -> App Bool
checkSeenMovie username mid = do
    muser <- runDB $ getBy $ UniqueUserName username
    case muser of
        Nothing -> throwM err404 { errBody = "Can't find user " <> toUtf8Lazy username }
        Just (Entity userid _) -> do
            em <- runDB $ getBy (UniqueUserSeenMovie userid dbmid)
            case em of
                Nothing -> pure False
                Just _ -> pure True
  where
    dbmid = toSqlKey mid

seenMovie :: Text -> Int64 -> App NoContent
seenMovie username mid = do
    muser <- runDB $ getBy $ UniqueUserName username
    case muser of
        Nothing -> throwM err404 { errBody = "Can't find user " <> toUtf8Lazy username }
        Just (Entity userid _) -> do
            em <- runDB $ getBy (UniqueUserSeenMovie userid dbmid)
            case em of
                Nothing -> do
                    now <- liftIO getCurrentTime
                    _ <- runDB $ insert $ UserSeenMovie userid dbmid now
                    return NoContent
                Just _ -> do
                    m <- getSimpleMovie mid
                    throwM err409 { errBody = "Movie \"" <> toUtf8Lazy (m ^. simpleMovieTitle) <> "\" is already set as seen by user " <> toUtf8Lazy username <> "." }
  where
    dbmid = toSqlKey mid

unseenMovie :: Text -> Int64 -> App NoContent
unseenMovie username mid = do
    muser <- runDB $ getBy $ UniqueUserName username
    case muser of
        Nothing -> throwM err404 { errBody = "Can't find user " <> toUtf8Lazy username }
        Just (Entity userid _) -> do
            em <- runDB $ getBy (UniqueUserSeenMovie userid dbmid)
            case em of
                Nothing -> do
                    m <- getSimpleMovie mid
                    throwM err409 { errBody = "Movie \"" <> toUtf8Lazy (m ^. simpleMovieTitle) <> "\" is already set as not seen by user " <> toUtf8Lazy username <> "." }
                Just (Entity umid _) -> do
                    runDB $ delete umid
                    return NoContent
  where
    dbmid = toSqlKey mid

deleteMovieFile :: Int64 -> App NoContent
deleteMovieFile mid = do
    mm <- runDB $ get dbmid
    case mm of
        Nothing -> throwM err404 { errBody = "Could not find file " <> toUtf8Lazy (show mid :: Text) }
        Just _ -> do
            runDB $ deleteCascade dbmid
            return NoContent
  where
    dbmid :: SimpleMovieFileId
    dbmid = toSqlKey mid

putMovieMovieFile :: Int64 -> [MovieFile] -> App [Int64]
putMovieMovieFile mid moviefiles = do
    mmovie <- runDB $ get dbmid
    case mmovie of
        Nothing -> throwM err404 { errBody = "Can't find movie " <> toUtf8Lazy (show mid :: Text) }
        Just _ -> do
            _ <- mapM (deleteMovieFile . fromSqlKey . entityKey) =<< getEntitySimpleMovieFiles dbmid
            -- ^ delete old MovieFiles
            moviefileids <- mapM postMovieFiles moviefiles
            mfkeys <- runDB $ mapM ((insert . MovieMovieFile dbmid) . toSqlKey) moviefileids
            return $ map fromSqlKey mfkeys
  where
    dbmid = toSqlKey mid

putMovieMovieFileFromIMDbId :: Text -> [MovieFile] -> App [Int64]
putMovieMovieFileFromIMDbId imdbid moviefiles = do
    em <- getEntitySimpleMovieFromIMDbId imdbid
    putMovieMovieFile (fromSqlKey $ entityKey em) moviefiles

putMovieMovieFileFromFile :: FilePath -> [MovieFile] -> App [Int64]
putMovieMovieFileFromFile fp moviefiles = do
    em <- getEntitySimpleMovieFromFile (Just fp)
    putMovieMovieFile (fromSqlKey $ entityKey em) moviefiles

updateMovie :: Int64 -> Movie -> App NoContent
updateMovie mid m = do
    mmovie <- runDB $ get dbmid
    case mmovie of
        Nothing -> throwM err404 { errBody = "Can't find movie " <> toUtf8Lazy (show mid :: Text) }
        Just _ -> do
            let sm = SimpleMovie
                    (m ^. movieTitle)
                    (m ^. movieYear)
                    (m ^. movieCriticScore)
                    (m ^. movieAudienceScore)
                    (m ^. movieIMDbScore)
                    (m ^. movieMetacriticScore)
                    (m ^. movieSynopsis)
                    (m ^. movieRating)
                    (m ^. movieRuntime)
                    (m ^. movieStudio)
                    (m ^. movieIMDbid)
                    (m ^. movieRtid)
                    (m ^. movieMcid)
                    (m ^. movieWikidataid)
                    (m ^. movieIdentificator)
            runDB $ do
                deleteWhere [ MovieDirectorMovie ==. dbmid ]
                deleteWhere [ MovieWriterMovie ==. dbmid ]
                deleteWhere [ MovieActorMovie ==. dbmid ]
                deleteWhere [ MovieCountryMovie ==. dbmid ]
                deleteWhere [ MovieLanguageMovie ==. dbmid ]
                deleteWhere [ MovieGenreMovie ==. dbmid ]
                replace dbmid sm
            deleteImages dbmid
            _ <- putMovieMovieFile mid (m ^. movieFiles)
            -- ^ TODO: use another function to avoid deleting-adding
            -- movieFiles?
            _ <- insertDirectors dbmid (m ^. movieDirectors)
            _ <- insertWriters dbmid (m ^. movieWriters)
            _ <- insertActors dbmid (m ^. movieActors)
            _ <- insertCountries dbmid (m ^. movieCountries)
            _ <- insertLanguages dbmid (m ^. movieLanguages)
            _ <- insertGenres dbmid (m ^. movieGenres)
            _ <- insertImages dbmid (m ^. movieImages)
            return NoContent
  where
    dbmid :: SimpleMovieId
    dbmid = toSqlKey mid