summaryrefslogtreecommitdiff
path: root/src/Erebos/Conversation.hs
blob: 94d23993bc110c733f484ca2e363f49684eca20b (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
module Erebos.Conversation (
    Message,
    messageFrom,
    messageText,
    messageUnread,
    formatMessage,

    Conversation,
    directMessageConversation,
    reloadConversation,
    lookupConversations,

    conversationName,
    conversationPeer,
    conversationHistory,

    sendMessage,
) where

import Control.Monad.Except

import Data.List
import Data.Maybe
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time.LocalTime

import Erebos.Identity
import Erebos.Message hiding (formatMessage)
import Erebos.State
import Erebos.Storage


data Message = DirectMessageMessage DirectMessage Bool

messageFrom :: Message -> ComposedIdentity
messageFrom (DirectMessageMessage msg _) = msgFrom msg

messageText :: Message -> Maybe Text
messageText (DirectMessageMessage msg _) = Just $ msgText msg

messageUnread :: Message -> Bool
messageUnread (DirectMessageMessage _ unread) = unread

formatMessage :: TimeZone -> Message -> String
formatMessage tzone (DirectMessageMessage msg _) = formatDirectMessage tzone msg


data Conversation = DirectMessageConversation DirectMessageThread

directMessageConversation :: MonadHead LocalState m => ComposedIdentity -> m Conversation
directMessageConversation peer = do
    (find (sameIdentity peer . msgPeer) . toThreadList . lookupSharedValue . lsShared . fromStored <$> getLocalHead) >>= \case
        Just thread -> return $ DirectMessageConversation thread
        Nothing -> return $ DirectMessageConversation $ DirectMessageThread peer [] [] []

reloadConversation :: MonadHead LocalState m => Conversation -> m Conversation
reloadConversation (DirectMessageConversation thread) = directMessageConversation (msgPeer thread)

lookupConversations :: MonadHead LocalState m => m [Conversation]
lookupConversations = map DirectMessageConversation . toThreadList . lookupSharedValue . lsShared . fromStored <$> getLocalHead


conversationName :: Conversation -> Text
conversationName (DirectMessageConversation thread) = fromMaybe (T.pack "<unnamed>") $ idName $ msgPeer thread

conversationPeer :: Conversation -> Maybe ComposedIdentity
conversationPeer (DirectMessageConversation thread) = Just $ msgPeer thread

conversationHistory :: Conversation -> [Message]
conversationHistory (DirectMessageConversation thread) = map (\msg -> DirectMessageMessage msg False) $ threadToList thread


sendMessage :: (MonadHead LocalState m, MonadError String m) => Conversation -> Text -> m Message
sendMessage (DirectMessageConversation thread) text = DirectMessageMessage <$> (fromStored <$> sendDirectMessage (msgPeer thread) text) <*> pure False