summaryrefslogtreecommitdiff
path: root/src/Message.hs
blob: 8eaf7f12740c543f41aea42da3dd30d7b4014960 (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
module Message (
    DirectMessage(..), DirectMessageThread(..),
    emptyDirectThread, createDirectMessage,
    threadToList,
) where

import Data.List
import Data.Ord
import Data.Text (Text)
import Data.Time.LocalTime

import Identity
import Storage

data DirectMessage = DirectMessage
    { msgFrom :: Stored Identity
    , msgPrev :: [Stored DirectMessage]
    , msgTime :: ZonedTime
    , msgText :: Text
    }

data DirectMessageThread = DirectMessageThread
    { msgPeer :: Stored Identity
    , msgHead :: [Stored DirectMessage]
    , msgSeen :: [Stored DirectMessage]
    }

instance Storable DirectMessage where
    store' msg = storeRec $ do
        storeRef "from" $ msgFrom msg
        mapM_ (storeRef "prev") $ msgPrev msg
        storeDate "time" $ msgTime msg
        storeText "text" $ msgText msg

    load' = loadRec $ DirectMessage
        <$> loadRef "from"
        <*> loadRefs "prev"
        <*> loadDate "time"
        <*> loadText "text"

instance Storable DirectMessageThread where
    store' msg = storeRec $ do
        storeRef "peer" $ msgPeer msg
        mapM_ (storeRef "head") $ msgHead msg
        mapM_ (storeRef "seen") $ msgSeen msg

    load' = loadRec $ DirectMessageThread
        <$> loadRef "peer"
        <*> loadRefs "head"
        <*> loadRefs "seen"


emptyDirectThread :: Stored Identity -> DirectMessageThread
emptyDirectThread peer = DirectMessageThread peer [] []

createDirectMessage :: Stored Identity -> DirectMessageThread -> Text -> IO (Stored DirectMessage, Stored DirectMessageThread)
createDirectMessage self thread msg = do
    let st = storedStorage self
    time <- getZonedTime
    smsg <- wrappedStore st DirectMessage
        { msgFrom = finalOwner self
        , msgPrev = msgHead thread
        , msgTime = time
        , msgText = msg
        }
    sthread <- wrappedStore st thread
        { msgHead = [smsg]
        , msgSeen = [smsg]
        }
    return (smsg, sthread)

threadToList :: DirectMessageThread -> [DirectMessage]
threadToList thread = helper $ msgHead thread
    where helper msgs | msg : msgs' <- sortBy (comparing cmpView) msgs =
              fromStored msg : helper (dropWhile (== msg) msgs')
                      | otherwise = []
          cmpView msg = (zonedTimeToUTC $ msgTime $ fromStored msg, storedRef msg)