mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-23 00:18:27 +00:00
* core, ui: chatItemUpdated event has the previous item Apps change counters by the difference between the previous and the new item, and insert an updated item only when the update created it. * core, ui: a recreated item is sent as newChatItems An update of a locally deleted message creates it again and sends it as a new item, so chatItemUpdated always has the previous item and the apps never insert on an update. * core, ui: previous item is optional and has no chat info Events from older remote hosts decode without it; the apps then insert the item if it is not loaded and change no counters. * core: catch-up subscriber gets an edited history post as a new item * ui: updates in another profile do not notify, as on iOS * core, ui: one type for the updated item and its previous version AChatItemUpdate has the chat info, the new item and the previous item with the same chat type and direction. Its JSON is the JSON of AChatItem with an optional prevChatItem; the event keeps the key chatItem. * core: tested event key, previous item reactions, cleared mentions One function renames the event field to chatItem for JSON and docs, and the test checks the wire key and compatibility with AChatItem. The previous item of a direct edit has its reactions. An edit that removes all mentions sends the item without them. * core: test that an edit removing mentions sends the item without them * core: event JSON field mapping inline in the TH options, for the Windows build * core: file chat item update checked in one store transaction * core: test that a file reset by unknown relays sends its previous item * core, ui: chatItemUpdated event key chatItemUpdate * core, ui: chatItemUpdated always has the previous item * ci: mcp scope tests the plugin with its published dependencies * core: mention of the user follows edits of a group message * core: previous item of a prohibited file is read before the prohibition * android, desktop: missed call check inline, counter test with core pairs * ios: spec link of the chatItemUpdated event * core: mention edits in support chats update members requiring attention * core: one rule for the mention of the user in received and edited items * core: record item events of updates for app tests * android, desktop: remove the missed call notification of updates, never shown * android, desktop: test item updates on events recorded by the core * ios: test item updates on events recorded by the core * docs: plan of app tests of item updates, recording tests in the CI guide * core: record the response to an update after its item status is final * ios: notification manager replaceable in tests * ios: test notifications of updates and the update response * android, desktop: test the recorded update response * docs: plan with iOS notifications and the update response * core: recorded response to an update of a sent message
3553 lines
205 KiB
Haskell
3553 lines
205 KiB
Haskell
{-# LANGUAGE BangPatterns #-}
|
|
{-# LANGUAGE DataKinds #-}
|
|
{-# LANGUAGE DuplicateRecordFields #-}
|
|
{-# LANGUAGE FlexibleContexts #-}
|
|
{-# LANGUAGE GADTs #-}
|
|
{-# LANGUAGE KindSignatures #-}
|
|
{-# LANGUAGE LambdaCase #-}
|
|
{-# LANGUAGE MultiWayIf #-}
|
|
{-# LANGUAGE NamedFieldPuns #-}
|
|
{-# LANGUAGE OverloadedLists #-}
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
{-# LANGUAGE PatternSynonyms #-}
|
|
{-# LANGUAGE RankNTypes #-}
|
|
{-# LANGUAGE ScopedTypeVariables #-}
|
|
{-# LANGUAGE TupleSections #-}
|
|
{-# LANGUAGE TypeApplications #-}
|
|
{-# OPTIONS_GHC -fno-warn-ambiguous-fields #-}
|
|
|
|
module Simplex.Chat.Library.Internal where
|
|
|
|
import qualified Codec.Compression.Zstd as Z1
|
|
import Control.Applicative ((<|>))
|
|
import Control.Concurrent.STM (retry)
|
|
import Control.Logger.Simple
|
|
import Control.Monad
|
|
import Control.Monad.Except
|
|
import Control.Monad.IO.Unlift
|
|
import Control.Monad.Reader
|
|
import Crypto.Random (ChaChaDRG)
|
|
import qualified Data.Aeson as J
|
|
import Data.Bifunctor (first)
|
|
import Data.ByteString.Char8 (ByteString)
|
|
import qualified Data.ByteString.Char8 as B
|
|
import qualified Data.ByteString.Lazy.Char8 as LB
|
|
import Data.Char (isDigit)
|
|
import Data.Containers.ListUtils (nubOrd)
|
|
import Data.Either (partitionEithers, rights)
|
|
import Data.Fixed (div')
|
|
import Data.Foldable (foldr')
|
|
import Data.Functor (($>))
|
|
import Data.Functor.Identity
|
|
import Data.Int (Int64)
|
|
import Data.List (foldl', mapAccumL, partition)
|
|
import Data.List.NonEmpty (NonEmpty (..), (<|))
|
|
import qualified Data.List.NonEmpty as L
|
|
import Data.Map.Strict (Map)
|
|
import qualified Data.Map.Strict as M
|
|
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe)
|
|
import qualified Data.Set as S
|
|
import Data.Text (Text)
|
|
import qualified Data.Text as T
|
|
import Data.Text.Encoding (encodeUtf8)
|
|
import Data.Time (addUTCTime)
|
|
import Data.Time.Calendar (fromGregorian)
|
|
import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime, nominalDiffTimeToSeconds, secondsToDiffTime)
|
|
import Simplex.Chat.Badges (BadgeCredential (..), BadgeInfo (..), ProofPresHeader (..), BadgeProof (..), BadgeProofKind (..), BadgeStatus (..), FileSizeLimits (..), LocalBadge (..), acceptedProof, badgeSndGraceInterval, generateBadgeProof, localBadgeStatus, maxXFTPFileSize, mkBadgeStatus, verifyBadge)
|
|
import Simplex.Chat.Names (SimplexDomainClaim (..), claimDomain)
|
|
import Simplex.Chat.Call
|
|
import Simplex.Chat.Controller
|
|
import Simplex.Chat.Files
|
|
import Simplex.Chat.Markdown
|
|
import Simplex.Chat.Messages
|
|
import Simplex.Chat.Messages.Batch (BatchMode (..), MsgBatch (..), batchElements, batchMessages, encodeBatchElement, encodeBinaryBatch, encodeFwdElement)
|
|
import Simplex.Chat.Messages.CIContent
|
|
import Simplex.Chat.Messages.CIContent.Events
|
|
import Simplex.Chat.Operators
|
|
import Simplex.Chat.ProfileGenerator (generateRandomProfile)
|
|
import Simplex.Chat.Protocol
|
|
import Simplex.Chat.Store
|
|
import Simplex.Chat.Store.ContactRequest
|
|
import Simplex.Chat.Store.Direct
|
|
import Simplex.Chat.Store.Files
|
|
import Simplex.Chat.Store.Groups
|
|
import Simplex.Chat.Store.Messages
|
|
import Simplex.Chat.Store.Profiles
|
|
import Simplex.Chat.Store.Shared
|
|
import Simplex.Chat.Types
|
|
import Simplex.Chat.Types.MemberRelations
|
|
import Simplex.Chat.Types.Preferences
|
|
import Simplex.Chat.Types.Shared
|
|
import Simplex.Chat.Types.UITheme (ChatLayout)
|
|
import Simplex.Chat.Util (encryptFile, shuffle)
|
|
import Simplex.FileTransfer.Description (FileDescriptionURI (..), ValidFileDescription)
|
|
import qualified Simplex.FileTransfer.Description as FD
|
|
import qualified Simplex.Messaging.Crypto.Lazy as LC
|
|
import Simplex.FileTransfer.Protocol (FileParty (..), FilePartyI)
|
|
import Simplex.FileTransfer.Types (RcvFileId, SndFileId)
|
|
import Simplex.Messaging.Agent
|
|
import Simplex.Messaging.Agent.Client (getFastNetworkConfig, ipAddressProtected, withLockMap)
|
|
import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), ServerCfg (..))
|
|
import Simplex.Messaging.Agent.Lock (withLock)
|
|
import Simplex.Messaging.Agent.Protocol
|
|
import qualified Simplex.Messaging.Agent.Protocol as AP (AgentErrorType (..))
|
|
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
|
import Simplex.Messaging.Client (NetworkConfig (..), NetworkRequestMode (..))
|
|
import Simplex.Messaging.Compression (compressionLevel, limitDecompress')
|
|
import qualified Simplex.Messaging.Crypto as C
|
|
import Simplex.Messaging.Crypto.File (CryptoFile (..), CryptoFileArgs (..))
|
|
import qualified Simplex.Messaging.Crypto.File as CF
|
|
import Simplex.Messaging.Crypto.Ratchet (PQEncryption (..), PQSupport (..), pattern PQEncOff, pattern PQEncOn, pattern PQSupportOff, pattern PQSupportOn)
|
|
import qualified Simplex.Messaging.Crypto.Ratchet as CR
|
|
import Simplex.Messaging.Crypto.BBS (BBSPresHeader (..))
|
|
import Simplex.Messaging.Encoding (smpDecode, smpEncode)
|
|
import Simplex.Messaging.Encoding.String
|
|
import Simplex.Messaging.Protocol (MsgBody, MsgFlags (..), ProtoServerWithAuth (..), ProtocolServer, ProtocolTypeI (..), SProtocolType (..), SubscriptionMode (..), UserProtocol, XFTPServer)
|
|
import qualified Simplex.Messaging.Protocol as SMP
|
|
import qualified Simplex.Messaging.TMap as TM
|
|
import Simplex.Messaging.Util
|
|
import Simplex.Messaging.Version
|
|
import System.FilePath (takeFileName, (</>))
|
|
import System.IO (Handle, IOMode (..), hFlush)
|
|
import UnliftIO.Concurrent (forkFinally, mkWeakThreadId)
|
|
import UnliftIO.Directory
|
|
import UnliftIO.IO (hClose, openFile)
|
|
import UnliftIO.STM
|
|
|
|
maxMsgReactions :: Int
|
|
maxMsgReactions = 3
|
|
|
|
maxRcvMentions :: Int
|
|
maxRcvMentions = 5
|
|
|
|
maxSndMentions :: Int
|
|
maxSndMentions = 3
|
|
|
|
withChatLock :: Text -> CM a -> CM a
|
|
withChatLock name action = asks chatLock >>= \l -> withLock l name action
|
|
|
|
withEntityLock :: Text -> ChatLockEntity -> CM a -> CM a
|
|
withEntityLock name entity action = do
|
|
chatLock <- asks chatLock
|
|
ls <- asks entityLocks
|
|
atomically $ unlessM (isEmptyTMVar chatLock) retry
|
|
withLockMap ls entity name action
|
|
|
|
withInvitationLock :: Text -> ByteString -> CM a -> CM a
|
|
withInvitationLock name = withEntityLock name . CLInvitation
|
|
{-# INLINE withInvitationLock #-}
|
|
|
|
withConnectionLock :: Text -> Int64 -> CM a -> CM a
|
|
withConnectionLock name = withEntityLock name . CLConnection
|
|
{-# INLINE withConnectionLock #-}
|
|
|
|
withContactLock :: Text -> ContactId -> CM a -> CM a
|
|
withContactLock name = withEntityLock name . CLContact
|
|
{-# INLINE withContactLock #-}
|
|
|
|
withGroupLock :: Text -> GroupId -> CM a -> CM a
|
|
withGroupLock name = withEntityLock name . CLGroup
|
|
{-# INLINE withGroupLock #-}
|
|
|
|
withUserContactLock :: Text -> Int64 -> CM a -> CM a
|
|
withUserContactLock name = withEntityLock name . CLUserContact
|
|
{-# INLINE withUserContactLock #-}
|
|
|
|
withContactRequestLock :: Text -> Int64 -> CM a -> CM a
|
|
withContactRequestLock name = withEntityLock name . CLContactRequest
|
|
{-# INLINE withContactRequestLock #-}
|
|
|
|
withFileLock :: Text -> Int64 -> CM a -> CM a
|
|
withFileLock name = withEntityLock name . CLFile
|
|
{-# INLINE withFileLock #-}
|
|
|
|
withUserProfileLock :: Text -> CM a -> CM a
|
|
withUserProfileLock name = withEntityLock name CLUserProfile
|
|
{-# INLINE withUserProfileLock #-}
|
|
|
|
useServerCfgs :: forall p. UserProtocol p => SProtocolType p -> RandomAgentServers -> [(Text, ServerOperator)] -> [UserServer p] -> NonEmpty (ServerCfg p)
|
|
useServerCfgs p RandomAgentServers {smpServers, xftpServers} opDomains =
|
|
fromMaybe (rndAgentServers p) . L.nonEmpty . agentServerCfgs p opDomains
|
|
where
|
|
rndAgentServers :: SProtocolType p -> NonEmpty (ServerCfg p)
|
|
rndAgentServers = \case
|
|
SPSMP -> smpServers
|
|
SPXFTP -> xftpServers
|
|
|
|
contactCITimed :: Contact -> CM (Maybe CITimed)
|
|
contactCITimed ct = sndContactCITimed False ct Nothing
|
|
|
|
sndContactCITimed :: Bool -> Contact -> Maybe Int -> CM (Maybe CITimed)
|
|
sndContactCITimed live = sndCITimed_ live . contactTimedTTL
|
|
|
|
sndGroupCITimed :: Bool -> GroupInfo -> Maybe Int -> CM (Maybe CITimed)
|
|
sndGroupCITimed live = sndCITimed_ live . groupTimedTTL
|
|
|
|
sndCITimed_ :: Bool -> Maybe (Maybe Int) -> Maybe Int -> CM (Maybe CITimed)
|
|
sndCITimed_ live chatTTL itemTTL =
|
|
forM (chatTTL >>= (itemTTL <|>)) $ \ttl ->
|
|
CITimed ttl
|
|
<$> if live
|
|
then pure Nothing
|
|
else Just . addUTCTime (realToFrac ttl) <$> liftIO getCurrentTime
|
|
|
|
callTimed :: Contact -> ACIContent -> CM (Maybe CITimed)
|
|
callTimed ct aciContent =
|
|
case aciContentCallStatus aciContent of
|
|
Just callStatus
|
|
| callComplete callStatus -> do
|
|
contactCITimed ct
|
|
_ -> pure Nothing
|
|
where
|
|
aciContentCallStatus :: ACIContent -> Maybe CICallStatus
|
|
aciContentCallStatus (ACIContent _ (CISndCall st _)) = Just st
|
|
aciContentCallStatus (ACIContent _ (CIRcvCall st _)) = Just st
|
|
aciContentCallStatus _ = Nothing
|
|
|
|
toggleNtf :: GroupMember -> Bool -> CM ()
|
|
toggleNtf m ntfOn =
|
|
when (memberActive m) $
|
|
forM_ (memberConnId m) $ \connId ->
|
|
withAgent (\a -> toggleConnectionNtfs a connId ntfOn) `catchAllErrors` eToView
|
|
|
|
prepareGroupMsg :: DB.Connection -> User -> GroupInfo -> Maybe MsgScope -> ShowGroupAsSender -> MsgContent -> Map MemberName MsgMention -> Maybe ChatItemId -> Maybe CIForwardedFrom -> Maybe FileInvitation -> Maybe CITimed -> Bool -> ExceptT StoreError IO (ChatMsgEvent 'Json, Maybe (CIQuote 'CTGroup))
|
|
prepareGroupMsg db user g@GroupInfo {membership} msgScope showGroupAsSender mc mentions quotedItemId_ itemForwarded fInv_ timed_ live = do
|
|
(mc', quotedItem_) <- case (quotedItemId_, itemForwarded) of
|
|
(Nothing, Nothing) -> pure (mcSimple mc, Nothing)
|
|
(Nothing, Just ciff) -> do
|
|
fl_ <- liftIO $ ciffForwardLink db ciff
|
|
pure (mcForward fl_ mc, Nothing)
|
|
(Just quotedItemId, Nothing) -> do
|
|
CChatItem _ qci@ChatItem {meta = CIMeta {itemTs, itemSharedMsgId}, mentions = quoteMentions, file} <-
|
|
getGroupCIWithReactions db user g quotedItemId
|
|
(origQmc, qd, sent, member_) <- quoteData qci membership
|
|
let msgRef = MsgRef {msgId = itemSharedMsgId, sentAt = itemTs, sent, memberId = memberId' <$> member_}
|
|
qmc = quoteContent mc origQmc file
|
|
ParsedMarkdown formattedText markdownBlocks = parsedMsgContent qmc
|
|
(qmc', ft', _) = updatedMentionNames qmc formattedText quoteMentions
|
|
quotedItem = CIQuote {chatDir = qd, itemId = Just quotedItemId, sharedMsgId = itemSharedMsgId, sentAt = itemTs, content = qmc', formattedText = ft', markdownBlocks}
|
|
pure (mcQuote QuotedMsg {msgRef, content = qmc'} mc, Just quotedItem)
|
|
(Just _, Just _) -> throwError SEInvalidQuote
|
|
let mc'' = mc' {mentions = MsgMentions mentions, file = fInv_, ttl = ttl' <$> timed_, live = justTrue live, scope = msgScope, asGroup = justTrue showGroupAsSender}
|
|
pure (XMsgNew mc'', quotedItem_)
|
|
where
|
|
quoteData :: ChatItem c d -> GroupMember -> ExceptT StoreError IO (MsgContent, CIQDirection 'CTGroup, Bool, Maybe GroupMember)
|
|
quoteData ChatItem {meta = CIMeta {itemDeleted = Just _}} _ = throwError SEInvalidQuote
|
|
quoteData ChatItem {chatDir = CIGroupSnd, content = CISndMsgContent qmc, meta = CIMeta {showGroupAsSender = sentAsGroup}} membership'
|
|
| sentAsGroup = pure (qmc, CIQGroupSnd, True, Nothing)
|
|
| otherwise = pure (qmc, CIQGroupSnd, True, Just membership')
|
|
quoteData ChatItem {chatDir = CIGroupRcv m, content = CIRcvMsgContent qmc} _ = pure (qmc, CIQGroupRcv $ Just m, False, Just m)
|
|
quoteData ChatItem {chatDir = CIChannelRcv, content = CIRcvMsgContent qmc} _ = pure (qmc, CIQGroupRcv Nothing, False, Nothing)
|
|
quoteData _ _ = throwError SEInvalidQuote
|
|
|
|
-- re-forwarded message is attributed to the original source
|
|
ciffForwardLink :: DB.Connection -> CIForwardedFrom -> IO (Maybe ForwardLink)
|
|
ciffForwardLink db = \case
|
|
CIFFGroup {groupId = Just gId, memberId, sharedMsgId_ = Just msgId} ->
|
|
getGroupProfileById db gId >>= \case
|
|
Just GroupProfile {displayName, publicGroup = Just PublicGroupProfile {groupLink, publicGroupId}} ->
|
|
pure $ Just ForwardLink {displayName, groupLink, publicGroupId, memberId, msgId}
|
|
_ -> pure Nothing
|
|
CIFFGroupLink {chatName, groupLink, publicGroupId, memberId, sharedMsgId} ->
|
|
pure $ Just ForwardLink {displayName = chatName, groupLink, publicGroupId, memberId, msgId = sharedMsgId}
|
|
_ -> pure Nothing
|
|
|
|
rcvForwardedFrom :: DB.Connection -> User -> ChatDirection c 'MDRcv -> RcvMessage -> IO (Maybe CIForwardedFrom)
|
|
rcvForwardedFrom db user chatDirection RcvMessage {chatMsgEvent} = case chatMsgEvent of
|
|
ACME _ (XMsgNew MsgContainer {forward = Just True, forwardLink}) -> case forwardLink of
|
|
Nothing -> pure $ Just CIFFUnknown
|
|
Just fl@ForwardLink {displayName}
|
|
| linkAllowed -> Just <$> forwardLinkCIFF db user fl
|
|
| otherwise -> pure $ Just $ CIFFGroup displayName MDRcv Nothing Nothing Nothing Nothing Nothing
|
|
_ -> pure Nothing
|
|
where
|
|
linkAllowed = case chatDirection of
|
|
CDGroupRcv gInfo _ GroupMember {memberRole} -> allowed memberRole gInfo
|
|
CDChannelRcv gInfo _ -> allowed GROwner gInfo
|
|
_ -> True
|
|
where
|
|
allowed role = groupFeatureMemberAllowed' SGFSimplexLinks role . fullGroupPreferences
|
|
|
|
forwardLinkCIFF :: DB.Connection -> User -> ForwardLink -> IO CIForwardedFrom
|
|
forwardLinkCIFF db user ForwardLink {displayName, groupLink, publicGroupId, memberId, msgId} =
|
|
getGroupViaPublicGroupId db user publicGroupId >>= \case
|
|
Just (gId, Just storedLink)
|
|
| sameShortLinkContact groupLink storedLink -> do
|
|
ciId_ <- itemId_ gId
|
|
pure $ CIFFGroup displayName MDRcv (Just gId) ciId_ memberId (Just msgId) linkGroupType
|
|
_ -> pure $ CIFFGroupLink displayName MDRcv groupLink publicGroupId memberId msgId linkGroupType
|
|
where
|
|
linkGroupType = case groupLink of
|
|
CSLContact _ CCTChannel _ _ -> Just GTChannel
|
|
CSLContact _ CCTGroup _ _ -> Just GTGroup
|
|
_ -> Nothing
|
|
itemId_ gId = case memberId of
|
|
Nothing -> getGroupChatItemBySharedMsgId_ db user gId Nothing msgId
|
|
Just mId ->
|
|
getGroupMemberViaMemberId_ db user gId mId >>= \case
|
|
Just (gmId, category) ->
|
|
let scope = if category == GCUserMember then Nothing else Just gmId
|
|
in getGroupChatItemBySharedMsgId_ db user gId scope msgId
|
|
Nothing -> pure Nothing
|
|
|
|
updatedMentionNames :: MsgContent -> Maybe MarkdownList -> Map MemberName CIMention -> (MsgContent, Maybe MarkdownList, Map MemberName CIMention)
|
|
updatedMentionNames mc ft_ mentions = case ft_ of
|
|
Just ft
|
|
| not (null ft) && not (null mentions) && not (all sameName $ M.assocs mentions) ->
|
|
let (mentions', ft') = mapAccumL update M.empty ft
|
|
text = T.concat $ map markdownText ft'
|
|
in (mc {text} :: MsgContent, Just ft', mentions')
|
|
_ -> (mc, ft_, mentions)
|
|
where
|
|
sameName (name, CIMention {memberRef}) = case memberRef of
|
|
Just CIMentionMember {displayName} -> case T.stripPrefix displayName name of
|
|
Just rest
|
|
| T.null rest -> True
|
|
| otherwise -> case T.uncons rest of
|
|
Just ('_', suffix) -> T.all isDigit suffix
|
|
_ -> False
|
|
Nothing -> False
|
|
Nothing -> True
|
|
update mentions' ft@(FormattedText f _) = case f of
|
|
Just (Mention name) -> case M.lookup name mentions of
|
|
Just mm@CIMention {memberRef} ->
|
|
let name' = uniqueMentionName 0 $ case memberRef of
|
|
Just CIMentionMember {displayName} -> displayName
|
|
Nothing -> name
|
|
in (M.insert name' mm mentions', FormattedText (Just $ Mention name') ('@' `T.cons` viewName name'))
|
|
Nothing -> (mentions', ft)
|
|
_ -> (mentions', ft)
|
|
where
|
|
uniqueMentionName :: Int -> Text -> Text
|
|
uniqueMentionName pfx name =
|
|
let prefixed = if pfx == 0 then name else (name `T.snoc` '_') <> tshow pfx
|
|
in if prefixed `M.member` mentions' then uniqueMentionName (pfx + 1) name else prefixed
|
|
|
|
getCIMentions :: DB.Connection -> User -> GroupInfo -> Maybe MarkdownList -> Map MemberName GroupMemberId -> ExceptT StoreError IO (Map MemberName CIMention)
|
|
getCIMentions db user GroupInfo {groupId} ft_ mentions = case ft_ of
|
|
Just ft | not (null ft) && not (null mentions) -> do
|
|
let msgMentions = S.fromList $ mentionedNames ft
|
|
n = M.size mentions
|
|
-- prevent "invisible" and repeated-with-different-name mentions (when the same member is mentioned via another name)
|
|
unless (n <= maxSndMentions && all (`S.member` msgMentions) (M.keys mentions) && S.size (S.fromList $ M.elems mentions) == n) $
|
|
throwError SEInvalidMention
|
|
mapM (getMentionedGroupMember db user groupId) mentions
|
|
_ -> pure M.empty
|
|
|
|
getRcvCIMentions :: DB.Connection -> User -> GroupInfo -> Maybe MarkdownList -> Map MemberName MsgMention -> IO (Map MemberName CIMention)
|
|
getRcvCIMentions db user GroupInfo {groupId} ft_ mentions = case ft_ of
|
|
Just ft
|
|
| not (null ft) && not (null mentions) ->
|
|
let mentions' = uniqueMsgMentions maxRcvMentions mentions $ mentionedNames ft
|
|
in mapM (getMentionedMemberByMemberId db user groupId) mentions'
|
|
_ -> pure M.empty
|
|
|
|
-- prevent "invisible" and repeated-with-different-name mentions
|
|
uniqueMsgMentions :: Int -> Map MemberName MsgMention -> [ContactName] -> Map MemberName MsgMention
|
|
uniqueMsgMentions maxMentions mentions = go M.empty S.empty 0
|
|
where
|
|
go acc _ _ [] = acc
|
|
go acc seen n (name : rest)
|
|
| n >= maxMentions = acc
|
|
| otherwise = case M.lookup name mentions of
|
|
Just mm@MsgMention {memberId}
|
|
| S.notMember memberId seen ->
|
|
go (M.insert name mm acc) (S.insert memberId seen) (n + 1) rest
|
|
_ -> go acc seen n rest
|
|
|
|
getMessageMentions :: DB.Connection -> User -> GroupId -> Text -> IO (Map MemberName GroupMemberId)
|
|
getMessageMentions db user gId msg = case parseMaybeMarkdownList msg of
|
|
Just ft | not (null ft) -> M.fromList . catMaybes <$> mapM get (nubOrd $ mentionedNames ft)
|
|
_ -> pure M.empty
|
|
where
|
|
get name =
|
|
fmap (name,) . eitherToMaybe
|
|
<$> runExceptT (getGroupMemberIdByName db user gId name)
|
|
|
|
msgContentTexts :: MsgContent -> (Text, ParsedMarkdown)
|
|
msgContentTexts mc = (msgContentText mc, parsedMsgContent mc)
|
|
|
|
ciContentTexts :: CIContent d -> (Text, ParsedMarkdown)
|
|
ciContentTexts content = let t = ciContentToText content in (t, parsedCIContent content t)
|
|
|
|
quoteContent :: forall d. MsgContent -> MsgContent -> Maybe (CIFile d) -> MsgContent
|
|
quoteContent mc qmc ciFile_
|
|
| replaceContent = MCText qTextOrFile
|
|
| otherwise = case qmc of
|
|
MCImage _ image -> MCImage qTextOrFile image
|
|
MCFile _ -> MCFile qTextOrFile
|
|
-- consider same for voice messages
|
|
-- MCVoice _ voice -> MCVoice qTextOrFile voice
|
|
_ -> qmc
|
|
where
|
|
-- if the message we're quoting with is one of the "large" MsgContents
|
|
-- we replace the quote's content with MCText
|
|
replaceContent = case mc of
|
|
MCText _ -> False
|
|
MCFile _ -> False
|
|
MCLink {} -> True
|
|
MCImage {} -> True
|
|
MCVideo {} -> True
|
|
MCVoice {} -> False
|
|
MCReport {} -> False
|
|
MCChat {} -> True
|
|
MCUnknown {} -> True
|
|
qText = msgContentText qmc
|
|
getFileName :: CIFile d -> String
|
|
getFileName CIFile {fileName} = fileName
|
|
qFileName = maybe qText (T.pack . getFileName) ciFile_
|
|
qTextOrFile = if T.null qText then qFileName else qText
|
|
|
|
prohibitedGroupContent :: GroupInfo -> GroupMember -> Maybe GroupChatScopeInfo -> MsgContent -> Maybe MarkdownList -> Maybe f -> Bool -> Maybe GroupFeature
|
|
prohibitedGroupContent gInfo@GroupInfo {membership = mem@GroupMember {memberRole = userRole}} m scopeInfo mc ft file_ sent
|
|
| not supportAllowed = Just GFSupport
|
|
| isVoice mc && not (groupFeatureMemberAllowed SGFVoice m gInfo) && not hostApprovalVoice = Just GFVoice
|
|
| isNothing scopeInfo && not (isVoice mc) && (isJust file_ || isMedia mc) && not (groupFeatureMemberAllowed SGFFiles m gInfo) = Just GFFiles
|
|
| isNothing scopeInfo && isReport mc && (badReportUser || not (groupFeatureAllowed SGFReports gInfo)) = Just GFReports
|
|
| isNothing scopeInfo && prohibitedSimplexLinks gInfo m mc ft = Just GFSimplexLinks
|
|
| otherwise = Nothing
|
|
where
|
|
supportAllowed = case scopeInfo of
|
|
Just (GCSIMemberSupport scopeMem_) ->
|
|
groupFeatureAllowed SGFSupport gInfo || isJust (supportChat $ fromMaybe mem scopeMem_)
|
|
Nothing -> True
|
|
hostApprovalVoice
|
|
| sent = userRole >= GRAdmin && sendApprovalPhase
|
|
| otherwise = memberCategory m == GCHostMember && hostApprovalPhase
|
|
hostApprovalPhase = case scopeInfo of
|
|
Just (GCSIMemberSupport Nothing) -> memberStatus mem == GSMemPendingApproval
|
|
_ -> False
|
|
sendApprovalPhase = case scopeInfo of
|
|
Just (GCSIMemberSupport (Just scopeMem)) -> memberStatus scopeMem == GSMemPendingApproval
|
|
_ -> False
|
|
-- admins cannot send reports, non-admins cannot receive reports
|
|
badReportUser
|
|
| sent = userRole >= GRModerator
|
|
| otherwise = userRole < GRModerator
|
|
|
|
prohibitedSimplexLinks :: GroupInfo -> GroupMember -> MsgContent -> Maybe MarkdownList -> Bool
|
|
prohibitedSimplexLinks gInfo m mc ft =
|
|
not (groupFeatureMemberAllowed SGFSimplexLinks m gInfo)
|
|
&& (isChatLink mc || maybe False (any ftIsSimplexLink) ft || hasObfuscatedSimplexLink (msgContentText mc))
|
|
where
|
|
isChatLink = \case
|
|
MCChat {} -> True
|
|
_ -> False
|
|
|
|
ftIsSimplexLink :: FormattedText -> Bool
|
|
ftIsSimplexLink FormattedText {format} = maybe False isSimplexLink format
|
|
|
|
roundedFDCount :: Int -> Int
|
|
roundedFDCount n
|
|
| n <= 0 = 4
|
|
| otherwise = max 4 $ fromIntegral $ (2 :: Integer) ^ (ceiling (logBase 2 (fromIntegral n) :: Double) :: Integer)
|
|
|
|
xftpSndFileTransfer_ :: User -> CryptoFile -> Integer -> Int -> Maybe ContactOrGroup -> Maybe ByteString -> CM (FileInvitation, CIFile 'MDSnd, FileTransferMeta)
|
|
xftpSndFileTransfer_ user file@(CryptoFile filePath cfArgs) fileSize n contactOrGroup_ binding_ = do
|
|
fileBadge <- pure binding_ $>>= \chatBinding -> sndBadgeProof user PHFileInv {chatBinding, fileSize = fromInteger fileSize}
|
|
let fileName = takeFileName filePath
|
|
fInv = (xftpFileInvitation fileName fileSize dummyFileDescr :: FileInvitation) {fileBadge}
|
|
fsFilePath <- lift $ toFSFilePath filePath
|
|
let srcFile = CryptoFile fsFilePath cfArgs
|
|
aFileId <- withAgent $ \a -> xftpPrepareSendFile a (aUserId user) srcFile (roundedFDCount n) Nothing
|
|
-- TODO CRSndFileStart event for XFTP
|
|
chSize <- asks $ fileChunkSize . config
|
|
ft@FileTransferMeta {fileId} <- withStore' $ \db -> createSndFileTransferXFTP db user contactOrGroup_ file fInv (AgentSndFileId aFileId) Nothing chSize
|
|
withAgent (`xftpStartSendFile` aFileId)
|
|
let fileSource = Just $ CryptoFile filePath cfArgs
|
|
ciFile = CIFile {fileId, fileName, fileSize, fileSource, fileStatus = CIFSSndStored, fileProtocol = FPXFTP, fileExpires = Nothing, fileProhibited = Nothing}
|
|
pure (fInv, ciFile, ft)
|
|
|
|
fileNeedsBadge :: Integer -> CM Bool
|
|
fileNeedsBadge fileSize = (fileSize >) . noBadge <$> asks (fileSizeLimits . config)
|
|
|
|
sndBadgeProof :: User -> ProofPresHeader -> CM (Maybe BadgeProof)
|
|
sndBadgeProof user = sndBadgeProof_ user . BBSPresHeader . strEncode
|
|
|
|
sndBadgeProof_ :: User -> BBSPresHeader -> CM (Maybe BadgeProof)
|
|
sndBadgeProof_ User {profile = LocalProfile {localBadge}} ph = case localBadge of
|
|
Just (OwnBadge cred@(BadgeCredential keyIdx _ _ _) _) -> do
|
|
keys <- asks $ badgePublicKeys . config
|
|
case M.lookup keyIdx keys of
|
|
Nothing -> Nothing <$ logError "sndBadgeProof: badge key index not in config"
|
|
Just key ->
|
|
liftIO (generateBadgeProof key cred ph) >>= \case
|
|
Right proof -> pure $ Just proof
|
|
Left e -> Nothing <$ logError ("sndBadgeProof: proof generation failed: " <> T.pack e)
|
|
_ -> pure Nothing
|
|
|
|
sndGroupChatBinding :: GroupInfo -> ShowGroupAsSender -> Maybe ByteString
|
|
sndGroupChatBinding gInfo@GroupInfo {membership = GroupMember {memberId, memberPubKey}} asGroup
|
|
| asGroup = (\PublicGroupProfile {publicGroupId} -> encodeChatBinding CBChannel $ smpEncode publicGroupId) <$> publicGroup' gInfo
|
|
| otherwise = (\k -> encodeChatBinding CBGroup $ groupBindingData gInfo memberId k) <$> memberPubKey
|
|
|
|
cryptoFileDigest :: CryptoFile -> CM FD.FileDigest
|
|
cryptoFileDigest (CryptoFile filePath cfArgs) = do
|
|
fsPath <- lift $ toFSFilePath filePath
|
|
r <- liftIO $ runExceptT $ CF.readFile (CryptoFile fsPath cfArgs)
|
|
either (throwChatError . CEInternalError . show) (pure . FD.FileDigest . LC.sha512Hash) r
|
|
|
|
xftpSndFileRedirect :: User -> FileTransferId -> ValidFileDescription 'FRecipient -> CM FileTransferMeta
|
|
xftpSndFileRedirect user ftId vfd = do
|
|
let fileName = "redirect.yaml"
|
|
file = CryptoFile fileName Nothing
|
|
fInv = xftpFileInvitation fileName (fromIntegral $ B.length $ strEncode vfd) dummyFileDescr
|
|
aFileId <- withAgent $ \a -> xftpPrepareSendDescription a (aUserId user) vfd (roundedFDCount 1)
|
|
chSize <- asks $ fileChunkSize . config
|
|
ft <- withStore' $ \db -> createSndFileTransferXFTP db user Nothing file fInv (AgentSndFileId aFileId) (Just ftId) chSize
|
|
ft <$ withAgent (`xftpStartSendFile` aFileId)
|
|
|
|
dummyFileDescr :: FileDescr
|
|
dummyFileDescr = FileDescr {fileDescrText = "", fileDescrPartNo = 0, fileDescrComplete = False}
|
|
|
|
cancelFilesInProgress :: User -> [CIFileInfo] -> CM ()
|
|
cancelFilesInProgress user filesInfo = do
|
|
let filesInfo' = filter (not . fileEnded) filesInfo
|
|
(sfs, rfs) <- lift $ splitFTTypes <$> withStoreBatch (\db -> map (getFT db) filesInfo')
|
|
forM_ rfs $ \RcvFileTransfer {fileId} -> lift (closeFileHandle fileId rcvFiles) `catchAllErrors` \_ -> pure ()
|
|
lift . void . withStoreBatch' $ \db -> map (updateSndFileCancelled db) sfs
|
|
lift . void . withStoreBatch' $ \db -> map (updateRcvFileCancelled db) rfs
|
|
let xsfIds = mapMaybe (\(FileTransferMeta {fileId, xftpSndFile}, _) -> (,fileId) <$> xftpSndFile) sfs
|
|
xrfIds = mapMaybe (\RcvFileTransfer {fileId, xftpRcvFile} -> (,fileId) <$> xftpRcvFile) rfs
|
|
lift $ agentXFTPDeleteSndFilesRemote user xsfIds
|
|
lift $ agentXFTPDeleteRcvFiles xrfIds
|
|
where
|
|
fileEnded CIFileInfo {fileStatus} = case fileStatus of
|
|
Just (AFS _ status) -> ciFileEnded status
|
|
Nothing -> True
|
|
getFT :: DB.Connection -> CIFileInfo -> IO (Either ChatError FileTransfer)
|
|
getFT db CIFileInfo {fileId} = runExceptT . withExceptT ChatErrorStore $ getFileTransfer db user fileId
|
|
updateSndFileCancelled :: DB.Connection -> (FileTransferMeta, [SndFileTransfer]) -> IO ()
|
|
updateSndFileCancelled db (FileTransferMeta {fileId}, sfts) = do
|
|
updateFileCancelled db user fileId CIFSSndCancelled
|
|
forM_ sfts $ \sft -> unless (sndFTEnded sft) $ updateSndFileStatus db sft FSCancelled
|
|
updateRcvFileCancelled :: DB.Connection -> RcvFileTransfer -> IO ()
|
|
updateRcvFileCancelled db ft@RcvFileTransfer {fileId} = do
|
|
updateFileCancelled db user fileId CIFSRcvCancelled
|
|
updateRcvFileStatus db fileId FSCancelled
|
|
deleteRcvFileChunks db ft
|
|
splitFTTypes :: [Either ChatError FileTransfer] -> ([(FileTransferMeta, [SndFileTransfer])], [RcvFileTransfer])
|
|
splitFTTypes = foldr addFT ([], []) . rights
|
|
where
|
|
addFT f (sfs, rfs) = case f of
|
|
FTSnd ft@FileTransferMeta {cancelled} sfts | not cancelled -> ((ft, sfts) : sfs, rfs)
|
|
FTRcv ft@RcvFileTransfer {cancelled} | not cancelled -> (sfs, ft : rfs)
|
|
_ -> (sfs, rfs)
|
|
sndFTEnded SndFileTransfer {fileStatus} = fileStatus == FSCancelled || fileStatus == FSComplete
|
|
|
|
deleteFilesLocally :: [CIFileInfo] -> CM ()
|
|
deleteFilesLocally files =
|
|
withFilesFolder $ \filesFolder ->
|
|
liftIO . forM_ files $ \CIFileInfo {filePath} ->
|
|
mapM_ (delete . (filesFolder </>)) filePath
|
|
where
|
|
delete :: FilePath -> IO ()
|
|
delete fPath =
|
|
removeFile fPath `catchAll` \_ ->
|
|
removePathForcibly fPath `catchAll_` pure ()
|
|
-- perform an action only if filesFolder is set (i.e. on mobile devices)
|
|
withFilesFolder :: (FilePath -> CM ()) -> CM ()
|
|
withFilesFolder action = asks filesFolder >>= readTVarIO >>= mapM_ action
|
|
|
|
deleteDirectCIs :: User -> Contact -> [CChatItem 'CTDirect] -> CM [ChatItemDeletion]
|
|
deleteDirectCIs user ct items = do
|
|
let ciFilesInfo = mapMaybe (\(CChatItem _ ChatItem {file}) -> mkCIFileInfo <$> file) items
|
|
deleteCIFiles user ciFilesInfo
|
|
(errs, deletions) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (deleteItem db) items)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
pure deletions
|
|
where
|
|
deleteItem db (CChatItem md ci) = do
|
|
deleteDirectChatItem db user ct ci
|
|
pure $ contactDeletion md ct ci Nothing
|
|
|
|
deleteGroupCIs :: User -> GroupInfo -> Maybe GroupChatScopeInfo -> [CChatItem 'CTGroup] -> Maybe GroupMember -> UTCTime -> CM [ChatItemDeletion]
|
|
deleteGroupCIs user gInfo chatScopeInfo items byGroupMember_ deletedTs = do
|
|
let ciFilesInfo = mapMaybe (\(CChatItem _ ChatItem {file}) -> mkCIFileInfo <$> file) items
|
|
deleteCIFiles user ciFilesInfo
|
|
(errs, deletions) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (deleteItem db) items)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
cxt <- chatStoreCxt
|
|
deletions' <- case chatScopeInfo of
|
|
Nothing -> pure deletions
|
|
Just scopeInfo@GCSIMemberSupport {groupMember_} -> do
|
|
let decStats = countDeletedUnreadItems groupMember_ deletions
|
|
gInfo' <- withFastStore' $ \db -> updateGroupScopeUnreadStats db cxt user gInfo scopeInfo decStats
|
|
pure $ map (updateDeletionGroupInfo gInfo') deletions
|
|
pure deletions'
|
|
where
|
|
deleteItem :: DB.Connection -> CChatItem 'CTGroup -> IO ChatItemDeletion
|
|
deleteItem db (CChatItem md ci) = do
|
|
ci' <- case byGroupMember_ of
|
|
Just m -> Just <$> updateGroupChatItemModerated db user gInfo ci m deletedTs
|
|
Nothing -> Nothing <$ deleteGroupChatItem db user gInfo ci
|
|
pure $ groupDeletion md gInfo chatScopeInfo ci ci'
|
|
countDeletedUnreadItems :: Maybe GroupMember -> [ChatItemDeletion] -> (Int, Int, Int)
|
|
countDeletedUnreadItems scopeMember_ = foldl' countItem (0, 0, 0)
|
|
where
|
|
countItem :: (Int, Int, Int) -> ChatItemDeletion -> (Int, Int, Int)
|
|
countItem (!unread, !unanswered, !mentions) ChatItemDeletion {deletedChatItem}
|
|
| aChatItemIsRcvNew deletedChatItem =
|
|
let unread' = unread + 1
|
|
unanswered' = case (scopeMember_, aChatItemRcvFromMember deletedChatItem) of
|
|
(Just scopeMember, Just rcvFromMember)
|
|
| groupMemberId' rcvFromMember == groupMemberId' scopeMember -> unanswered + 1
|
|
_ -> unanswered
|
|
mentions' = if isACIUserMention deletedChatItem then mentions + 1 else mentions
|
|
in (unread', unanswered', mentions')
|
|
| otherwise = (unread, unanswered, mentions)
|
|
updateDeletionGroupInfo :: GroupInfo -> ChatItemDeletion -> ChatItemDeletion
|
|
updateDeletionGroupInfo gInfo' ChatItemDeletion {deletedChatItem, toChatItem} =
|
|
ChatItemDeletion
|
|
{ deletedChatItem = updateACIGroupInfo gInfo' deletedChatItem,
|
|
toChatItem = updateACIGroupInfo gInfo' <$> toChatItem
|
|
}
|
|
|
|
updateACIGroupInfo :: GroupInfo -> AChatItem -> AChatItem
|
|
updateACIGroupInfo gInfo' = \case
|
|
AChatItem SCTGroup dir (GroupChat _gInfo chatScopeInfo) ci ->
|
|
AChatItem SCTGroup dir (GroupChat gInfo' chatScopeInfo) ci
|
|
aci -> aci
|
|
|
|
deleteGroupMemberCIs :: User -> GroupInfo -> GroupMember -> CM ()
|
|
deleteGroupMemberCIs user gInfo member = do
|
|
filesInfo <- withStore' $ \db -> deleteGroupMemberCIs_ db user gInfo member
|
|
deleteCIFiles user filesInfo
|
|
|
|
deleteGroupMembersCIs :: User -> GroupInfo -> [GroupMember] -> CM ()
|
|
deleteGroupMembersCIs user gInfo members = do
|
|
filesInfo <- withStore' $ \db -> fmap concat $ forM members $ deleteGroupMemberCIs_ db user gInfo
|
|
deleteCIFiles user filesInfo
|
|
|
|
deleteGroupMemberCIs_ :: DB.Connection -> User -> GroupInfo -> GroupMember -> IO [CIFileInfo]
|
|
deleteGroupMemberCIs_ db user gInfo member = do
|
|
fs <- getGroupMemberFileInfo db user gInfo member
|
|
deleteMemberCIs db user gInfo member
|
|
pure fs
|
|
|
|
deleteLocalCIs :: User -> NoteFolder -> [CChatItem 'CTLocal] -> Bool -> Bool -> CM ChatResponse
|
|
deleteLocalCIs user nf items byUser timed = do
|
|
let ciFilesInfo = mapMaybe (\(CChatItem _ ChatItem {file}) -> mkCIFileInfo <$> file) items
|
|
deleteFilesLocally ciFilesInfo
|
|
(errs, deletions) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (deleteItem db) items)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
pure $ CRChatItemsDeleted user deletions byUser timed
|
|
where
|
|
deleteItem db (CChatItem md ci) = do
|
|
deleteLocalChatItem db user nf ci
|
|
pure $ ChatItemDeletion (nfItem md ci) Nothing
|
|
nfItem :: MsgDirectionI d => SMsgDirection d -> ChatItem 'CTLocal d -> AChatItem
|
|
nfItem md = AChatItem SCTLocal md (LocalChat nf)
|
|
|
|
deleteCIFiles :: User -> [CIFileInfo] -> CM ()
|
|
deleteCIFiles user filesInfo = do
|
|
cancelFilesInProgress user filesInfo
|
|
deleteFilesLocally filesInfo
|
|
|
|
markDirectCIsDeleted :: User -> Contact -> [CChatItem 'CTDirect] -> UTCTime -> CM [ChatItemDeletion]
|
|
markDirectCIsDeleted user ct items deletedTs = do
|
|
let ciFilesInfo = mapMaybe (\(CChatItem _ ChatItem {file}) -> mkCIFileInfo <$> file) items
|
|
cancelFilesInProgress user ciFilesInfo
|
|
(errs, deletions) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (markDeleted db) items)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
pure deletions
|
|
where
|
|
markDeleted db (CChatItem md ci) = do
|
|
ci' <- markDirectChatItemDeleted db user ct ci deletedTs
|
|
pure $ contactDeletion md ct ci (Just ci')
|
|
|
|
markGroupCIsDeleted :: User -> GroupInfo -> Maybe GroupChatScopeInfo -> [CChatItem 'CTGroup] -> Maybe GroupMember -> UTCTime -> CM [ChatItemDeletion]
|
|
markGroupCIsDeleted user gInfo chatScopeInfo items byGroupMember_ deletedTs = do
|
|
let ciFilesInfo = mapMaybe (\(CChatItem _ ChatItem {file}) -> mkCIFileInfo <$> file) items
|
|
cancelFilesInProgress user ciFilesInfo
|
|
(errs, deletions) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (markDeleted db) items)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
pure deletions
|
|
where
|
|
markDeleted db (CChatItem md ci) = do
|
|
ci' <- markGroupChatItemDeleted db user gInfo ci byGroupMember_ deletedTs
|
|
pure $ groupDeletion md gInfo chatScopeInfo ci (Just ci')
|
|
|
|
markGroupMemberCIsDeleted :: User -> GroupInfo -> GroupMember -> GroupMember -> CM ()
|
|
markGroupMemberCIsDeleted user gInfo member byGroupMember = do
|
|
deletedTs <- liftIO getCurrentTime
|
|
filesInfo <- withStore' $ \db -> markGroupMemberCIsDeleted_ db user gInfo member byGroupMember deletedTs
|
|
cancelFilesInProgress user filesInfo
|
|
|
|
markGroupMembersCIsDeleted :: User -> GroupInfo -> [GroupMember] -> GroupMember -> CM ()
|
|
markGroupMembersCIsDeleted user gInfo members byGroupMember = do
|
|
deletedTs <- liftIO getCurrentTime
|
|
filesInfo <- withStore' $ \db -> fmap concat $ forM members $ \m -> markGroupMemberCIsDeleted_ db user gInfo m byGroupMember deletedTs
|
|
cancelFilesInProgress user filesInfo
|
|
|
|
markGroupMemberCIsDeleted_ :: DB.Connection -> User -> GroupInfo -> GroupMember -> GroupMember -> UTCTime -> IO [CIFileInfo]
|
|
markGroupMemberCIsDeleted_ db user gInfo member byGroupMember deletedTs = do
|
|
fs <- getGroupMemberFileInfo db user gInfo member
|
|
markMemberCIsDeleted db user gInfo member byGroupMember deletedTs
|
|
pure fs
|
|
|
|
groupDeletion :: MsgDirectionI d => SMsgDirection d -> GroupInfo -> Maybe GroupChatScopeInfo -> ChatItem 'CTGroup d -> Maybe (ChatItem 'CTGroup d) -> ChatItemDeletion
|
|
groupDeletion md g chatScopeInfo ci ci' = ChatItemDeletion (gItem ci) (gItem <$> ci')
|
|
where
|
|
gItem = AChatItem SCTGroup md (GroupChat g chatScopeInfo)
|
|
|
|
contactDeletion :: MsgDirectionI d => SMsgDirection d -> Contact -> ChatItem 'CTDirect d -> Maybe (ChatItem 'CTDirect d) -> ChatItemDeletion
|
|
contactDeletion md ct ci ci' = ChatItemDeletion (ctItem ci) (ctItem <$> ci')
|
|
where
|
|
ctItem = AChatItem SCTDirect md (DirectChat ct)
|
|
|
|
updateCallItemStatus :: User -> Contact -> Call -> WebRTCCallStatus -> Maybe MessageId -> CM ()
|
|
updateCallItemStatus user ct@Contact {contactId} Call {chatItemId} receivedStatus msgId_ = do
|
|
aciContent_ <- callStatusItemContent user ct chatItemId receivedStatus
|
|
forM_ aciContent_ $ \aciContent -> do
|
|
timed_ <- callTimed ct aciContent
|
|
updateDirectChatItemView user ct chatItemId aciContent False False timed_ msgId_
|
|
forM_ (timed_ >>= timedDeleteAt') $
|
|
startProximateTimedItemThread user (ChatRef CTDirect contactId Nothing, chatItemId)
|
|
|
|
updateDirectChatItemView :: User -> Contact -> ChatItemId -> ACIContent -> Bool -> Bool -> Maybe CITimed -> Maybe MessageId -> CM ()
|
|
updateDirectChatItemView user ct chatItemId (ACIContent msgDir ciContent) edited live timed_ msgId_ = do
|
|
(ci, ci') <- withStore $ \db -> updateDirectChatItem db user ct chatItemId ciContent edited live timed_ msgId_
|
|
toView $ CEvtChatItemUpdated user (AChatItemUpdate SCTDirect msgDir (DirectChat ct) ci' ci)
|
|
|
|
callStatusItemContent :: User -> Contact -> ChatItemId -> WebRTCCallStatus -> CM (Maybe ACIContent)
|
|
callStatusItemContent user Contact {contactId} chatItemId receivedStatus = do
|
|
CChatItem msgDir ChatItem {meta = CIMeta {updatedAt}, content} <-
|
|
withStore $ \db -> getDirectChatItem db user contactId chatItemId
|
|
ts <- liftIO getCurrentTime
|
|
let callDuration :: Int = nominalDiffTimeToSeconds (ts `diffUTCTime` updatedAt) `div'` 1
|
|
callStatus = case content of
|
|
CISndCall st _ -> Just st
|
|
CIRcvCall st _ -> Just st
|
|
_ -> Nothing
|
|
newState_ = case (callStatus, receivedStatus) of
|
|
(Just CISCallProgress, WCSConnected) -> Nothing -- if call in-progress received connected -> no change
|
|
(Just CISCallProgress, WCSDisconnected) -> Just (CISCallEnded, callDuration) -- calculate in-progress duration
|
|
(Just CISCallProgress, WCSFailed) -> Just (CISCallEnded, callDuration) -- whether call disconnected or failed
|
|
(Just CISCallPending, WCSDisconnected) -> Just (CISCallMissed, 0)
|
|
(Just CISCallEnded, _) -> Nothing -- if call already ended or failed -> no change
|
|
(Just CISCallError, _) -> Nothing
|
|
(Just _, WCSConnecting) -> Just (CISCallNegotiated, 0)
|
|
(Just _, WCSConnected) -> Just (CISCallProgress, 0) -- if call ended that was never connected, duration = 0
|
|
(Just _, WCSDisconnected) -> Just (CISCallEnded, 0)
|
|
(Just _, WCSFailed) -> Just (CISCallError, 0)
|
|
(Nothing, _) -> Nothing -- some other content - we should never get here, but no exception is thrown
|
|
pure $ aciContent msgDir <$> newState_
|
|
where
|
|
aciContent :: forall d. SMsgDirection d -> (CICallStatus, Int) -> ACIContent
|
|
aciContent msgDir (callStatus', duration) = case msgDir of
|
|
SMDSnd -> ACIContent SMDSnd $ CISndCall callStatus' duration
|
|
SMDRcv -> ACIContent SMDRcv $ CIRcvCall callStatus' duration
|
|
|
|
-- mobile clients use file paths relative to app directory (e.g. for the reason ios app directory changes on updates),
|
|
-- so we have to differentiate between the file path stored in db and communicated with frontend, and the file path
|
|
-- used during file transfer for actual operations with file system
|
|
toFSFilePath :: FilePath -> CM' FilePath
|
|
toFSFilePath f =
|
|
maybe f (</> f) <$> (chatReadVar' filesFolder)
|
|
|
|
setFileToEncrypt :: RcvFileTransfer -> CM RcvFileTransfer
|
|
setFileToEncrypt ft@RcvFileTransfer {fileId} = do
|
|
cfArgs <- atomically . CF.randomArgs =<< asks random
|
|
withStore' $ \db -> setFileCryptoArgs db fileId cfArgs
|
|
pure (ft :: RcvFileTransfer) {cryptoArgs = Just cfArgs}
|
|
|
|
receiveFile' :: User -> RcvFileTransfer -> Bool -> Maybe Bool -> Maybe FilePath -> CM ChatResponse
|
|
receiveFile' user ft userApprovedRelays rcvInline_ filePath_ = do
|
|
(CRRcvFileAccepted user <$> acceptFileReceive user ft userApprovedRelays rcvInline_ filePath_) `catchAllErrors` processError
|
|
where
|
|
-- TODO AChatItem in Cancelled events
|
|
processError e
|
|
| rctFileCancelled e = pure $ CRRcvFileAcceptedSndCancelled user ft
|
|
| otherwise = throwError e
|
|
|
|
receiveFileEvt' :: User -> RcvFileTransfer -> Bool -> Maybe Bool -> Maybe FilePath -> CM ChatEvent
|
|
receiveFileEvt' user ft userApprovedRelays rcvInline_ filePath_ = do
|
|
(CEvtRcvFileAccepted user <$> acceptFileReceive user ft userApprovedRelays rcvInline_ filePath_) `catchAllErrors` processError
|
|
where
|
|
-- TODO AChatItem in Cancelled events
|
|
processError e
|
|
| rctFileCancelled e = pure $ CEvtRcvFileAcceptedSndCancelled user ft
|
|
| otherwise = throwError e
|
|
|
|
rctFileCancelled :: ChatError -> Bool
|
|
rctFileCancelled = \case
|
|
ChatErrorAgent (SMP _ SMP.AUTH) _ _ -> True
|
|
ChatErrorAgent (CONN DUPLICATE _) _ _ -> True
|
|
_ -> False
|
|
|
|
acceptFileReceive :: User -> RcvFileTransfer -> Bool -> Maybe Bool -> Maybe FilePath -> CM AChatItem
|
|
acceptFileReceive user@User {userId} RcvFileTransfer {fileId, xftpRcvFile, fileInvitation = FileInvitation {fileName = fName, fileConnReq, fileInline, fileSize}, fileProhibited, fileStatus, grpMemberId, cryptoArgs} userApprovedRelays rcvInline_ filePath_ = do
|
|
unless (fileStatus == RFSNew) $ case fileStatus of
|
|
RFSCancelled _ -> throwChatError $ CEFileCancelled fName
|
|
_ -> throwChatError $ CEFileAlreadyReceiving fName
|
|
when (isJust fileProhibited) $ throwChatError $ CEFileSize fName
|
|
cxt <- chatStoreCxt
|
|
case (xftpRcvFile, fileConnReq) of
|
|
-- XFTP
|
|
(Just XFTPRcvFile {userApprovedRelays = approvedBeforeReady}, _) -> do
|
|
let userApproved = approvedBeforeReady || userApprovedRelays
|
|
filePath <- getRcvFilePath fileId filePath_ fName False
|
|
(ci, rfd) <- withStore $ \db -> do
|
|
-- marking file as accepted and reading description in the same transaction
|
|
-- to prevent race condition with appending description
|
|
ci <- xftpAcceptRcvFT db cxt user fileId filePath userApproved
|
|
rfd <- getRcvFileDescrByRcvFileId db fileId
|
|
pure (ci, rfd)
|
|
receiveViaCompleteFD user fileId rfd fileSize userApproved cryptoArgs
|
|
pure ci
|
|
(Nothing, Just _fileConnReq) -> throwChatError $ CEException "accepting file via a separate connection is deprecated"
|
|
-- group & direct file protocol
|
|
_ -> do
|
|
chatRef <- withStore $ \db -> getChatRefByFileId db user fileId
|
|
case (chatRef, grpMemberId) of
|
|
(ChatRef CTDirect contactId _, Nothing) -> do
|
|
ct <- withStore $ \db -> getContact db cxt user contactId
|
|
acceptFile $ \msg -> void $ sendDirectContactMessage user ct msg
|
|
(ChatRef CTGroup groupId _, Just memId) -> do
|
|
GroupMember {activeConn} <- withStore $ \db -> getGroupMember db cxt user groupId memId
|
|
case activeConn of
|
|
Just conn -> do
|
|
acceptFile $ \msg -> void $ sendDirectMemberMessage conn msg groupId
|
|
_ -> throwChatError $ CEFileInternal "member connection not active"
|
|
_ -> throwChatError $ CEFileInternal "invalid chat ref for file transfer"
|
|
where
|
|
acceptFile :: (ChatMsgEvent 'Json -> CM ()) -> CM AChatItem
|
|
acceptFile send = do
|
|
filePath <- getRcvFilePath fileId filePath_ fName True
|
|
inline <- receiveInline
|
|
cxt <- chatStoreCxt
|
|
if
|
|
| inline -> do
|
|
-- accepting inline
|
|
(ci, sharedMsgId) <- withStore $ \db ->
|
|
liftM2 (,) (acceptRcvInlineFT db cxt user fileId filePath) (getSharedMsgIdByFileId db userId fileId)
|
|
send $ XFileAcptInv sharedMsgId Nothing fName
|
|
pure ci
|
|
| fileInline == Just IFMSent -> throwChatError $ CEFileAlreadyReceiving fName
|
|
| otherwise -> throwChatError $ CEException "accepting file via a separate connection is deprecated"
|
|
receiveInline :: CM Bool
|
|
receiveInline = do
|
|
ChatConfig {fileChunkSize, inlineFiles = InlineFilesConfig {receiveChunks, offerChunks}} <- asks config
|
|
pure $
|
|
rcvInline_ /= Just False
|
|
&& fileInline == Just IFMOffer
|
|
&& ( fileSize <= fileChunkSize * receiveChunks
|
|
|| (rcvInline_ == Just True && fileSize <= fileChunkSize * offerChunks)
|
|
)
|
|
|
|
receiveViaCompleteFD :: User -> FileTransferId -> RcvFileDescr -> Integer -> Bool -> Maybe CryptoFileArgs -> CM ()
|
|
receiveViaCompleteFD user fileId RcvFileDescr {fileDescrText, fileDescrComplete} expectedFileSize userApprovedRelays cfArgs =
|
|
when fileDescrComplete $ do
|
|
rd <- parseFileDescription fileDescrText
|
|
let FD.ValidFileDescription FD.FileDescription {size = FD.FileSize encSize, redirect} = rd
|
|
redirectSize = maybe 0 (\FD.RedirectFileInfo {size = FD.FileSize s} -> toInteger s) redirect
|
|
-- for a redirect, encSize is the description blob and redirectSize the final file; take the larger
|
|
rcvSize = max (toInteger encSize) redirectSize
|
|
-- 10 MB margin: encryption and chunk-size rounding make the transfer larger than the advertised size
|
|
maxRcvSize = min expectedFileSize (toInteger FD.maxFileSizeHard) + toInteger (FD.mb 10 :: Int64)
|
|
-- TODO re-enable redirects with relay checks
|
|
when (isJust redirect) $ do
|
|
cxt <- chatStoreCxt
|
|
upd_ <- withStore $ \db ->
|
|
updateFileChatItem db cxt user fileId $ updateFileCancelled db user fileId (CIFSRcvError $ FileErrOther "redirect not allowed")
|
|
forM_ upd_ $ \upd -> do
|
|
cleanupACIFile $ updatedAChatItem upd
|
|
toView $ CEvtChatItemUpdated user upd
|
|
throwChatError $ CEInvalidFileDescription "redirect not allowed"
|
|
when (rcvSize > maxRcvSize) $ throwChatError $ CEFileRcvChunk "declared file size exceeds the file invitation size"
|
|
if userApprovedRelays
|
|
then receive' rd True
|
|
else do
|
|
let srvs = fileDescrServers rd
|
|
unknownSrvs <- getUnknownSrvs srvs
|
|
let approved = null unknownSrvs
|
|
ifM
|
|
((approved ||) <$> ipProtectedForSrvs srvs)
|
|
(receive' rd approved)
|
|
(relaysNotApproved unknownSrvs)
|
|
where
|
|
receive' :: ValidFileDescription 'FRecipient -> Bool -> CM ()
|
|
receive' rd approved = do
|
|
aFileId <- withAgent $ \a -> xftpPrepareReceiveFile a (aUserId user) rd cfArgs approved
|
|
startReceivingFile user fileId
|
|
withStore' $ \db -> updateRcvFileAgentId db fileId (Just $ AgentRcvFileId aFileId)
|
|
withAgent (`xftpStartReceiveFile` aFileId)
|
|
getUnknownSrvs :: [XFTPServer] -> CM [XFTPServer]
|
|
getUnknownSrvs srvs = do
|
|
knownSrvs <- L.map protoServer' <$> getKnownAgentServers SPXFTP user
|
|
pure $ filter (`notElem` knownSrvs) srvs
|
|
ipProtectedForSrvs :: [XFTPServer] -> CM Bool
|
|
ipProtectedForSrvs srvs = do
|
|
netCfg <- lift getNetworkConfig
|
|
pure $ all (ipAddressProtected netCfg) srvs
|
|
relaysNotApproved :: [XFTPServer] -> CM ()
|
|
relaysNotApproved unknownSrvs = do
|
|
upd_ <- resetRcvCIFileStatus user fileId CIFSRcvInvitation
|
|
forM_ upd_ $ \upd -> do
|
|
cleanupACIFile $ updatedAChatItem upd
|
|
toView $ CEvtChatItemUpdated user upd
|
|
throwChatError $ CEFileNotApproved fileId unknownSrvs
|
|
|
|
cleanupACIFile :: AChatItem -> CM ()
|
|
cleanupACIFile (AChatItem _ _ _ ChatItem {file = Just CIFile {fileSource = Just CryptoFile {filePath}}}) = do
|
|
fsFilePath <- lift $ toFSFilePath filePath
|
|
removeFile fsFilePath `catchAllErrors` \_ -> pure ()
|
|
cleanupACIFile _ = pure ()
|
|
|
|
getKnownAgentServers :: (ProtocolTypeI p, UserProtocol p) => SProtocolType p -> User -> CM (NonEmpty (ServerCfg p))
|
|
getKnownAgentServers p user = do
|
|
as <- asks randomAgentServers
|
|
withStore $ \db -> do
|
|
opDomains <- operatorDomains . serverOperators <$> getServerOperators db
|
|
srvs <- liftIO $ getProtocolServers db p user
|
|
pure $ useServerCfgs p as opDomains srvs
|
|
|
|
protoServer' :: ServerCfg p -> ProtocolServer p
|
|
protoServer' ServerCfg {server} = protoServer server
|
|
|
|
getNetworkConfig :: CM' NetworkConfig
|
|
getNetworkConfig = withAgent' $ liftIO . getFastNetworkConfig
|
|
|
|
resetRcvCIFileStatus :: User -> FileTransferId -> CIFileStatus 'MDRcv -> CM (Maybe AChatItemUpdate)
|
|
resetRcvCIFileStatus user fileId ciFileStatus = do
|
|
cxt <- chatStoreCxt
|
|
withStore $ \db -> updateFileChatItem db cxt user fileId $ resetRcvFile db user fileId ciFileStatus
|
|
|
|
resetRcvFile :: DB.Connection -> User -> FileTransferId -> CIFileStatus 'MDRcv -> IO ()
|
|
resetRcvFile db user fileId ciFileStatus = do
|
|
updateCIFileStatus db user fileId ciFileStatus
|
|
updateRcvFileStatus db fileId FSNew
|
|
updateRcvFileAgentId db fileId Nothing
|
|
|
|
receiveViaURI :: User -> FileDescriptionURI -> CryptoFile -> CM RcvFileTransfer
|
|
receiveViaURI user@User {userId} FileDescriptionURI {description} cf@CryptoFile {cryptoArgs} = do
|
|
fileId <- withStore $ \db -> createRcvStandaloneFileTransfer db userId cf fileSize chunkSize
|
|
-- currently the only use case is user migrating via their configured servers, so we pass approvedRelays = True
|
|
aFileId <- withAgent $ \a -> xftpPrepareReceiveFile a (aUserId user) description cryptoArgs True
|
|
ft <- withStore $ \db -> do
|
|
liftIO $ do
|
|
updateRcvFileStatus db fileId FSConnected
|
|
updateCIFileStatus db user fileId $ CIFSRcvTransfer 0 1
|
|
updateRcvFileAgentId db fileId (Just $ AgentRcvFileId aFileId)
|
|
getRcvFileTransfer db user fileId
|
|
ft <$ withAgent (`xftpStartReceiveFile` aFileId)
|
|
where
|
|
FD.ValidFileDescription FD.FileDescription {size = FD.FileSize fileSize, chunkSize = FD.FileSize chunkSize} = description
|
|
|
|
startReceivingFile :: User -> FileTransferId -> CM ()
|
|
startReceivingFile user fileId = do
|
|
cxt <- chatStoreCxt
|
|
ci <- withStore $ \db -> do
|
|
liftIO $ updateRcvFileStatus db fileId FSConnected
|
|
liftIO $ updateCIFileStatus db user fileId $ CIFSRcvTransfer 0 1
|
|
getChatItemByFileId db cxt user fileId
|
|
toView $ CEvtRcvFileStart user ci
|
|
|
|
getRcvFilePath :: FileTransferId -> Maybe FilePath -> String -> Bool -> CM FilePath
|
|
getRcvFilePath fileId fPath_ fn keepHandle = case fPath_ of
|
|
Nothing ->
|
|
chatReadVar filesFolder >>= \case
|
|
Nothing -> do
|
|
defaultFolder <- lift getDefaultFilesFolder
|
|
fPath <- liftIO $ defaultFolder `uniqueCombine` fn
|
|
createEmptyFile fPath $> fPath
|
|
Just filesFolder -> do
|
|
fPath <- liftIO $ filesFolder `uniqueCombine` fn
|
|
createEmptyFile fPath
|
|
pure $ takeFileName fPath
|
|
Just fPath ->
|
|
ifM
|
|
(doesDirectoryExist fPath)
|
|
(createInPassedDirectory fPath)
|
|
$ ifM
|
|
(doesFileExist fPath)
|
|
(throwChatError $ CEFileAlreadyExists fPath)
|
|
(createEmptyFile fPath $> fPath)
|
|
where
|
|
createInPassedDirectory :: FilePath -> CM FilePath
|
|
createInPassedDirectory fPathDir = do
|
|
fPath <- liftIO $ fPathDir `uniqueCombine` fn
|
|
createEmptyFile fPath $> fPath
|
|
createEmptyFile :: FilePath -> CM ()
|
|
createEmptyFile fPath = emptyFile `catchThrow` (ChatError . CEFileWrite fPath . show)
|
|
where
|
|
emptyFile :: CM ()
|
|
emptyFile
|
|
| keepHandle = do
|
|
h <- getFileHandle fileId fPath rcvFiles AppendMode
|
|
liftIO $ B.hPut h "" >> hFlush h
|
|
| otherwise = liftIO $ B.writeFile fPath ""
|
|
|
|
-- TODO [short links]
|
|
-- Please note:
|
|
-- - the connection here is created as ConnNew, even though when joining it is created as ConnPrepared.
|
|
-- (changing it is risky, as there may be existing "prepared" connections that were not accepted in ConnNew status).
|
|
-- - after accepted, the status is changed by this func caller to ConnSndReady if it is sndSecure, and not changed otherwise - joined changed to ConnJoined in this case.
|
|
-- - xContactId is set on the contact at the first acceptance attempt, not after accept success, which prevents profile updates after such attempt.
|
|
-- It may be reasonable to set it when contact is first prepared, but then we can't use it to ignore requests after acceptance,
|
|
-- and it may lead to race conditions with XInfo events.
|
|
acceptContactRequest :: NetworkRequestMode -> User -> UserContactRequest -> IncognitoEnabled -> CM (Contact, Connection, SndQueueSecured)
|
|
acceptContactRequest nm user@User {userId} UserContactRequest {agentInvitationId = AgentInvId invId, contactId_, cReqChatVRange, localDisplayName = cName, profileId, profile = cp, userContactLinkId_, xContactId, pqSupport} incognito = do
|
|
subMode <- chatReadVar subscriptionMode
|
|
let pqSup = PQSupportOn
|
|
pqSup' = pqSup `CR.pqSupportAnd` pqSupport
|
|
cxt <- chatStoreCxt
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
(ct, conn, incognitoProfile, getPresHeader) <- case contactId_ of
|
|
Nothing -> do
|
|
incognitoProfile <- if incognito then Just . NewIncognito <$> liftIO (generateIncognitoProfile user) else pure Nothing
|
|
(connId, binding) <- withAgent $ \a -> prepareConnectionToAccept a (aUserId user) True invId pqSup'
|
|
(ct, conn) <- withStore' $ \db ->
|
|
createContactFromRequest db user userContactLinkId_ connId chatV cReqChatVRange cName profileId cp xContactId incognitoProfile subMode pqSup' False
|
|
pure (ct, conn, incognitoProfile, pure $ Just $ directPresHeader binding)
|
|
Just contactId -> do
|
|
ct <- withFastStore $ \db -> getContact db cxt user contactId
|
|
case contactConn ct of
|
|
Nothing -> do
|
|
incognitoProfile <- if incognito then Just . NewIncognito <$> liftIO (generateIncognitoProfile user) else pure Nothing
|
|
(connId, binding) <- withAgent $ \a -> prepareConnectionToAccept a (aUserId user) True invId pqSup'
|
|
currentTs <- liftIO getCurrentTime
|
|
conn <- withStore' $ \db -> do
|
|
forM_ xContactId $ \xcId -> setContactAcceptedXContactId db ct xcId
|
|
createAcceptedContactConn db user userContactLinkId_ contactId connId chatV cReqChatVRange pqSup' incognitoProfile subMode currentTs
|
|
pure (ct {activeConn = Just conn} :: Contact, conn, incognitoProfile, pure $ Just $ directPresHeader binding)
|
|
Just conn@Connection {customUserProfileId} -> do
|
|
incognitoProfile <- forM customUserProfileId $ \pId -> withFastStore $ \db -> getProfileById db userId pId
|
|
pure (ct, conn, ExistingIncognito <$> incognitoProfile, connPresHeader conn)
|
|
profileToSend <- presentUserBadgeWith user incognitoProfile getPresHeader $ userProfileDirect user (fromIncognitoProfile <$> incognitoProfile) (Just ct) True
|
|
dm <- encodeConnInfoPQ pqSup' $ XInfo profileToSend Nothing
|
|
(ct,conn,) <$> withAgent (\a -> acceptContact a nm (aUserId user) (aConnId conn) True invId dm pqSup' subMode)
|
|
|
|
acceptContactRequestAsync :: User -> Int64 -> Contact -> UserContactRequest -> Maybe IncognitoProfile -> CM Contact
|
|
acceptContactRequestAsync
|
|
user
|
|
uclId
|
|
ct@Contact {contactId}
|
|
UserContactRequest {agentInvitationId = AgentInvId cReqInvId, cReqChatVRange, xContactId, pqSupport = cReqPQSup}
|
|
incognitoProfile = do
|
|
subMode <- chatReadVar subscriptionMode
|
|
cxt <- chatStoreCxt
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
((cmdId, acId), presHeader) <- prepareAgentAccept user True cReqInvId cReqPQSup
|
|
profileToSend <- presentUserBadge user incognitoProfile (Just presHeader) $ userProfileDirect user (fromIncognitoProfile <$> incognitoProfile) (Just ct) True
|
|
currentTs <- liftIO getCurrentTime
|
|
ct' <- withStore $ \db -> do
|
|
forM_ xContactId $ \xcId -> liftIO $ setContactAcceptedXContactId db ct xcId
|
|
Connection {connId} <- liftIO $ createAcceptedContactConn db user (Just uclId) contactId acId chatV cReqChatVRange cReqPQSup incognitoProfile subMode currentTs
|
|
liftIO $ setCommandConnId db user cmdId connId
|
|
getContact db cxt user contactId
|
|
agentAcceptContactAsync cmdId acId True cReqInvId (XInfo profileToSend Nothing) cReqPQSup subMode
|
|
pure ct'
|
|
|
|
acceptGroupJoinRequestAsync :: User -> Int64 -> GroupInfoKeys -> InvitationId -> VersionRangeChat -> Profile -> Maybe ProofPresHeader -> Maybe XContactId -> Maybe MemberId -> Maybe SharedMsgId -> GroupAcceptance -> GroupMemberRole -> Maybe IncognitoProfile -> Maybe MemberKey -> Maybe GroupMember -> CM GroupMember
|
|
acceptGroupJoinRequestAsync
|
|
user@User {userId}
|
|
uclId
|
|
(GIK gInfo@GroupInfo {groupProfile, membership, businessChat} gks)
|
|
cReqInvId
|
|
cReqChatVRange
|
|
cReqProfile
|
|
presHeader_
|
|
cReqXContactId_
|
|
cReqMemberId_
|
|
welcomeMsgId_
|
|
gAccepted
|
|
gLinkMemRole
|
|
incognitoProfile
|
|
memberKey_
|
|
existingMem_ = do
|
|
gVar <- asks random
|
|
let initialStatus = acceptanceToStatus (memberAdmission groupProfile) gAccepted
|
|
-- a roster-established privileged member attaches a connection to its existing record (keeping
|
|
-- owner-authoritative role + key); everyone else is created fresh with the group-link role
|
|
cxt <- chatStoreCxt
|
|
(groupMemberId, memberId) <- case existingMem_ of
|
|
Just m -> do
|
|
-- refresh the hash placeholder name from the authenticated join profile; role + key stay roster-authoritative
|
|
withStore $ \db -> do
|
|
liftIO $ updateGroupMemberStatus db userId m initialStatus
|
|
void $ updateMemberProfile db cxt user m presHeader_ cReqProfile
|
|
pure (groupMemberId' m, memberId' m)
|
|
Nothing -> withStore $ \db ->
|
|
createJoiningMember db cxt gVar user gInfo cReqChatVRange cReqProfile presHeader_ cReqXContactId_ cReqMemberId_ welcomeMsgId_ gLinkMemRole initialStatus memberKey_
|
|
let currentMemCount = fromIntegral $ currentMembers $ groupSummary gInfo
|
|
let Profile {displayName} = userProfileInGroup user gInfo (fromIncognitoProfile <$> incognitoProfile)
|
|
GroupMember {memberRole = userRole, memberId = userMemberId} = membership
|
|
msg =
|
|
XGrpLinkInv $
|
|
GroupLinkInvitation
|
|
{ fromMember = MemberIdRole userMemberId userRole,
|
|
fromMemberName = displayName,
|
|
fromMemberKey = Just $ groupMemberKey gks,
|
|
invitedMember = MemberIdRole memberId gLinkMemRole,
|
|
groupProfile,
|
|
accepted = Just gAccepted,
|
|
business = businessChat,
|
|
groupSize = Just currentMemCount
|
|
}
|
|
subMode <- chatReadVar subscriptionMode
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
((cmdId, acId), _) <- prepareAgentAccept user True cReqInvId PQSupportOff
|
|
m <- withStore $ \db -> do
|
|
liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode
|
|
getGroupMemberById db cxt user groupMemberId
|
|
agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff subMode
|
|
pure m
|
|
|
|
acceptGroupJoinSendRejectAsync :: User -> Int64 -> GroupInfo -> InvitationId -> VersionRangeChat -> Profile -> Maybe XContactId -> GroupRejectionReason -> CM GroupMember
|
|
acceptGroupJoinSendRejectAsync
|
|
user
|
|
uclId
|
|
gInfo@GroupInfo {groupProfile, membership}
|
|
cReqInvId
|
|
cReqChatVRange
|
|
cReqProfile
|
|
cReqXContactId_
|
|
rejectionReason = do
|
|
gVar <- asks random
|
|
cxt <- chatStoreCxt
|
|
(groupMemberId, memberId) <- withStore $ \db ->
|
|
createJoiningMember db cxt gVar user gInfo cReqChatVRange cReqProfile Nothing cReqXContactId_ Nothing Nothing GRObserver GSMemRejected Nothing
|
|
let GroupMember {memberRole = userRole, memberId = userMemberId} = membership
|
|
msg =
|
|
XGrpLinkReject $
|
|
GroupLinkRejection
|
|
{ fromMember = MemberIdRole userMemberId userRole,
|
|
invitedMember = MemberIdRole memberId GRObserver,
|
|
groupProfile,
|
|
rejectionReason
|
|
}
|
|
subMode <- chatReadVar subscriptionMode
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
((cmdId, acId), _) <- prepareAgentAccept user False cReqInvId PQSupportOff
|
|
m <- withStore $ \db -> do
|
|
liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode
|
|
getGroupMemberById db cxt user groupMemberId
|
|
agentAcceptContactAsync cmdId acId False cReqInvId msg PQSupportOff subMode
|
|
pure m
|
|
|
|
acceptBusinessJoinRequestAsync :: User -> Int64 -> Maybe ChatLayout -> GroupInfoKeys -> GroupMember -> UserContactRequest -> CM (GroupInfo, GroupMember)
|
|
acceptBusinessJoinRequestAsync
|
|
user
|
|
uclId
|
|
chatLayout
|
|
(GIK gInfo@GroupInfo {membership = GroupMember {memberRole = userRole, memberId = userMemberId}} gks)
|
|
clientMember@GroupMember {groupMemberId, memberId}
|
|
UserContactRequest {agentInvitationId = AgentInvId cReqInvId, cReqChatVRange, xContactId} = do
|
|
cxt <- chatStoreCxt
|
|
let userProfile@Profile {displayName, preferences} = fromLocalProfile $ profile' user
|
|
-- TODO [short links] take groupPreferences from group info
|
|
groupPreferences = maybe defaultBusinessGroupPrefs businessGroupPrefs preferences
|
|
msg =
|
|
XGrpLinkInv $
|
|
GroupLinkInvitation
|
|
{ fromMember = MemberIdRole userMemberId userRole,
|
|
fromMemberName = displayName,
|
|
fromMemberKey = Just $ groupMemberKey gks,
|
|
invitedMember = MemberIdRole memberId GRMember,
|
|
groupProfile = businessGroupProfile userProfile groupPreferences chatLayout,
|
|
accepted = Just GAAccepted,
|
|
-- This refers to the "title member" that defines the group name and profile.
|
|
-- This coincides with fromMember to be current user when accepting the connecting user,
|
|
-- but it will be different when inviting somebody else.
|
|
business = Just $ BusinessChatInfo {chatType = BCBusiness, businessId = userMemberId, customerId = memberId, businessDomain = Nothing},
|
|
groupSize = Just 1
|
|
}
|
|
subMode <- chatReadVar subscriptionMode
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
((cmdId, acId), _) <- prepareAgentAccept user True cReqInvId PQSupportOff
|
|
withStore' $ \db -> do
|
|
forM_ xContactId $ \xcId -> setBusinessChatAcceptedXContactId db gInfo xcId
|
|
createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode
|
|
agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff subMode
|
|
let cd = CDGroupSnd gInfo Nothing
|
|
-- TODO [short links] move to profileContactRequest?
|
|
createInternalChatItem user cd (CISndGroupE2EEInfo $ e2eInfoGroup gInfo) Nothing
|
|
createGroupFeatureItems user cd CISndGroupFeature gInfo
|
|
-- TODO [short links] get updated business chat group and member? (currently not used)
|
|
pure (gInfo, clientMember)
|
|
|
|
acceptRelayJoinRequestAsync :: User -> Int64 -> GroupInfo -> GroupMember -> InvitationId -> VersionRangeChat -> ShortLinkContact -> CM (GroupInfo, GroupMember)
|
|
acceptRelayJoinRequestAsync
|
|
user
|
|
uclId
|
|
gInfo
|
|
_ownerMember@GroupMember {groupMemberId}
|
|
cReqInvId
|
|
cReqChatVRange
|
|
relayLink = do
|
|
ChatConfig {webPreviewConfig} <- asks config
|
|
let webDomain_ = (\WebPreviewConfig {webDomain} -> webDomain) <$> webPreviewConfig
|
|
msg = XGrpRelayAcpt relayLink RelayCapabilities {webDomain = webDomain_}
|
|
subMode <- chatReadVar subscriptionMode
|
|
cxt <- chatStoreCxt
|
|
let chatV = vr cxt `peerConnChatVersion` cReqChatVRange
|
|
((cmdId, acId), _) <- prepareAgentAccept user True cReqInvId PQSupportOff
|
|
r <- withStore $ \db -> do
|
|
liftIO $ createJoiningMemberConnection db user uclId (cmdId, acId) chatV cReqChatVRange groupMemberId subMode
|
|
gInfo' <- liftIO $ updateRelayOwnStatusFromTo db gInfo RSInvited RSAccepted
|
|
ownerMember' <- getGroupMemberById db cxt user groupMemberId
|
|
pure (gInfo', ownerMember')
|
|
agentAcceptContactAsync cmdId acId True cReqInvId msg PQSupportOff subMode
|
|
pure r
|
|
|
|
rejectRelayInvitationAsync
|
|
:: User
|
|
-> Int64
|
|
-> StoreCxt
|
|
-> GroupRelayInvitation
|
|
-> Maybe ProofPresHeader
|
|
-> InvitationId
|
|
-> VersionRangeChat
|
|
-> Int64
|
|
-> RelayRejectionReason
|
|
-> CM ()
|
|
rejectRelayInvitationAsync user uclId cxt groupRelayInv presHeader_ invId reqChatVRange initialDelay reason = do
|
|
(_gInfo, ownerMember) <- withStore $ \db ->
|
|
createRelayRequestGroup db cxt user groupRelayInv presHeader_ invId reqChatVRange initialDelay GSMemInvited RSRejected
|
|
let GroupMember {groupMemberId} = ownerMember
|
|
msg = XGrpRelayReject reason
|
|
subMode <- chatReadVar subscriptionMode
|
|
chatVR <- chatVersionRange
|
|
let chatV = chatVR `peerConnChatVersion` reqChatVRange
|
|
((cmdId, acId), _) <- prepareAgentAccept user False invId PQSupportOff
|
|
withStore' $ \db ->
|
|
createJoiningMemberConnection db user uclId (cmdId, acId) chatV reqChatVRange groupMemberId subMode
|
|
agentAcceptContactAsync cmdId acId False invId msg PQSupportOff subMode
|
|
|
|
businessGroupProfile :: Profile -> GroupPreferences -> Maybe ChatLayout -> GroupProfile
|
|
businessGroupProfile Profile {displayName, fullName, shortDescr, description, image} groupPreferences chatLayout =
|
|
GroupProfile {displayName, fullName, description, shortDescr, image, publicGroup = Nothing, groupPreferences = Just groupPreferences, memberAdmission = Nothing, chatLayout}
|
|
|
|
introduceToModerators :: StoreCxt -> User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
introduceToModerators cxt user gInfo@(GIK g@GroupInfo {groupId} _) m@GroupMember {memberRole, memberId} = do
|
|
forM_ (memberConn m) $ \mConn -> do
|
|
let msg =
|
|
if maxVersion (memberChatVRange m) >= groupKnockingVersion
|
|
then XGrpLinkAcpt GAPendingReview memberRole memberId
|
|
else XMsgNew $ mcSimple (MCText pendingReviewMessage)
|
|
void $ sendDirectMemberMessage mConn msg groupId
|
|
modMs <- withStore' $ \db -> getGroupModerators db cxt user g
|
|
let rcpModMs = filter shouldIntroduceToMod modMs
|
|
introduceMember user gInfo m rcpModMs (Just $ MSMember $ memberId' m)
|
|
where
|
|
shouldIntroduceToMod :: GroupMember -> Bool
|
|
shouldIntroduceToMod mem =
|
|
memberCurrent mem
|
|
&& groupMemberId' mem /= groupMemberId' m
|
|
&& maxVersion (memberChatVRange mem) >= groupKnockingVersion
|
|
|
|
introduceToAll :: StoreCxt -> User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
introduceToAll cxt user gInfo@(GIK g _) m = do
|
|
(members, vector) <- withStore $ \db -> liftM2 (,) (liftIO $ getGroupMembers db cxt user g) (getMemberRelationsVector db m)
|
|
let recipients = filter (shouldIntroduce m vector) members
|
|
introduceMember user gInfo m recipients Nothing
|
|
|
|
introduceToRemaining :: StoreCxt -> User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
introduceToRemaining cxt user gInfo@(GIK g _) m = do
|
|
(members, vector) <- withStore $ \db -> liftM2 (,) (liftIO $ getGroupMembers db cxt user g) (getMemberRelationsVector db m)
|
|
let recipients = filter (shouldIntroduce m vector) members
|
|
introduceMember user gInfo m recipients Nothing
|
|
|
|
shouldIntroduce :: GroupMember -> ByteString -> GroupMember -> Bool
|
|
shouldIntroduce m vec mem =
|
|
memberCurrent mem
|
|
&& groupMemberId' mem /= groupMemberId' m
|
|
&& getRelation (indexInGroup mem) vec == MRNew
|
|
|
|
introduceMember :: User -> GroupInfoKeys -> GroupMember -> [GroupMember] -> Maybe MsgScope -> CM ()
|
|
introduceMember _ _ GroupMember {activeConn = Nothing} _ _ = throwChatError $ CEInternalError "member connection not active"
|
|
introduceMember user gInfo@(GIK g _) toMember@GroupMember {activeConn = Just conn} introduceToMembers msgScope = do
|
|
void . sendGroupMessage' user gInfo introduceToMembers $ XGrpMemNew (memberInfo g toMember) msgScope
|
|
sendIntroductions introduceToMembers
|
|
where
|
|
sendIntroductions reMembers = do
|
|
updateToMemberVector reMembers
|
|
updateReMembersVectors reMembers
|
|
shuffledReMembers <- liftIO $ shuffleMembers reMembers
|
|
let events = map (memberIntroEvt g) shuffledReMembers
|
|
forM_ (L.nonEmpty events) $ \events' ->
|
|
sendGroupMemberMessages user gInfo conn events'
|
|
updateToMemberVector :: [GroupMember] -> CM ()
|
|
updateToMemberVector reMembers = do
|
|
let relations = map (\GroupMember {indexInGroup} -> (indexInGroup, (IDReferencedIntroduced, MRIntroduced))) reMembers
|
|
withStore' $ \db -> setMemberVectorNewRelations db toMember relations
|
|
updateReMembersVectors :: [GroupMember] -> CM ()
|
|
updateReMembersVectors reMembers = do
|
|
let GroupMember {indexInGroup} = toMember
|
|
withStore' $ \db -> setMembersVectorsNewRelation db reMembers indexInGroup IDSubjectIntroduced MRIntroduced
|
|
shuffleMembers :: [GroupMember] -> IO [GroupMember]
|
|
shuffleMembers reMembers = do
|
|
let (admins, others) = partition isAdmin reMembers
|
|
(admPics, admNoPics) = partition hasPicture admins
|
|
(othPics, othNoPics) = partition hasPicture others
|
|
mconcat <$> mapM shuffle [admPics, admNoPics, othPics, othNoPics]
|
|
where
|
|
isAdmin GroupMember {memberRole} = memberRole >= GRAdmin
|
|
hasPicture GroupMember {memberProfile = LocalProfile {image}} = isJust image
|
|
|
|
memberIntroEvt :: GroupInfo -> GroupMember -> ChatMsgEvent 'Json
|
|
memberIntroEvt gInfo reMember =
|
|
let mInfo = memberInfo gInfo reMember
|
|
mRestrictions = memberRestrictions reMember
|
|
in XGrpMemIntro mInfo mRestrictions
|
|
|
|
-- Forward the saved owner-signed roster verbatim (reusing its signed shared_msg_id), then the
|
|
-- blob chunks, so the recipient verifies the owner signature.
|
|
serveRoster :: User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
serveRoster user gInfo@(GIK g _) member =
|
|
when (member `supportsVersion` groupRosterVersion) $ do
|
|
cxt <- chatStoreCxt
|
|
withStore' (\db -> getStoredGroupRoster db g) >>= \case
|
|
Just (ownerGMId, brokerTs, sm@SignedMsg {signedBody}, blob_, storedVer_) ->
|
|
case J.eitherDecodeStrict' signedBody :: Either String (ChatMessage 'Json) of
|
|
Left e -> logError $ "serveRoster: cannot decode saved roster message: " <> tshow e
|
|
Right chatMsg@ChatMessage {msgId} ->
|
|
withStore' (\db -> runExceptT $ getGroupMemberById db cxt user ownerGMId) >>= \case
|
|
Right owner -> do
|
|
let fwd = GrpMsgForward {fwdSender = FwdMember (memberId' owner) (memberShortenedName owner), fwdBrokerTs = brokerTs}
|
|
sendFwdMemberMessage member fwd (VMSigned MSSVerified sm chatMsg)
|
|
forM_ ((,) <$> msgId <*> blob_) $ \(sid, blob) ->
|
|
sendInlineBlobChunks user gInfo [member] sid blob
|
|
-- record the blob's own stored version as served, not roster_version (the gate): a delta can
|
|
-- advance the gate past the stored blob on a failed blob send, and recording the gate would
|
|
-- over-claim what this member was actually served, suppressing legitimate catch-up
|
|
forM_ storedVer_ $ \v -> withStore' $ \db -> setMemberRosterServedVersion db member v
|
|
Left e -> logError $ "serveRoster: roster owner not found: " <> tshow e
|
|
Nothing -> pure ()
|
|
|
|
-- Used in groups with relays to introduce moderators and above to a new member,
|
|
-- and to announce the new member to moderators and above.
|
|
-- This doesn't create introduction records in db, compared to above methods.
|
|
introduceInChannel :: StoreCxt -> User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
introduceInChannel _ _ _ GroupMember {activeConn = Nothing} = throwChatError $ CEInternalError "member connection not active"
|
|
introduceInChannel cxt user g@(GIK gInfo _) subscriber@GroupMember {activeConn = Just conn, indexInGroup = subscriberIdx} = do
|
|
(owners, adminsMods) <- withStore' $ \db ->
|
|
(,) <$> getGroupOwners db cxt user gInfo <*> getGroupAdminsMods db cxt user gInfo
|
|
let modMs = owners <> adminsMods
|
|
void $ sendGroupMessage' user g modMs $ XGrpMemNew (memberInfo gInfo subscriber) Nothing
|
|
withStore' $ \db ->
|
|
setMemberVectorNewRelations db subscriber [(indexInGroup m, (IDSubjectIntroduced, MRIntroduced)) | m <- modMs]
|
|
-- owner intros first so the joiner has the owner profile loaded before applying the saved roster (signed by the owner)
|
|
sendIntros owners
|
|
serveRoster user g subscriber
|
|
sendIntros adminsMods
|
|
withStore' $ \db ->
|
|
setMembersVectorsNewRelation db modMs subscriberIdx IDSubjectIntroduced MRIntroduced
|
|
where
|
|
sendIntros ms = forM_ (L.nonEmpty $ map (memberIntroEvt gInfo) ms) $ \evts ->
|
|
sendGroupMemberMessages user g conn evts
|
|
|
|
generateIncognitoProfile :: User -> IO Profile
|
|
generateIncognitoProfile User {profile = LocalProfile {peerType}} = generateRandomProfile peerType
|
|
|
|
userProfileInGroup :: User -> GroupInfo -> Maybe Profile -> Profile
|
|
userProfileInGroup user g = userProfileInGroup' user (Just g)
|
|
{-# INLINE userProfileInGroup #-}
|
|
|
|
-- Nothing group ⇒ no redaction (e.g. joining via a link with no group profile yet).
|
|
userProfileInGroup' :: User -> Maybe GroupInfo -> Maybe Profile -> Profile
|
|
userProfileInGroup' User {profile = p} mg incognitoProfile =
|
|
let p' = fromMaybe (fromLocalProfile p) incognitoProfile
|
|
in maybe p' (\g -> redactedMemberProfile g (membership g) p') mg
|
|
|
|
memberInfo :: GroupInfo -> GroupMember -> MemberInfo
|
|
memberInfo g m@GroupMember {memberId, memberRole, memberProfile, memberPubKey, activeConn, memberBadgeProof} =
|
|
MemberInfo
|
|
{ memberId,
|
|
memberRole,
|
|
v = ChatVersionRange . peerChatVRange <$> activeConn,
|
|
profile = (p :: Profile) {badge = mfilter (acceptedProof $ memberPresHeader g memberId memberPubKey) (unNoJSON memberBadgeProof <|> badge)},
|
|
memberKey = MemberKey <$> memberPubKey
|
|
}
|
|
where
|
|
p@Profile {badge} = redactedMemberProfile g m $ fromLocalProfile memberProfile
|
|
|
|
redactedMemberProfile :: GroupInfo -> GroupMember -> Profile -> Profile
|
|
redactedMemberProfile g m Profile {displayName, fullName, shortDescr, description, image, contactLink = lnk, peerType, badge, contactDomain} =
|
|
Profile {displayName, fullName, shortDescr = removeSimplexLink True =<< shortDescr, description = removeSimplexLink False =<< description, image, contactLink, preferences = Nothing, peerType, badge, contactDomain = redactedDomain}
|
|
where
|
|
contactLink = if allowSimplexLinks then lnk else Nothing
|
|
redactedDomain = if allowDirect then (\d -> d {proof = Nothing} :: SimplexDomainClaim) <$> contactDomain else Nothing
|
|
allowDirect = groupFeatureMemberAllowed SGFDirectMessages m g
|
|
allowSimplexLinks = groupFeatureMemberAllowed SGFSimplexLinks m g && allowDirect
|
|
removeSimplexLink dropOnLink s
|
|
| allowSimplexLinks = Just s
|
|
| otherwise = case parseMaybeMarkdownList s of
|
|
Nothing -> dropObfuscated
|
|
Just fts
|
|
| not (any ftIsSimplexLink fts) -> dropObfuscated
|
|
| dropOnLink || T.null (T.strip kept) || hasObfuscatedSimplexLink kept -> Nothing
|
|
| otherwise -> Just kept
|
|
where
|
|
kept = T.concat $ map (\(FormattedText _ t) -> t) $ filter (not . ftIsSimplexLink) fts
|
|
where
|
|
dropObfuscated = if hasObfuscatedSimplexLink s then Nothing else Just s
|
|
|
|
-- Roles carried by the roster; owners are on the link, not the roster.
|
|
isRosterRole :: GroupMemberRole -> Bool
|
|
isRosterRole r = r == GRMember || r == GRModerator || r == GRAdmin
|
|
|
|
isPrivilegedRole :: GroupMemberRole -> Bool
|
|
isPrivilegedRole r = r >= GRMember
|
|
|
|
-- Minimum role allowed to change a member's role from `from` to `to` (moderators only up to member; relay checked separately).
|
|
roleRequiredToChange :: GroupMemberRole -> GroupMemberRole -> GroupMemberRole
|
|
roleRequiredToChange from to
|
|
| from <= GRMember && to <= GRMember = GRModerator
|
|
| otherwise = maximum ([GRAdmin, from, to] :: [GroupMemberRole])
|
|
|
|
-- Drop non-privileged-role entries and de-duplicate by memberId, keeping the first.
|
|
-- Runs on the parsed roster blob.
|
|
validateGroupRoster :: [RosterMember] -> [RosterMember]
|
|
validateGroupRoster entries =
|
|
dedup S.empty $ filter (\RosterMember {role} -> isRosterRole role) entries
|
|
where
|
|
dedup _ [] = []
|
|
dedup seen (rm@RosterMember {memberId} : rms)
|
|
| memberId `S.member` seen = dedup seen rms
|
|
| otherwise = rm : dedup (S.insert memberId seen) rms
|
|
|
|
-- Privileged members without a known key are skipped (recipients can't verify them).
|
|
buildGroupRoster :: [GroupMember] -> [RosterMember]
|
|
buildGroupRoster mods = take maxGroupRosterSize $ mapMaybe rosterMember mods
|
|
where
|
|
rosterMember GroupMember {memberId, memberPubKey, memberRole}
|
|
| isRosterRole memberRole = (\k -> RosterMember {memberId, key = MemberKey k, role = memberRole, privileges = 0}) <$> memberPubKey
|
|
| otherwise = Nothing
|
|
|
|
sendHistory :: User -> GroupInfo -> GroupMember -> CM ()
|
|
sendHistory _ _ GroupMember {activeConn = Nothing} = throwChatError $ CEInternalError "member connection not active"
|
|
sendHistory user gInfo@GroupInfo {membership} m@GroupMember {activeConn = Just conn} = do
|
|
(errs, items) <- partitionEithers <$> withStore' (\db -> getGroupHistoryItems db user gInfo m 100)
|
|
(errs', fwdMsgsByItem) <- partitionEithers <$> mapM (tryAllErrors . itemForwardMsgs) items
|
|
let errors = map ChatErrorStore errs <> errs'
|
|
unless (null errors) $ toView $ CEvtChatErrors errors
|
|
-- signed items keep the author's original bytes/signature, unsigned are re-encoded; the welcome message
|
|
-- (regular groups only; never channels) is an authored element -- all batch together in order.
|
|
let fwdEls = map (uncurry encodeFwdElement) (concat fwdMsgsByItem)
|
|
welcomeEl <- welcomeElement
|
|
let (batches, dropped) = batchElements maxForwardBatchLength (fwdEls <> maybe [] (: []) welcomeEl)
|
|
when (dropped > 0) $ toView $ CEvtChatErrors [ChatError $ CEInternalError ("sendHistory: dropped " <> show dropped <> " oversized history messages")]
|
|
forM_ batches $ \body ->
|
|
void $ withAgent $ \a -> sendMessages a [(aConnId conn, PQEncOff, MsgFlags False, VRValue Nothing body)]
|
|
where
|
|
welcomeElement :: CM (Maybe ByteString)
|
|
welcomeElement = case descrEvent_ of
|
|
Just descr ->
|
|
withStore' (\db -> getMemberJoinRequest db user gInfo m) >>= \case
|
|
Just (_, Just _welcomeMsgId) -> pure Nothing
|
|
_ -> do
|
|
vr <- chatVersionRange
|
|
sharedMsgId <- SharedMsgId <$> drgRandomBytes 24
|
|
case encodeChatMessage maxEncodedMsgLength ChatMessage {chatVRange = vr, msgId = Just sharedMsgId, chatMsgEvent = descr} of
|
|
ECMEncoded body -> pure $ Just (encodeBatchElement Nothing body)
|
|
ECMLarge -> Nothing <$ toView (CEvtChatErrors [ChatError $ CEInternalError "sendHistory: welcome message too large"])
|
|
Nothing -> pure Nothing
|
|
descrEvent_ :: Maybe (ChatMsgEvent 'Json)
|
|
descrEvent_
|
|
-- in channels sendHistory runs on the relay, which cannot author XMsgNew (GRRelay < GRObserver);
|
|
-- the welcome message reaches new members via the channel link data instead
|
|
| useRelays' gInfo = Nothing
|
|
| otherwise = do
|
|
let GroupInfo {groupProfile = GroupProfile {description}} = gInfo
|
|
fmap (\descr -> XMsgNew $ mcSimple (MCText descr)) description
|
|
itemForwardMsgs :: (CChatItem 'CTGroup, (Maybe SignedMsg, Maybe GroupMemberId)) -> CM [(GrpMsgForward, VerifiedMsg 'Json)]
|
|
itemForwardMsgs (cci, (signedMsg_, signedByGMId_)) = case cci of
|
|
(CChatItem SMDRcv ci@ChatItem {content = CIRcvMsgContent mc, file})
|
|
| not (maybe False blockedByAdmin (chatItemRcvFromMember ci)) -> do
|
|
fInvDescr_ <- join <$> forM file getRcvFileInvDescr
|
|
-- channel items carry no from-member; a signed one falls back to the stored author (verified attribution)
|
|
member_ <- maybe (resolveAuthor signedByGMId_) (pure . Just) (chatItemRcvFromMember ci)
|
|
processContentItem member_ ci mc fInvDescr_
|
|
| otherwise -> pure []
|
|
(CChatItem SMDSnd ci@ChatItem {content = CISndMsgContent mc, file, meta = CIMeta {showGroupAsSender}}) -> do
|
|
fInvDescr_ <- join <$> forM file getSndFileInvDescr
|
|
let member_ = if showGroupAsSender && isNothing signedMsg_ then Nothing else Just membership
|
|
processContentItem member_ ci mc fInvDescr_
|
|
_ -> pure []
|
|
where
|
|
resolveAuthor :: Maybe GroupMemberId -> CM (Maybe GroupMember)
|
|
resolveAuthor Nothing = pure Nothing
|
|
resolveAuthor (Just gmId) = do
|
|
cxt <- chatStoreCxt
|
|
eitherToMaybe <$> withStore' (\db -> runExceptT $ getGroupMemberById db cxt user gmId)
|
|
getRcvFileInvDescr :: CIFile 'MDRcv -> CM (Maybe HistoryFile)
|
|
getRcvFileInvDescr ciFile@CIFile {fileId, fileProtocol, fileStatus, fileExpires} = do
|
|
expired <- fileExpired fileExpires
|
|
if fileProtocol /= FPXFTP || fileStatus == CIFSRcvCancelled || expired
|
|
then pure Nothing
|
|
else do
|
|
(rfd, (invBadge, descrBadge)) <- withStore $ \db -> do
|
|
rfd <- getRcvFileDescrByRcvFileId db fileId
|
|
(rfd,) <$> liftIO (getFileBadgeProofs db fileId)
|
|
pure $ invCompleteDescr ciFile rfd invBadge descrBadge
|
|
getSndFileInvDescr :: CIFile 'MDSnd -> CM (Maybe HistoryFile)
|
|
getSndFileInvDescr ciFile@CIFile {fileId, fileProtocol, fileStatus, fileExpires} = do
|
|
expired <- fileExpired fileExpires
|
|
if fileProtocol /= FPXFTP || fileStatus == CIFSSndCancelled || expired
|
|
then pure Nothing
|
|
else do
|
|
-- can also lookup in extra_xftp_file_descriptions, though it can be empty;
|
|
-- would be best if snd file had a single rcv description for all members saved in files table
|
|
now <- liftIO getCurrentTime
|
|
(rfd, (invBadge, descrBadge)) <- withStore $ \db -> do
|
|
rfd <- getRcvFileDescrBySndFileId db fileId
|
|
(rfd,) <$> liftIO (getFileBadgeProofs db fileId)
|
|
-- a signed item forwards the author's original bytes, so its invitation proof cannot be replaced
|
|
(invBadge', descrBadge') <-
|
|
if isNothing signedMsg_ && ownBadgeActive && (staleBadge now invBadge || staleBadge now descrBadge)
|
|
then refreshSndBadges fileId invBadge descrBadge
|
|
else pure (invBadge, descrBadge)
|
|
pure $ invCompleteDescr ciFile rfd invBadge' descrBadge'
|
|
staleBadge :: UTCTime -> Maybe BadgeProof -> Bool
|
|
staleBadge now = \case
|
|
Just BadgeProof {badgeInfo = BadgeInfo {badgeExpiry}} -> addUTCTime badgeSndGraceInterval badgeExpiry < now
|
|
Nothing -> False
|
|
ownBadgeActive :: Bool
|
|
ownBadgeActive = maybe False ((BSActive ==) . localBadgeStatus) localBadge
|
|
where
|
|
User {profile = LocalProfile {localBadge}} = user
|
|
-- both proofs are made with the same badge, and are re-made with the current badge over the stored headers
|
|
refreshSndBadges :: FileTransferId -> Maybe BadgeProof -> Maybe BadgeProof -> CM (Maybe BadgeProof, Maybe BadgeProof)
|
|
refreshSndBadges fileId invBadge descrBadge = do
|
|
invBadge' <- mapM reProve invBadge
|
|
descrBadge' <- mapM reProve descrBadge
|
|
withStore' $ \db -> do
|
|
forM_ invBadge' $ createFileBadgeProof db fileId BPKInvitation
|
|
forM_ descrBadge' $ createFileBadgeProof db fileId BPKDescription
|
|
pure (invBadge', descrBadge')
|
|
where
|
|
reProve badge@BadgeProof {presHeader} = fromMaybe badge <$> sndBadgeProof_ user presHeader
|
|
fileExpired :: Maybe UTCTime -> CM Bool
|
|
fileExpired fileExpires = do
|
|
ttl <- asks $ rcvFilesTTL . agentConfig . config
|
|
now <- liftIO getCurrentTime
|
|
pure $ fromMaybe (addUTCTime ttl $ chatItemTs cci) fileExpires < now
|
|
invCompleteDescr :: CIFile d -> RcvFileDescr -> Maybe BadgeProof -> Maybe BadgeProof -> Maybe HistoryFile
|
|
invCompleteDescr CIFile {fileName, fileSize, fileExpires} RcvFileDescr {fileDescrText, fileDescrComplete} invBadge descrBadge
|
|
| fileDescrComplete =
|
|
let fInv = (xftpFileInvitation fileName fileSize dummyFileDescr :: FileInvitation) {fileBadge = invBadge}
|
|
in Just (fInv, fileDescrText, fileExpires, descrBadge)
|
|
| otherwise = Nothing
|
|
processContentItem :: Maybe GroupMember -> ChatItem 'CTGroup d -> MsgContent -> Maybe HistoryFile -> CM [(GrpMsgForward, VerifiedMsg 'Json)]
|
|
processContentItem member_ ChatItem {formattedText, meta, quotedItem, mentions} mc fInvDescr_ =
|
|
if isNothing fInvDescr_ && not (msgContentHasText mc)
|
|
then pure []
|
|
else do
|
|
let CIMeta {itemTs, itemSharedMsgId, itemTimed, showGroupAsSender} = meta
|
|
quotedItemId_ = quoteItemId =<< quotedItem
|
|
fInv_ = (\(fInv, _, _, _) -> fInv) <$> fInvDescr_
|
|
(mc', _, mentions') = updatedMentionNames mc formattedText mentions
|
|
mentions'' = M.map (\CIMention {memberId} -> MsgMention {memberId}) mentions'
|
|
-- for channel messages default chat version range to membership range
|
|
senderVRange = maybe (memberChatVRange' membership) memberChatVRange' member_
|
|
-- member_ is Nothing only for as-group unsigned items -> FwdChannel; otherwise attribute to the member
|
|
-- (the author for signed as-group items), so the recipient can reconstruct the binding and verify
|
|
fwdSender = maybe FwdChannel (\am -> FwdMember (memberId' am) (memberShortenedName am)) member_
|
|
fwd = GrpMsgForward {fwdSender, fwdBrokerTs = itemTs}
|
|
-- signed items forward the author's original bytes so the signature stays valid; unsigned re-encode current content
|
|
contentVM <- case signedMsg_ of
|
|
Just sm@SignedMsg {signedBody}
|
|
| Right chatMsg <- (J.eitherDecodeStrict' signedBody :: Either String (ChatMessage 'Json)) ->
|
|
pure $ VMSigned MSSVerified sm chatMsg
|
|
_ -> do
|
|
-- TODO [knocking] send history to other scopes too?
|
|
(chatMsgEvent, _) <- withStore $ \db -> prepareGroupMsg db user gInfo Nothing showGroupAsSender mc' mentions'' quotedItemId_ Nothing fInv_ itemTimed False
|
|
pure $ VMUnsigned ChatMessage {chatVRange = senderVRange, msgId = itemSharedMsgId, chatMsgEvent}
|
|
fileDescrEvents <- case (fInvDescr_, itemSharedMsgId) of
|
|
(Just (_, fileDescrText, fileExpires, descrBadge), Just msgId) -> do
|
|
partSize <- asks $ xftpDescrPartSize . config
|
|
let parts = splitFileDescr partSize (maybe partSize (const badgeDescrPartSize) descrBadge) fileDescrText
|
|
pure . L.toList $ L.map (\fd@FileDescr {fileDescrComplete} -> XMsgFileDescr msgId fd fileExpires (if fileDescrComplete then descrBadge else Nothing)) parts
|
|
_ -> pure []
|
|
let fileDescrVMs = map (VMUnsigned . ChatMessage senderVRange Nothing) fileDescrEvents
|
|
pure $ map ((,) fwd) (contentVM : fileDescrVMs)
|
|
|
|
memberShortenedName :: GroupMember -> ContactName
|
|
memberShortenedName GroupMember {memberProfile = LocalProfile {displayName}} = fwdMemberName displayName
|
|
|
|
-- the description proof travels on the last part, so that part leaves room for it
|
|
badgeDescrPartSize :: Int
|
|
badgeDescrPartSize = 13500
|
|
|
|
splitFileDescr :: Int -> Int -> RcvFileDescrText -> NonEmpty FileDescr
|
|
splitFileDescr partSize lastSize rfdText = splitParts 1 rfdText
|
|
where
|
|
splitParts partNo remText =
|
|
let n = T.length remText
|
|
(part, rest) = T.splitAt (if n <= lastSize then n else if n <= partSize then lastSize else partSize) remText
|
|
complete = T.null rest
|
|
fileDescr = FileDescr {fileDescrText = part, fileDescrPartNo = partNo, fileDescrComplete = complete}
|
|
in if complete
|
|
then fileDescr :| []
|
|
else fileDescr <| splitParts (partNo + 1) rest
|
|
|
|
setGroupLinkData' :: NetworkRequestMode -> User -> GroupInfoKeys -> CM (Maybe GroupLink)
|
|
setGroupLinkData' nm user gInfo@(GIK g _) =
|
|
withFastStore' (\db -> runExceptT $ getGroupLink db user g) >>= \case
|
|
Right gLink@GroupLink {shortLinkDataSet}
|
|
| shortLinkDataSet -> Just <$> setGroupLinkData nm user gInfo gLink
|
|
_ -> pure Nothing
|
|
|
|
setGroupLinkData :: NetworkRequestMode -> User -> GroupInfoKeys -> GroupLink -> CM GroupLink
|
|
setGroupLinkData nm user g@(GIK gInfo _) gLink = do
|
|
cxt <- chatStoreCxt
|
|
(conn, groupRelays) <- withFastStore $ \db ->
|
|
(,) <$> getGroupLinkConnection db cxt user gInfo <*> liftIO (getPublishableGroupRelays db cxt user gInfo)
|
|
let (userLinkData, crClientData) = groupLinkData g gLink groupRelays
|
|
linkType = if useRelays' gInfo then CCTChannel else CCTGroup
|
|
sLnk <- shortenShortLink' . setShortLinkType_ linkType =<< withAgent (\a -> setConnShortLink a nm (aConnId conn) SCMContact userLinkData (Just crClientData) False Nothing)
|
|
withFastStore' $ \db -> setGroupLinkShortLink db gLink sLnk
|
|
|
|
setGroupLinkDataAsync :: User -> GroupInfoKeys -> GroupLink -> CM ()
|
|
setGroupLinkDataAsync user g@(GIK gInfo _) gLink = do
|
|
cxt <- chatStoreCxt
|
|
(conn, groupRelays) <- withStore $ \db ->
|
|
(,) <$> getGroupLinkConnection db cxt user gInfo <*> liftIO (getPublishableGroupRelays db cxt user gInfo)
|
|
let (userLinkData, crClientData) = groupLinkData g gLink groupRelays
|
|
setAgentConnShortLinkAsync user conn userLinkData (Just crClientData)
|
|
|
|
connectToRelayAsync :: User -> GroupInfo -> ShortLinkContact -> CM ()
|
|
connectToRelayAsync user gInfo relayLink = do
|
|
cxt <- chatStoreCxt
|
|
gVar <- asks random
|
|
relayMember@GroupMember {activeConn} <- withFastStore $ \db -> getCreateRelayForMember db cxt gVar user gInfo relayLink
|
|
case activeConn of
|
|
Just _ -> pure ()
|
|
Nothing -> do
|
|
subMode <- chatReadVar subscriptionMode
|
|
newConnIds <- getAgentConnShortLinkAsync user CFGetRelayDataJoin Nothing relayLink
|
|
withFastStore' $ \db -> createRelayMemberConnectionAsync db user gInfo relayMember relayLink newConnIds subMode
|
|
|
|
updatePublicGroupData :: User -> GroupInfo -> GroupKeys -> CM GroupInfo
|
|
updatePublicGroupData user gInfo gks
|
|
| useRelays' gInfo && memberRole' (membership gInfo) == GROwner = do
|
|
cxt <- chatStoreCxt
|
|
(gInfo', gLink) <- withStore $ \db -> do
|
|
gInfo' <- updatePublicMemberCount db cxt user gInfo
|
|
gLink <- getGroupLink db user gInfo'
|
|
pure (gInfo', gLink)
|
|
setGroupLinkDataAsync user (GIK gInfo' gks) gLink
|
|
pure gInfo'
|
|
| useRelays' gInfo && isRelay (membership gInfo) = do
|
|
cxt <- chatStoreCxt
|
|
withStore $ \db -> updatePublicMemberCount db cxt user gInfo
|
|
| otherwise = pure gInfo
|
|
|
|
-- must not resolve names here: a background link-data refresh would leak channel membership to the resolver
|
|
updateGroupFromLinkData :: User -> GroupInfo -> GroupShortLinkData -> Maybe SimplexDomain -> CM (GroupInfo, Bool, ([ContactId], [GroupId]))
|
|
updateGroupFromLinkData user gInfo@GroupInfo {groupProfile = p, groupSummary = GroupSummary {publicMemberCount = localCount}} GroupShortLinkData {groupProfile, publicGroupData} resolvedDomain_
|
|
| profileChanged || countChanged || verifyResolved = do
|
|
cxt <- chatStoreCxt
|
|
(gInfo', moved) <- withStore $ \db -> do
|
|
g <- if profileChanged then updateGroupProfile db user gInfo groupProfile else pure gInfo
|
|
g' <- case publicGroupData of
|
|
Just PublicGroupData {publicMemberCount} | countChanged ->
|
|
setPublicMemberCount db cxt user g publicMemberCount
|
|
_ -> pure g
|
|
if verifyResolved
|
|
then liftIO $ do
|
|
g'' <- setGroupDomainVerified db user g' True
|
|
(g'',) <$> setOtherNameChatsMoved db user (GroupChat g'' Nothing)
|
|
else pure (g', ([], []))
|
|
nameMovedToView user moved
|
|
pure (gInfo', profileChanged, moved)
|
|
| otherwise = pure (gInfo, False, ([], []))
|
|
where
|
|
profileChanged = p /= groupProfile
|
|
countChanged = case publicGroupData of
|
|
Just PublicGroupData {publicMemberCount} -> Just publicMemberCount /= localCount
|
|
_ -> False
|
|
newClaim = groupClaim groupProfile
|
|
verifyResolved = isJust resolvedDomain_ && resolvedDomain_ == newClaim
|
|
|
|
groupClaim :: GroupProfile -> Maybe SimplexDomain
|
|
groupClaim GroupProfile {publicGroup} = claimDomain <$> (publicGroup >>= publicGroupAccess >>= groupDomainClaim)
|
|
|
|
updateContactFromLinkData :: User -> Contact -> ProofPresHeader -> Profile -> CM (Contact, ([ContactId], [GroupId]))
|
|
updateContactFromLinkData user ct@Contact {profile = profile@LocalProfile {contactDomain = prevClaim, contactDomainVerified}} presHeader linkProfile@Profile {contactDomain = newClaim}
|
|
| profileChanged || verifyChanged = do
|
|
cxt <- chatStoreCxt
|
|
r@(_, moved) <- withFastStore $ \db -> do
|
|
ct' <- updateContactProfile db cxt user ct (Just presHeader) linkProfile
|
|
if verifyChanged
|
|
then liftIO $ do
|
|
ct'' <- setContactDomainVerified db user ct' True
|
|
(ct'',) <$> setOtherNameChatsMoved db user (DirectChat ct'')
|
|
else pure (ct', ([], []))
|
|
nameMovedToView user moved
|
|
pure r
|
|
| otherwise = pure (ct, ([], []))
|
|
where
|
|
profileChanged = fromLocalProfile profile /= linkProfile
|
|
claimChanged = (claimDomain <$> prevClaim) /= (claimDomain <$> newClaim)
|
|
verifyChanged = contactDomainVerified /= Just DVVerified || claimChanged
|
|
|
|
setOtherNameChatsMoved :: DB.Connection -> User -> ChatInfo c -> IO ([ContactId], [GroupId])
|
|
setOtherNameChatsMoved db user = \case
|
|
DirectChat Contact {contactId, profile = LocalProfile {contactDomain = Just d}} -> setMoved (SimplexNameInfo NTContact $ claimDomain d) (Just contactId) Nothing
|
|
GroupChat GroupInfo {groupId, businessChat = Just BusinessChatInfo {businessDomain = Just d}} _ -> setMoved (SimplexNameInfo NTContact $ claimDomain d) Nothing (Just groupId)
|
|
GroupChat GroupInfo {groupId, businessChat = Nothing, groupProfile} _ | Just d <- groupClaim groupProfile -> setMoved (SimplexNameInfo NTPublicGroup d) Nothing (Just groupId)
|
|
_ -> pure ([], [])
|
|
where
|
|
setMoved ni@SimplexNameInfo {nameType, nameDomain} ctId_ gId_ =
|
|
(,)
|
|
<$> (if nameType == NTContact then setNameContactsMoved db user nameDomain ctId_ else pure [])
|
|
<*> setNameGroupsMoved db user ni gId_
|
|
|
|
nameMovedToView :: User -> ([ContactId], [GroupId]) -> CM ()
|
|
nameMovedToView user (ctIds, gIds) = unless (null ctIds && null gIds) $ toView $ CEvtNameMoved user ctIds gIds
|
|
|
|
-- TODO [relays] owner: set owners on updating link data (multi-owner)
|
|
groupLinkData :: GroupInfoKeys -> GroupLink -> [GroupRelay] -> (UserConnLinkData 'CMContact, CRClientData)
|
|
groupLinkData (GIK gInfo@GroupInfo {groupProfile, groupSummary = GroupSummary {publicMemberCount}, membership = GroupMember {memberId}} gks) GroupLink {groupLinkId} groupRelays =
|
|
let direct = not $ useRelays' gInfo
|
|
relays = mapMaybe (\GroupRelay {relayLink} -> relayLink) groupRelays
|
|
publicGroupData_ = PublicGroupData <$> publicMemberCount
|
|
userData = encodeShortLinkData $ GroupShortLinkData {groupProfile, publicGroupData = publicGroupData_}
|
|
owners = case gks of
|
|
GKPublicGroup {groupRootKey = GRKPrivate rootPrivKey, memberPrivKey} ->
|
|
let ownerId = unMemberId memberId
|
|
ownerKey = C.publicKey memberPrivKey
|
|
authOwnerSig = C.sign' rootPrivKey (ownerId <> C.encodePubKey ownerKey)
|
|
in [OwnerAuth {ownerId, ownerKey, authOwnerSig}]
|
|
_ -> []
|
|
userLinkData = UserContactLinkData UserContactData {direct, owners, relays, userData, ratchetKeys = Nothing}
|
|
crClientData = encodeJSON $ CRDataGroup groupLinkId
|
|
in (userLinkData, crClientData)
|
|
|
|
restoreShortLink' :: ConnShortLink m -> CM (ConnShortLink m)
|
|
restoreShortLink' l = (`restoreShortLink` l) <$> asks (shortLinkPresetServers . config)
|
|
|
|
getShortLinkConnReq' :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m)
|
|
getShortLinkConnReq' nm user l = do
|
|
l' <- restoreShortLink' l
|
|
withAgent $ \a -> getConnShortLink a nm (aUserId user) l'
|
|
|
|
getShortLinkConnReq :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m)
|
|
getShortLinkConnReq nm user l = do
|
|
r@(_, cData, _) <- getShortLinkConnReq' nm user l
|
|
case cData of
|
|
ContactLinkData _ UserContactData {direct, relays}
|
|
| not direct && null relays -> throwChatError CEUnsupportedConnReq
|
|
_ -> pure ()
|
|
pure r
|
|
|
|
encodeShortLinkData :: J.ToJSON a => a -> UserLinkData
|
|
encodeShortLinkData d =
|
|
let s = LB.toStrict $ J.encode d
|
|
-- 10kb size limit for compression to be used is based on 13784 limit for link data
|
|
-- and the space reserved for the other fields in ConnLinkData encoding (most of these fields are currently unused).
|
|
s'
|
|
| B.length s > 10240 = B.cons 'X' $ Z1.compress compressionLevel s
|
|
| otherwise = s
|
|
in UserLinkData s'
|
|
|
|
decodeLinkUserData :: J.FromJSON a => ConnLinkData c -> IO (Maybe a)
|
|
decodeLinkUserData cData
|
|
| B.null s = pure Nothing
|
|
| B.head s == 'X' = case limitDecompress' maxDecompressedMsgLength $ B.drop 1 s of
|
|
Left e -> Nothing <$ logError ("Error decompressing link data: " <> tshow e)
|
|
Right s' -> decode s'
|
|
| otherwise = decode s
|
|
where
|
|
decode s' = case J.eitherDecodeStrict s' of
|
|
Right d -> pure $ Just d
|
|
Left e -> Nothing <$ logError ("Error decoding link data: " <> tshow e)
|
|
s = linkUserData' cData
|
|
|
|
shortenShortLink' :: ConnShortLink m -> CM (ConnShortLink m)
|
|
shortenShortLink' l = (`shortenShortLink` l) <$> asks (shortLinkPresetServers . config)
|
|
|
|
shortenCreatedLink :: CreatedConnLink m -> CM (CreatedConnLink m)
|
|
shortenCreatedLink (CCLink cReq sLnk) = CCLink cReq <$> mapM shortenShortLink' sLnk
|
|
|
|
deleteGroupLink' :: User -> GroupInfo -> CM ()
|
|
deleteGroupLink' user gInfo = do
|
|
cxt <- chatStoreCxt
|
|
conn <- withStore $ \db -> getGroupLinkConnection db cxt user gInfo
|
|
deleteGroupLink_ user gInfo conn
|
|
|
|
deleteGroupLinkIfExists :: User -> GroupInfo -> CM ()
|
|
deleteGroupLinkIfExists user gInfo = do
|
|
cxt <- chatStoreCxt
|
|
conn_ <- eitherToMaybe <$> withStore' (\db -> runExceptT $ getGroupLinkConnection db cxt user gInfo)
|
|
mapM_ (deleteGroupLink_ user gInfo) conn_
|
|
|
|
deleteGroupLink_ :: User -> GroupInfo -> Connection -> CM ()
|
|
deleteGroupLink_ user gInfo conn = do
|
|
deleteAgentConnectionAsync $ aConnId conn
|
|
withStore' $ \db -> deleteGroupLink db user gInfo
|
|
|
|
startProximateTimedItemThread :: User -> (ChatRef, ChatItemId) -> UTCTime -> CM ()
|
|
startProximateTimedItemThread user itemRef deleteAt = do
|
|
interval <- asks (cleanupManagerInterval . config)
|
|
ts <- liftIO getCurrentTime
|
|
when (diffUTCTime deleteAt ts <= interval) $
|
|
startTimedItemThread user itemRef deleteAt
|
|
|
|
startTimedItemThread :: User -> (ChatRef, ChatItemId) -> UTCTime -> CM ()
|
|
startTimedItemThread user itemRef deleteAt = do
|
|
itemThreads <- asks timedItemThreads
|
|
threadTVar_ <- atomically $ do
|
|
exists <- TM.member itemRef itemThreads
|
|
if not exists
|
|
then do
|
|
threadTVar <- newTVar Nothing
|
|
TM.insert itemRef threadTVar itemThreads
|
|
pure $ Just threadTVar
|
|
else pure Nothing
|
|
forM_ threadTVar_ $ \threadTVar -> do
|
|
tId <- mkWeakThreadId =<< deleteTimedItem user itemRef deleteAt `forkFinally` const (atomically $ TM.delete itemRef itemThreads)
|
|
atomically $ writeTVar threadTVar (Just tId)
|
|
|
|
deleteTimedItem :: User -> (ChatRef, ChatItemId) -> UTCTime -> CM ()
|
|
deleteTimedItem user (ChatRef cType chatId scope, itemId) deleteAt = do
|
|
ts <- liftIO getCurrentTime
|
|
liftIO $ threadDelay' $ diffToMicroseconds $ diffUTCTime deleteAt ts
|
|
lift waitChatStartedAndActivated
|
|
cxt <- chatStoreCxt
|
|
case cType of
|
|
CTDirect -> do
|
|
(ct, ci) <- withStore $ \db -> (,) <$> getContact db cxt user chatId <*> getDirectChatItem db user chatId itemId
|
|
deletions <- deleteDirectCIs user ct [ci]
|
|
toView $ CEvtChatItemsDeleted user deletions True True
|
|
CTGroup -> do
|
|
(gInfo, ci) <- withStore $ \db -> (,) <$> getGroupInfo db cxt user chatId <*> getGroupChatItem db user chatId itemId
|
|
deletedTs <- liftIO getCurrentTime
|
|
chatScopeInfo <- mapM (getChatScopeInfo cxt user) scope
|
|
deletions <- deleteGroupCIs user gInfo chatScopeInfo [ci] Nothing deletedTs
|
|
toView $ CEvtChatItemsDeleted user deletions True True
|
|
_ -> eToView $ ChatError $ CEInternalError "bad deleteTimedItem cType"
|
|
|
|
startUpdatedTimedItemThread :: User -> ChatRef -> ChatItem c d -> ChatItem c d -> CM ()
|
|
startUpdatedTimedItemThread user chatRef ci ci' =
|
|
case (chatItemTimed ci >>= timedDeleteAt', chatItemTimed ci' >>= timedDeleteAt') of
|
|
(Nothing, Just deleteAt') ->
|
|
startProximateTimedItemThread user (chatRef, chatItemId' ci') deleteAt'
|
|
_ -> pure ()
|
|
|
|
metaBrokerTs :: MsgMeta -> UTCTime
|
|
metaBrokerTs MsgMeta {broker = (_, brokerTs)} = brokerTs
|
|
|
|
createContactPQSndItem :: User -> Contact -> Connection -> PQEncryption -> CM (Contact, Connection)
|
|
createContactPQSndItem user ct conn@Connection {pqSndEnabled} pqSndEnabled' =
|
|
flip catchAllErrors (const $ pure (ct, conn)) $ case (pqSndEnabled, pqSndEnabled') of
|
|
(Just b, b') | b' /= b -> createPQItem $ CISndConnEvent (SCEPqEnabled pqSndEnabled')
|
|
(Nothing, PQEncOn) -> createPQItem $ CISndDirectE2EEInfo (e2eInfoEncrypted $ Just pqSndEnabled')
|
|
_ -> pure (ct, conn)
|
|
where
|
|
createPQItem ciContent = do
|
|
let conn' = conn {pqSndEnabled = Just pqSndEnabled'} :: Connection
|
|
ct' = ct {activeConn = Just conn'} :: Contact
|
|
when (contactPQEnabled ct /= contactPQEnabled ct') $ do
|
|
createInternalChatItem user (CDDirectSnd ct') ciContent Nothing
|
|
toView $ CEvtContactPQEnabled user ct' pqSndEnabled'
|
|
pure (ct', conn')
|
|
|
|
updateContactPQRcv :: User -> Contact -> Connection -> PQEncryption -> CM (Contact, Connection)
|
|
updateContactPQRcv user ct conn@Connection {connId, pqRcvEnabled} pqRcvEnabled' =
|
|
flip catchAllErrors (const $ pure (ct, conn)) $ case (pqRcvEnabled, pqRcvEnabled') of
|
|
(Just b, b') | b' /= b -> updatePQ $ CIRcvConnEvent (RCEPqEnabled pqRcvEnabled')
|
|
(Nothing, PQEncOn) -> updatePQ $ CIRcvDirectE2EEInfo (e2eInfoEncrypted $ Just pqRcvEnabled')
|
|
_ -> pure (ct, conn)
|
|
where
|
|
updatePQ ciContent = do
|
|
withStore' $ \db -> updateConnPQRcvEnabled db connId pqRcvEnabled'
|
|
let conn' = conn {pqRcvEnabled = Just pqRcvEnabled'} :: Connection
|
|
ct' = ct {activeConn = Just conn'} :: Contact
|
|
when (contactPQEnabled ct /= contactPQEnabled ct') $ do
|
|
createInternalChatItem user (CDDirectRcv ct') ciContent Nothing
|
|
toView $ CEvtContactPQEnabled user ct' pqRcvEnabled'
|
|
pure (ct', conn')
|
|
|
|
updatePeerChatVRange :: Connection -> VersionRangeChat -> CM Connection
|
|
updatePeerChatVRange conn@Connection {connId, connChatVersion = v, peerChatVRange, connType, pqSupport, pqEncryption} msgVRange = do
|
|
v' <- lift $ upgradedConnVersion v msgVRange
|
|
conn' <-
|
|
if msgVRange /= peerChatVRange || v' /= v
|
|
then do
|
|
withStore' $ \db -> setPeerChatVRange db connId v' msgVRange
|
|
pure conn {connChatVersion = v', peerChatVRange = msgVRange}
|
|
else pure conn
|
|
-- TODO v6.0 remove/review: for contacts only version upgrade should trigger enabling PQ support/encryption
|
|
if connType == ConnContact && (pqSupport /= PQSupportOn || pqEncryption /= PQEncOn)
|
|
then do
|
|
withStore' $ \db -> updateConnSupportPQ db connId PQSupportOn PQEncOn
|
|
pure conn' {pqSupport = PQSupportOn, pqEncryption = PQEncOn}
|
|
else pure conn'
|
|
|
|
updateMemberChatVRange :: GroupMember -> Connection -> VersionRangeChat -> CM (GroupMember, Connection)
|
|
updateMemberChatVRange mem@GroupMember {groupMemberId, memberChatVRange} conn@Connection {connId, connChatVersion = v, peerChatVRange} msgVRange = do
|
|
v' <- lift $ upgradedConnVersion v msgVRange
|
|
if msgVRange /= peerChatVRange || v' /= v || msgVRange /= memberChatVRange
|
|
then do
|
|
withStore' $ \db -> do
|
|
setPeerChatVRange db connId v' msgVRange
|
|
setMemberChatVRange db groupMemberId msgVRange
|
|
let conn' = conn {connChatVersion = v', peerChatVRange = msgVRange}
|
|
pure (mem {memberChatVRange = msgVRange, activeConn = Just conn'}, conn')
|
|
else pure (mem, conn)
|
|
|
|
upgradedConnVersion :: VersionChat -> VersionRangeChat -> CM' VersionChat
|
|
upgradedConnVersion v peerVR = do
|
|
vr <- chatVersionRange'
|
|
-- don't allow reducing agreed connection version
|
|
pure $ maybe v (\(Compatible v') -> max v v') $ vr `compatibleVersion` peerVR
|
|
|
|
parseFileDescription :: FilePartyI p => Text -> CM (ValidFileDescription p)
|
|
parseFileDescription =
|
|
liftEither . first (ChatError . CEInvalidFileDescription) . (strDecode . encodeUtf8)
|
|
|
|
-- | Unique XFTP servers hosting the file's chunks, parsed from a stored file description.
|
|
fileDescrServers :: ValidFileDescription p -> [XFTPServer]
|
|
fileDescrServers (FD.ValidFileDescription FD.FileDescription {chunks}) =
|
|
S.toList $ S.fromList $ concatMap (\FD.FileChunk {replicas} -> map (\FD.FileChunkReplica {server} -> server) replicas) chunks
|
|
|
|
-- | XFTP servers the file's data chunks were uploaded to (sender's servers for sent items,
|
|
-- the same servers via the recipient description for received items).
|
|
-- Returns [] for non-XFTP/inline files or when no description is available; never fails the caller.
|
|
getChatItemFileServers :: User -> SMsgDirection d -> ChatItem c d -> CM [XFTPServer]
|
|
getChatItemFileServers user dir ci = case ci of
|
|
ChatItem {file = Just CIFile {fileId, fileProtocol = FPXFTP}} ->
|
|
itemFileServers fileId `catchAllErrors` \_ -> pure []
|
|
_ -> pure []
|
|
where
|
|
itemFileServers fileId = case dir of
|
|
SMDSnd -> do
|
|
sfd_ <- withStore' $ \db -> getSndFTPrivateSndDescr db user fileId
|
|
case sfd_ of
|
|
Just sfdText -> fileDescrServers <$> (parseFileDescription sfdText :: CM (ValidFileDescription 'FSender))
|
|
Nothing -> pure []
|
|
SMDRcv -> do
|
|
RcvFileDescr {fileDescrText, fileDescrComplete} <- withStore $ \db -> getRcvFileDescrByRcvFileId db fileId
|
|
unless fileDescrComplete $ throwChatError $ CEInvalidFileDescription "incomplete file description"
|
|
fileDescrServers <$> (parseFileDescription fileDescrText :: CM (ValidFileDescription 'FRecipient))
|
|
|
|
sendDirectFileInline :: User -> Contact -> FileTransferMeta -> SharedMsgId -> CM ()
|
|
sendDirectFileInline user ct ft sharedMsgId = do
|
|
msgDeliveryId <- sendFileInline_ ft sharedMsgId $ sendDirectContactMessage user ct
|
|
withStore $ \db -> updateSndDirectFTDelivery db ct ft msgDeliveryId
|
|
|
|
sendMemberFileInline :: GroupMember -> Connection -> FileTransferMeta -> SharedMsgId -> CM ()
|
|
sendMemberFileInline m@GroupMember {groupId} conn ft sharedMsgId = do
|
|
msgDeliveryId <- sendFileInline_ ft sharedMsgId $ \msg -> do
|
|
(sndMsg, msgDeliveryId, _) <- sendDirectMemberMessage conn msg groupId
|
|
pure (sndMsg, msgDeliveryId)
|
|
withStore' $ \db -> updateSndGroupFTDelivery db m conn ft msgDeliveryId
|
|
|
|
sendFileInline_ :: FileTransferMeta -> SharedMsgId -> (ChatMsgEvent 'Binary -> CM (SndMessage, Int64)) -> CM Int64
|
|
sendFileInline_ FileTransferMeta {filePath, chunkSize} sharedMsgId sendMsg =
|
|
sendChunks 1 =<< liftIO . B.readFile =<< lift (toFSFilePath filePath)
|
|
where
|
|
sendChunks chunkNo bytes = do
|
|
let (chunk, rest) = B.splitAt chSize bytes
|
|
(_, msgDeliveryId) <- sendMsg $ BFileChunk sharedMsgId $ FileChunk chunkNo chunk
|
|
if B.null rest
|
|
then pure msgDeliveryId
|
|
else sendChunks (chunkNo + 1) rest
|
|
chSize = fromIntegral chunkSize
|
|
|
|
parseChatMessage :: Connection -> ByteString -> CM (ChatMessage 'Json)
|
|
parseChatMessage conn s = snd <$> parseChatMessage' conn s
|
|
{-# INLINE parseChatMessage #-}
|
|
|
|
parseChatMessage' :: Connection -> ByteString -> CM (Maybe SignedMsg, ChatMessage 'Json)
|
|
parseChatMessage' conn s =
|
|
case parseChatMessages s of
|
|
[msg] -> liftEither . first (ChatError . errType) $ (\(APMsg _ (ParsedMsg _ sm m)) -> (sm,) <$> checkEncoding m) =<< msg
|
|
_ -> throwChatError $ CEException "parseChatMessage: single message is expected"
|
|
where
|
|
errType = CEInvalidChatMessage conn Nothing (safeDecodeUtf8 s)
|
|
|
|
getChatScopeInfo :: StoreCxt -> User -> GroupChatScope -> CM GroupChatScopeInfo
|
|
getChatScopeInfo cxt user = \case
|
|
GCSMemberSupport Nothing -> pure $ GCSIMemberSupport Nothing
|
|
GCSMemberSupport (Just gmId) -> do
|
|
supportMem <- withFastStore $ \db -> getGroupMemberById db cxt user gmId
|
|
pure $ GCSIMemberSupport (Just supportMem)
|
|
|
|
getGroupRecipients :: StoreCxt -> User -> GroupInfo -> Maybe GroupChatScopeInfo -> VersionChat -> CM [GroupMember]
|
|
getGroupRecipients cxt user gInfo@GroupInfo {membership} scopeInfo modsCompatVersion
|
|
| useRelays' gInfo && not (isRelay membership) = do
|
|
unless (memberCurrent membership && memberActive membership) $ throwChatError $ CECommandError "not current member"
|
|
withFastStore' $ \db -> getGroupRelayMembers db cxt user gInfo
|
|
| otherwise = case scopeInfo of
|
|
Nothing -> do
|
|
unless (memberCurrent membership && memberActive membership) $ throwChatError $ CECommandError "not current member"
|
|
ms <- withFastStore' $ \db -> getGroupMembers db cxt user gInfo
|
|
pure $ filter memberCurrent ms
|
|
Just (GCSIMemberSupport Nothing) -> do
|
|
modMs <- withFastStore' $ \db -> getGroupModerators db cxt user gInfo
|
|
let rcpModMs' = filter (\m -> compatible m && memberCurrent m) modMs
|
|
when (null rcpModMs') $ throwChatError $ CECommandError "no admins support this message"
|
|
pure rcpModMs'
|
|
Just (GCSIMemberSupport (Just supportMem)) -> do
|
|
unless (memberCurrent membership && memberActive membership) $ throwChatError $ CECommandError "not current member"
|
|
unless (memberCurrentOrPending supportMem) $ throwChatError $ CECommandError "support member not current or pending"
|
|
if memberStatus supportMem == GSMemPendingApproval
|
|
then pure [supportMem]
|
|
else do
|
|
modMs <- withFastStore' $ \db -> getGroupModerators db cxt user gInfo
|
|
let rcpModMs' = filter (\m -> compatible m && memberCurrent m) modMs
|
|
pure $ [supportMem] <> rcpModMs'
|
|
where
|
|
compatible GroupMember {activeConn, memberChatVRange} =
|
|
maxVersion (maybe memberChatVRange peerChatVRange activeConn) >= modsCompatVersion
|
|
|
|
mkLocalGroupChatScope :: GroupInfo -> CM (GroupInfo, Maybe GroupChatScopeInfo)
|
|
mkLocalGroupChatScope gInfo@GroupInfo {membership}
|
|
| memberPending membership = do
|
|
(gInfo', scopeInfo) <- mkGroupSupportChatInfo gInfo
|
|
pure (gInfo', Just scopeInfo)
|
|
| otherwise =
|
|
pure (gInfo, Nothing)
|
|
|
|
mkGroupChatScope :: GroupInfo -> GroupMember -> CM (GroupInfo, GroupMember, Maybe GroupChatScopeInfo)
|
|
mkGroupChatScope gInfo@GroupInfo {membership} m
|
|
| memberPending membership = do
|
|
(gInfo', scopeInfo) <- mkGroupSupportChatInfo gInfo
|
|
pure (gInfo', m, Just scopeInfo)
|
|
| memberPending m = do
|
|
(m', scopeInfo) <- mkMemberSupportChatInfo m
|
|
pure (gInfo, m', Just scopeInfo)
|
|
| otherwise =
|
|
pure (gInfo, m, Nothing)
|
|
|
|
mkGetMessageChatScope :: StoreCxt -> User -> GroupInfo -> GroupMember -> MsgContent -> Maybe MsgScope -> CM (GroupInfo, GroupMember, Maybe GroupChatScopeInfo)
|
|
mkGetMessageChatScope cxt user gInfo@GroupInfo {membership} m mc msgScope_ =
|
|
mkGroupChatScope gInfo m >>= \case
|
|
groupScope@(_gInfo', _m', Just _scopeInfo) -> pure groupScope
|
|
(_, _, Nothing)
|
|
| isReport mc -> do
|
|
-- TODO [knocking] return patched _m'?
|
|
(_m', scopeInfo) <- mkMemberSupportChatInfo m -- only support scope member can send a report (m is sender)
|
|
pure (gInfo, m, Just scopeInfo)
|
|
| otherwise -> case msgScope_ of
|
|
Nothing -> pure (gInfo, m, Nothing)
|
|
Just (MSMember mId)
|
|
| sameMemberId mId membership -> do
|
|
(gInfo', scopeInfo) <- mkGroupSupportChatInfo gInfo
|
|
pure (gInfo', m, Just scopeInfo)
|
|
| otherwise -> do
|
|
referredMember <- withStore $ \db -> getGroupMemberByMemberId db cxt user gInfo mId
|
|
-- TODO [knocking] return patched _referredMember'?
|
|
(_referredMember', scopeInfo) <- mkMemberSupportChatInfo referredMember
|
|
pure (gInfo, m, Just scopeInfo)
|
|
|
|
mkGroupSupportChatInfo :: GroupInfo -> CM (GroupInfo, GroupChatScopeInfo)
|
|
mkGroupSupportChatInfo gInfo@GroupInfo {membership} =
|
|
case supportChat membership of
|
|
Nothing -> do
|
|
chatTs <- liftIO getCurrentTime
|
|
withStore' $ \db -> setSupportChatTs db (groupMemberId' membership) chatTs
|
|
let gInfo' = gInfo {membership = membership {supportChat = Just $ GroupSupportChat chatTs 0 0 0 Nothing}}
|
|
scopeInfo = GCSIMemberSupport {groupMember_ = Nothing}
|
|
pure (gInfo', scopeInfo)
|
|
Just _supportChat ->
|
|
let scopeInfo = GCSIMemberSupport {groupMember_ = Nothing}
|
|
in pure (gInfo, scopeInfo)
|
|
|
|
mkMemberSupportChatInfo :: GroupMember -> CM (GroupMember, GroupChatScopeInfo)
|
|
mkMemberSupportChatInfo m@GroupMember {groupMemberId, supportChat} =
|
|
case supportChat of
|
|
Nothing -> do
|
|
chatTs <- liftIO getCurrentTime
|
|
withStore' $ \db -> setSupportChatTs db groupMemberId chatTs
|
|
let m' = m {supportChat = Just $ GroupSupportChat chatTs 0 0 0 Nothing}
|
|
scopeInfo = GCSIMemberSupport {groupMember_ = Just m'}
|
|
pure (m', scopeInfo)
|
|
Just _supportChat ->
|
|
let scopeInfo = GCSIMemberSupport {groupMember_ = Just m}
|
|
in pure (m, scopeInfo)
|
|
|
|
appendFileChunk :: RcvFileTransfer -> Integer -> ByteString -> Bool -> CM ()
|
|
appendFileChunk ft@RcvFileTransfer {fileId, fileStatus, cryptoArgs, fileInvitation = FileInvitation {fileName}} chunkNo chunk final =
|
|
case fileStatus of
|
|
RFSConnected filePath -> append_ filePath
|
|
-- sometimes update of file transfer status to FSConnected
|
|
-- doesn't complete in time before MSG with first file chunk
|
|
RFSAccepted filePath -> append_ filePath
|
|
RFSCancelled _ -> pure ()
|
|
_ -> throwChatError $ CEFileInternal "receiving file transfer not in progress"
|
|
where
|
|
append_ :: FilePath -> CM ()
|
|
append_ filePath = do
|
|
fsFilePath <- lift $ toFSFilePath filePath
|
|
h <- getFileHandle fileId fsFilePath rcvFiles AppendMode
|
|
liftIO (B.hPut h chunk >> hFlush h) `catchThrow` (fileErr . show)
|
|
withStore' $ \db -> updatedRcvFileChunkStored db ft chunkNo
|
|
when final $ do
|
|
lift $ closeFileHandle fileId rcvFiles
|
|
forM_ cryptoArgs $ \cfArgs -> do
|
|
tmpFile <- lift getChatTempDirectory >>= liftIO . (`uniqueCombine` fileName)
|
|
tryAllErrors (liftError encryptErr $ encryptFile fsFilePath tmpFile cfArgs) >>= \case
|
|
Right () -> do
|
|
removeFile fsFilePath `catchAllErrors` \_ -> pure ()
|
|
renameFile tmpFile fsFilePath
|
|
Left e -> do
|
|
eToView e
|
|
removeFile tmpFile `catchAllErrors` \_ -> pure ()
|
|
withStore' (`removeFileCryptoArgs` fileId)
|
|
where
|
|
encryptErr e = fileErr $ e <> ", received file not encrypted"
|
|
fileErr = ChatError . CEFileWrite filePath
|
|
|
|
getFileHandle :: Int64 -> FilePath -> (ChatController -> TVar (Map Int64 Handle)) -> IOMode -> CM Handle
|
|
getFileHandle fileId filePath files ioMode = do
|
|
fs <- asks files
|
|
h_ <- M.lookup fileId <$> readTVarIO fs
|
|
maybe (newHandle fs) pure h_
|
|
where
|
|
newHandle fs = do
|
|
h <- openFile filePath ioMode `catchThrow` (ChatError . CEFileInternal . show)
|
|
atomically . modifyTVar fs $ M.insert fileId h
|
|
pure h
|
|
|
|
isFileActive :: Int64 -> (ChatController -> TVar (Map Int64 Handle)) -> CM Bool
|
|
isFileActive fileId files = do
|
|
fs <- asks files
|
|
isJust . M.lookup fileId <$> readTVarIO fs
|
|
|
|
cancelRcvFileTransfer :: User -> RcvFileTransfer -> CM ()
|
|
cancelRcvFileTransfer user ft@RcvFileTransfer {fileId, xftpRcvFile} =
|
|
cancel' `catchAllErrors` \e -> eToView e
|
|
where
|
|
cancel' = do
|
|
lift $ closeFileHandle fileId rcvFiles
|
|
withStore' $ \db -> do
|
|
updateFileCancelled db user fileId CIFSRcvCancelled
|
|
updateRcvFileStatus db fileId FSCancelled
|
|
deleteRcvFileChunks db ft
|
|
case xftpRcvFile of
|
|
Just XFTPRcvFile {agentRcvFileId = Just (AgentRcvFileId aFileId), agentRcvFileDeleted} ->
|
|
unless agentRcvFileDeleted $ agentXFTPDeleteRcvFile aFileId fileId
|
|
_ -> pure ()
|
|
|
|
cancelSndFile :: User -> FileTransferMeta -> [SndFileTransfer] -> Bool -> CM ()
|
|
cancelSndFile user FileTransferMeta {fileId, xftpSndFile} fts sendCancel = do
|
|
withStore' (\db -> updateFileCancelled db user fileId CIFSSndCancelled)
|
|
`catchAllErrors` eToView
|
|
case xftpSndFile of
|
|
Nothing ->
|
|
forM_ fts (\ft -> cancelSndFileTransfer user ft sendCancel)
|
|
Just xsf -> do
|
|
forM_ fts (\ft -> cancelSndFileTransfer user ft False)
|
|
lift (agentXFTPDeleteSndFileRemote user xsf fileId) `catchAllErrors` eToView
|
|
|
|
cancelSndFileTransfer :: User -> SndFileTransfer -> Bool -> CM ()
|
|
cancelSndFileTransfer user@User {userId} ft@SndFileTransfer {fileId, connId, fileStatus, fileInline} sendCancel =
|
|
unless (fileStatus == FSCancelled || fileStatus == FSComplete) $
|
|
cancel' `catchAllErrors` \e -> eToView e
|
|
where
|
|
cancel' = do
|
|
withStore' $ \db -> updateSndFileStatus db ft FSCancelled
|
|
when sendCancel $ case fileInline of
|
|
Just _ -> do
|
|
cxt <- chatStoreCxt
|
|
(sharedMsgId, conn) <- withStore $ \db -> (,) <$> getSharedMsgIdByFileId db userId fileId <*> getConnectionById db cxt user connId
|
|
void $ sendDirectMessage_ conn (BFileChunk sharedMsgId FileChunkCancel) (ConnectionId connId)
|
|
_ -> throwChatError $ CEException "cancelSndFileTransfer: cancelling file via a separate connection is deprecated"
|
|
|
|
closeFileHandle :: Int64 -> (ChatController -> TVar (Map Int64 Handle)) -> CM' ()
|
|
closeFileHandle fileId files = do
|
|
fs <- asks files
|
|
h_ <- atomically . stateTVar' fs $ \m -> (M.lookup fileId m, M.delete fileId m)
|
|
liftIO $ mapM_ hClose h_ `catchAll_` pure ()
|
|
|
|
-- The roster file has no chat item, so chat-item file enumeration misses it; clean it up by group.
|
|
cleanupGroupRosterFile :: User -> GroupInfo -> CM ()
|
|
cleanupGroupRosterFile User {userId} GroupInfo {groupId} = do
|
|
infos <- withStore' $ \db -> getGroupRosterFileInfo db userId groupId
|
|
forM_ infos $ \(fileId, filePath_) -> do
|
|
lift $ closeFileHandle fileId rcvFiles
|
|
forM_ filePath_ removeFsFile
|
|
withStore' $ \db -> do
|
|
deleteGroupRosterFile db userId groupId
|
|
deleteGroupRosterTransfers db groupId
|
|
|
|
-- Supersede/cancel one source relay's in-flight roster transfer: remove its on-disk file + cached
|
|
-- handle first (the cascade only does rows), then the files + transfer rows.
|
|
cleanupRosterTransfer :: GroupInfo -> GroupMemberId -> CM ()
|
|
cleanupRosterTransfer gInfo fromMemberId =
|
|
withStore' (\db -> getRosterTransferId db gInfo fromMemberId) >>= mapM_ cleanupRosterTransferById
|
|
|
|
cleanupRosterTransferById :: Int64 -> CM ()
|
|
cleanupRosterTransferById transferId = do
|
|
file_ <- withStore' $ \db -> getRosterTransferFile db transferId
|
|
forM_ file_ $ \(fileId, filePath_) -> do
|
|
lift $ closeFileHandle fileId rcvFiles
|
|
forM_ filePath_ removeFsFile
|
|
withStore' $ \db -> do
|
|
deleteRosterTransferFile db transferId
|
|
deleteRosterTransfer db transferId
|
|
|
|
-- MUST evict the cached AppendMode handle before deleting chunks, else re-driven bytes append
|
|
-- after the stale prefix and corrupt the blob.
|
|
resetRosterPartialChunks :: RcvFileTransfer -> CM ()
|
|
resetRosterPartialChunks ft@RcvFileTransfer {fileId, fileStatus} = do
|
|
lift $ closeFileHandle fileId rcvFiles
|
|
forM_ (rcvFilePath fileStatus) removeFsFile
|
|
withStore' $ \db -> deleteRcvFileChunks db ft
|
|
where
|
|
rcvFilePath = \case
|
|
RFSAccepted p -> Just p
|
|
RFSConnected p -> Just p
|
|
_ -> Nothing
|
|
|
|
removeFsFile :: FilePath -> CM ()
|
|
removeFsFile fp = do
|
|
p <- lift $ toFSFilePath fp
|
|
removeFile p `catchAllErrors` \_ -> pure ()
|
|
|
|
deleteMembersConnections :: User -> [GroupMember] -> CM ()
|
|
deleteMembersConnections user members = deleteMembersConnections' user members False
|
|
|
|
deleteMembersConnections' :: User -> [GroupMember] -> Bool -> CM ()
|
|
deleteMembersConnections' user members waitDelivery = do
|
|
let memberConns = mapMaybe (\GroupMember {activeConn} -> activeConn) members
|
|
deleteAgentConnectionsAsync' (map aConnId memberConns) waitDelivery
|
|
lift . void . withStoreBatch' $ \db -> map (\Connection {connId} -> deleteConnectionRecord db user connId) memberConns
|
|
|
|
deleteMemberConnection :: GroupMember -> CM ()
|
|
deleteMemberConnection mem = deleteMemberConnection' mem False
|
|
|
|
deleteMemberConnection' :: GroupMember -> Bool -> CM ()
|
|
deleteMemberConnection' GroupMember {activeConn} waitDelivery = do
|
|
forM_ activeConn $ \conn -> do
|
|
deleteAgentConnectionAsync' (aConnId conn) waitDelivery
|
|
withStore' $ \db -> updateConnectionStatus db conn ConnDeleted
|
|
|
|
deleteOrUpdateMemberRecord :: User -> GroupInfo -> GroupMember -> CM GroupInfo
|
|
deleteOrUpdateMemberRecord user gInfo m =
|
|
withStore' $ \db -> deleteOrUpdateMemberRecordIO db user gInfo m
|
|
|
|
deleteOrUpdateMemberRecordIO :: DB.Connection -> User -> GroupInfo -> GroupMember -> IO GroupInfo
|
|
deleteOrUpdateMemberRecordIO db user@User {userId} gInfo m = do
|
|
(gInfo', m') <- deleteSupportChatIfExists db user gInfo m
|
|
if isRelay m'
|
|
then deleteGroupMember db user m'
|
|
else
|
|
checkGroupMemberHasItems db user m' >>= \case
|
|
Just _ -> updateGroupMemberStatus db userId m' GSMemRemoved
|
|
Nothing
|
|
| useRelays' gInfo -> updateGroupMemberRemovedAt db user m'
|
|
| otherwise -> deleteGroupMember db user m'
|
|
pure gInfo'
|
|
|
|
-- Unlike deleteOrUpdateMemberRecord, skips checkGroupMemberHasItems.
|
|
fullyDeleteMemberRecord :: User -> GroupInfo -> GroupMember -> CM GroupInfo
|
|
fullyDeleteMemberRecord user gInfo m =
|
|
withStore' $ \db -> fullyDeleteMemberRecordIO db user gInfo m
|
|
|
|
fullyDeleteMemberRecordIO :: DB.Connection -> User -> GroupInfo -> GroupMember -> IO GroupInfo
|
|
fullyDeleteMemberRecordIO db user gInfo m = do
|
|
(gInfo', m') <- deleteSupportChatIfExists db user gInfo m
|
|
if useRelays' gInfo && not (isRelay m')
|
|
then updateGroupMemberRemovedAt db user m'
|
|
else deleteGroupMember db user m'
|
|
pure gInfo'
|
|
|
|
updateMemberRecordDeleted :: User -> GroupInfo -> GroupMember -> GroupMemberStatus -> CM GroupInfo
|
|
updateMemberRecordDeleted user@User {userId} gInfo m newStatus =
|
|
withStore' $ \db -> do
|
|
(gInfo', m') <- deleteSupportChatIfExists db user gInfo m
|
|
updateGroupMemberStatus db userId m' newStatus
|
|
deactivateRelay_ db m
|
|
pure gInfo'
|
|
|
|
deactivateRelay_ :: DB.Connection -> GroupMember -> IO ()
|
|
deactivateRelay_ db m =
|
|
when (isRelay m) $ do
|
|
relay_ <- runExceptT $ getGroupRelayByGMId db (groupMemberId' m)
|
|
forM_ relay_ $ \relay -> void $ updateRelayStatus db relay RSInactive
|
|
|
|
deleteSupportChatIfExists :: DB.Connection -> User -> GroupInfo -> GroupMember -> IO (GroupInfo, GroupMember)
|
|
deleteSupportChatIfExists db user gInfo m = do
|
|
gInfo' <-
|
|
if gmRequiresAttention m
|
|
then decreaseGroupMembersRequireAttention db user gInfo
|
|
else pure gInfo
|
|
m' <-
|
|
if isJust (supportChat m)
|
|
then deleteGroupMemberSupportChat db m
|
|
else pure m
|
|
pure (gInfo', m')
|
|
|
|
sendDirectContactMessages :: MsgEncodingI e => User -> Contact -> NonEmpty (ChatMsgEvent e) -> CM [Either ChatError SndMessage]
|
|
sendDirectContactMessages user ct events = do
|
|
conn@Connection {connId} <- liftEither $ contactSendConn_ ct
|
|
let idsEvts = L.map (ConnectionId connId,Nothing,) events
|
|
msgFlags = MsgFlags {notification = any (hasNotification . toCMEventTag) events}
|
|
sndMsgs_ <- lift $ createSndMessages idsEvts
|
|
(sndMsgs', pqEnc_) <- batchSendConnMessagesB BMJson user conn msgFlags sndMsgs_
|
|
forM_ pqEnc_ $ \pqEnc' -> void $ createContactPQSndItem user ct conn pqEnc'
|
|
pure sndMsgs'
|
|
|
|
-- present the user's own badge on an outgoing profile: a fresh, single-use proof from the stored credential.
|
|
-- the send's incognito profile (when set) suppresses it - an incognito identity must never carry the badge.
|
|
-- a long-expired badge is not presented at all (receivers would hide it anyway).
|
|
presentUserBadge :: User -> Maybe i -> Maybe ProofPresHeader -> Profile -> CM Profile
|
|
presentUserBadge user incognitoProfile = presentUserBadgeWith user incognitoProfile . pure
|
|
|
|
presentUserBadgeWith :: User -> Maybe i -> CM (Maybe ProofPresHeader) -> Profile -> CM Profile
|
|
presentUserBadgeWith user incognitoProfile getPresHeader p
|
|
| isNothing incognitoProfile && presentsUserBadge user = do
|
|
badge <- getPresHeader $>>= sndBadgeProof user
|
|
pure p {badge}
|
|
| otherwise = pure p
|
|
|
|
presentsUserBadge :: User -> Bool
|
|
presentsUserBadge User {profile = LocalProfile {localBadge}} = case localBadge of
|
|
Just (OwnBadge _ st) -> st == BSActive || st == BSExpired
|
|
_ -> False
|
|
|
|
groupPresHeader :: GroupInfo -> Maybe ProofPresHeader
|
|
groupPresHeader gInfo@GroupInfo {membership = GroupMember {memberId, memberPubKey}} = memberPresHeader gInfo memberId memberPubKey
|
|
|
|
membershipHandshakeProfile :: User -> GroupInfo -> CM Profile
|
|
membershipHandshakeProfile user gInfo@GroupInfo {membership} =
|
|
presentUserBadge user (incognitoMembershipProfile gInfo) (groupPresHeader gInfo) $ redactedMemberProfile gInfo membership $ fromLocalProfile $ memberProfile membership
|
|
|
|
directPresHeader :: ContactRequestBinding -> ProofPresHeader
|
|
directPresHeader = \case
|
|
CRBRatchet ConnVerifyCodes {codeAD} -> PHChat $ encodeChatBinding CBDirect $ C.sha256Hash $ "SimpleX badge" <> codeAD
|
|
CRBRequest code -> PHRequest code
|
|
|
|
linkPresHeader :: ConnShortLink c -> ProofPresHeader
|
|
linkPresHeader = \case
|
|
CSLInvitation _ _ _ (LinkKey key) -> PHLink key
|
|
CSLContact _ _ _ (LinkKey key) -> PHLink key
|
|
|
|
connPresHeader :: Connection -> CM (Maybe ProofPresHeader)
|
|
connPresHeader conn = M.lookup (aConnId conn) <$> connsPresHeaders [conn]
|
|
|
|
connsPresHeaders :: [Connection] -> CM (Map ConnId ProofPresHeader)
|
|
connsPresHeaders conns = M.map (directPresHeader . CRBRatchet) <$> withAgent (`getConnectionsVerifyCodes` map aConnId conns)
|
|
|
|
-- receiving side of contact/invitation link data: verify the badge proof from the link profile
|
|
-- and set the crypto-free display badge for the UI (the raw proof stays in profile for APIPrepareContact)
|
|
linkDataBadge :: ProofPresHeader -> ContactShortLinkData -> CM ContactShortLinkData
|
|
linkDataBadge presHeader cld@ContactShortLinkData {profile = Profile {badge}} = case mfilter (acceptedProof (Just presHeader)) badge of
|
|
Nothing -> pure (cld :: ContactShortLinkData) {localBadge = Nothing}
|
|
Just b@(BadgeProof _ _ _ info) -> do
|
|
keys <- asks $ badgePublicKeys . config
|
|
verified <- liftIO $ verifyBadge keys b
|
|
now <- liftIO getCurrentTime
|
|
pure (cld :: ContactShortLinkData) {localBadge = Just $ ShownBadge info (mkBadgeStatus now verified info)}
|
|
|
|
sendDirectContactMessage :: MsgEncodingI e => User -> Contact -> ChatMsgEvent e -> CM (SndMessage, Int64)
|
|
sendDirectContactMessage user ct chatMsgEvent = do
|
|
conn@Connection {connId} <- liftEither $ contactSendConn_ ct
|
|
r <- sendDirectMessage_ conn chatMsgEvent (ConnectionId connId)
|
|
let (sndMessage, msgDeliveryId, pqEnc') = r
|
|
void $ createContactPQSndItem user ct conn pqEnc'
|
|
pure (sndMessage, msgDeliveryId)
|
|
|
|
contactSendConn_ :: Contact -> Either ChatError Connection
|
|
contactSendConn_ ct@Contact {activeConn} = case activeConn of
|
|
Nothing -> err $ CEContactNotReady ct
|
|
Just conn
|
|
| not (connReady conn) -> err $ CEContactNotReady ct
|
|
| not (contactActive ct) -> err $ CEContactNotActive ct
|
|
| connDisabled conn -> err $ CEContactDisabled ct
|
|
| otherwise -> Right conn
|
|
where
|
|
err = Left . ChatError
|
|
|
|
-- unlike sendGroupMemberMessage, this function will not store message as pending
|
|
-- TODO v5.8 we could remove pending messages once all clients support forwarding
|
|
sendDirectMemberMessage :: MsgEncodingI e => Connection -> ChatMsgEvent e -> GroupId -> CM (SndMessage, Int64, PQEncryption)
|
|
sendDirectMemberMessage conn chatMsgEvent groupId = sendDirectMessage_ conn chatMsgEvent (GroupId groupId)
|
|
|
|
sendDirectMessage_ :: MsgEncodingI e => Connection -> ChatMsgEvent e -> ConnOrGroupId -> CM (SndMessage, Int64, PQEncryption)
|
|
sendDirectMessage_ conn chatMsgEvent connOrGroupId = do
|
|
when (connDisabled conn) $ throwChatError (CEConnectionDisabled conn)
|
|
msg@SndMessage {msgId, msgBody} <- createSndMessage chatMsgEvent connOrGroupId
|
|
-- TODO move compressed body to SndMessage and compress in createSndMessage
|
|
(msgDeliveryId, pqEnc') <- deliverMessage conn (toCMEventTag chatMsgEvent) msgBody msgId
|
|
pure (msg, msgDeliveryId, pqEnc')
|
|
|
|
createSndMessage :: MsgEncodingI e => ChatMsgEvent e -> ConnOrGroupId -> CM SndMessage
|
|
createSndMessage chatMsgEvent connOrGroupId =
|
|
liftEither . runIdentity =<< lift (createSndMessages $ Identity (connOrGroupId, Nothing, chatMsgEvent))
|
|
|
|
createSndMessages :: forall e t. (MsgEncodingI e, Traversable t) => t (ConnOrGroupId, Maybe MsgSigning, ChatMsgEvent e) -> CM' (t (Either ChatError SndMessage))
|
|
createSndMessages idsEvents = do
|
|
g <- asks random
|
|
vr <- chatVersionRange'
|
|
withStoreBatch $ \db -> fmap (createMsg db g vr) idsEvents
|
|
where
|
|
createMsg :: DB.Connection -> TVar ChaChaDRG -> VersionRangeChat -> (ConnOrGroupId, Maybe MsgSigning, ChatMsgEvent e) -> IO (Either ChatError SndMessage)
|
|
createMsg db g vr (connOrGroupId, msgSigning_, evnt) = runExceptT $ do
|
|
withExceptT ChatErrorStore $ createNewSndMessage db g connOrGroupId evnt msgSigning_ encodeMessage
|
|
where
|
|
encodeMessage sharedMsgId =
|
|
encodeChatMessage maxEncodedMsgLength ChatMessage {chatVRange = vr, msgId = Just sharedMsgId, chatMsgEvent = evnt}
|
|
|
|
groupMsgSigning :: Bool -> GroupInfoKeys -> ChatMsgEvent e -> Maybe MsgSigning
|
|
groupMsgSigning sign (GIK gInfo@GroupInfo {membership = GroupMember {memberId}} gks) evt
|
|
| shouldSign = Just $ MsgSigning CBGroup bindingData KRMember memberPrivKey'
|
|
| otherwise = Nothing
|
|
where
|
|
memberPrivKey' = memberPrivKey gks
|
|
tag = toCMEventTag evt
|
|
shouldSign = requiresSignature tag || (sign && signableContent tag) || badgePresented
|
|
badgePresented = case evt of
|
|
XGrpMemInfo _ Profile {badge} -> isJust badge
|
|
XGrpAcpt _ _ (Just Profile {badge}) -> isJust badge
|
|
_ -> False
|
|
bindingData = groupBindingData gInfo memberId (C.publicKey memberPrivKey')
|
|
|
|
groupBindingData :: GroupInfo -> MemberId -> C.PublicKeyEd25519 -> ByteString
|
|
groupBindingData gInfo memberId memberKey = case publicGroup' gInfo of
|
|
Just PublicGroupProfile {publicGroupId} -> smpEncode (publicGroupId, memberId)
|
|
Nothing -> smpEncode (memberId, memberKey)
|
|
|
|
type HistoryFile = (FileInvitation, RcvFileDescrText, Maybe UTCTime, Maybe BadgeProof)
|
|
|
|
directChatBinding :: Contact -> CM (Maybe ByteString)
|
|
directChatBinding ct =
|
|
forM (contactConn ct) $ \conn ->
|
|
encodeChatBinding CBDirect . codeAD <$> withAgent (`getConnectionVerifyCodes` aConnId conn)
|
|
|
|
rcvGroupChatBinding :: GroupInfo -> Maybe GroupMember -> ShowGroupAsSender -> Maybe BadgeProof -> Maybe ByteString
|
|
rcvGroupChatBinding gInfo m_ asGroup badge_ =
|
|
case (publicGroup' gInfo, asGroup, m_) of
|
|
(Just PublicGroupProfile {publicGroupId}, True, _) ->
|
|
Just $ encodeChatBinding CBChannel $ smpEncode publicGroupId
|
|
(Just PublicGroupProfile {publicGroupId}, False, Just GroupMember {memberId}) ->
|
|
Just $ encodeChatBinding CBGroup $ smpEncode (publicGroupId, memberId)
|
|
(Nothing, False, Just GroupMember {memberId, memberPubKey}) ->
|
|
(\k -> encodeChatBinding CBGroup $ smpEncode (memberId, k)) <$> (memberPubKey <|> proofMemberKey memberId badge_)
|
|
_ -> Nothing
|
|
|
|
memberPresHeader :: GroupInfo -> MemberId -> Maybe C.PublicKeyEd25519 -> Maybe ProofPresHeader
|
|
memberPresHeader gInfo memberId = fmap $ memberKeyPresHeader ((\PublicGroupProfile {publicGroupId} -> publicGroupId) <$> publicGroup' gInfo) memberId
|
|
|
|
memberKeyPresHeader :: Maybe B64UrlByteString -> MemberId -> C.PublicKeyEd25519 -> ProofPresHeader
|
|
memberKeyPresHeader publicGroupId_ memberId k =
|
|
PHChat $ encodeChatBinding CBGroup $ maybe (smpEncode (memberId, k)) (\publicGroupId -> smpEncode (publicGroupId, memberId, k)) publicGroupId_
|
|
|
|
memberInfoPresHeader :: GroupInfo -> MemberInfo -> Maybe ProofPresHeader
|
|
memberInfoPresHeader gInfo MemberInfo {memberId, memberKey} = memberPresHeader gInfo memberId ((\(MemberKey k) -> k) <$> memberKey)
|
|
|
|
proofMemberKey :: MemberId -> Maybe BadgeProof -> Maybe C.PublicKeyEd25519
|
|
proofMemberKey memberId badge_ = do
|
|
BadgeProof _ (BBSPresHeader phBytes) _ _ <- badge_
|
|
binding <- headerChatBinding =<< eitherToMaybe (strDecode phBytes)
|
|
d <- B.stripPrefix (smpEncode CBGroup) binding
|
|
(mId, k) <- eitherToMaybe (smpDecode d :: Either String (MemberId, C.PublicKeyEd25519))
|
|
if mId == memberId then Just k else Nothing
|
|
where
|
|
headerChatBinding = \case
|
|
PHFileInv {chatBinding} -> Just chatBinding
|
|
PHFileDescr {chatBinding} -> Just chatBinding
|
|
_ -> Nothing
|
|
|
|
badgeProofStatus :: Maybe ProofPresHeader -> BadgeProof -> CM BadgeStatus
|
|
badgeProofStatus expected_ badge@BadgeProof {presHeader = BBSPresHeader phBytes, badgeInfo} =
|
|
case expected_ of
|
|
Just expected | phBytes == strEncode expected -> do
|
|
keys <- asks $ badgePublicKeys . config
|
|
verified <- liftIO $ verifyBadge keys badge
|
|
now <- liftIO getCurrentTime
|
|
pure $ mkBadgeStatus now verified badgeInfo
|
|
_ -> pure BSFailed
|
|
|
|
rcvDirectFileProhibited :: Contact -> FileInvitation -> CM (Maybe FileProhibited)
|
|
rcvDirectFileProhibited ct fInv@FileInvitation {fileBadge} = do
|
|
binding_ <- if isJust fileBadge then directChatBinding ct else pure Nothing
|
|
rcvFileProhibited binding_ fInv
|
|
|
|
rcvGroupFileProhibited :: GroupInfo -> Maybe GroupMember -> ShowGroupAsSender -> FileInvitation -> CM (Maybe FileProhibited)
|
|
rcvGroupFileProhibited gInfo m_ asGroup fInv@FileInvitation {fileBadge} =
|
|
rcvFileProhibited (rcvGroupChatBinding gInfo m_ asGroup fileBadge) fInv
|
|
|
|
rcvFileProhibited :: Maybe ByteString -> FileInvitation -> CM (Maybe FileProhibited)
|
|
rcvFileProhibited binding_ FileInvitation {fileSize, fileBadge} = do
|
|
lims <- asks $ fileSizeLimits . config
|
|
if fileSize <= noBadge lims
|
|
then pure Nothing
|
|
else case fileBadge of
|
|
Nothing -> pure $ Just FileProhibited {maxSize = noBadge lims, badgeStatus = Nothing}
|
|
Just badge -> do
|
|
st <- badgeProofStatus ((\chatBinding -> PHFileInv {chatBinding, fileSize = fromInteger fileSize}) <$> binding_) badge
|
|
let maxSize = maxXFTPFileSize lims $ Just $ PeerBadge badge st
|
|
pure $
|
|
if fileSize <= maxSize
|
|
then Nothing
|
|
else Just FileProhibited {maxSize, badgeStatus = Just st}
|
|
|
|
groupMemberKey :: GroupKeys -> MemberKey
|
|
groupMemberKey gks = MemberKey $ C.publicKey $ memberPrivKey gks
|
|
|
|
sendGroupMemberMessages :: forall e. MsgEncodingI e => User -> GroupInfoKeys -> Connection -> NonEmpty (ChatMsgEvent e) -> CM ()
|
|
sendGroupMemberMessages user g@(GIK gInfo@GroupInfo {groupId} _) conn events = do
|
|
when (connDisabled conn) $ throwChatError (CEConnectionDisabled conn)
|
|
let idsEvts = L.map (\evt -> (GroupId groupId, groupMsgSigning False g evt, evt)) events
|
|
(errs, msgs) <- lift $ partitionEithers . L.toList <$> createSndMessages idsEvts
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
forM_ (L.nonEmpty msgs) $ \msgs' ->
|
|
batchSendConnMessages gInfo user conn MsgFlags {notification = True} msgs'
|
|
|
|
batchSendConnMessages :: GroupInfo -> User -> Connection -> MsgFlags -> NonEmpty SndMessage -> CM ([Either ChatError SndMessage], Maybe PQEncryption)
|
|
batchSendConnMessages gInfo user conn msgFlags msgs =
|
|
batchSendConnMessagesB mode user conn msgFlags $ L.map Right msgs
|
|
where
|
|
mode
|
|
| useRelays' gInfo || maxVersion (peerChatVRange conn) >= relayWebCapVersion = BMBinary
|
|
| otherwise = BMJson
|
|
|
|
batchSendConnMessagesB :: BatchMode -> User -> Connection -> MsgFlags -> NonEmpty (Either ChatError SndMessage) -> CM ([Either ChatError SndMessage], Maybe PQEncryption)
|
|
batchSendConnMessagesB mode _user conn msgFlags msgs_ = do
|
|
let batched_ = batchSndMessagesJSON mode msgs_
|
|
case L.nonEmpty batched_ of
|
|
Just batched' -> do
|
|
let msgReqs = L.map (fmap msgBatchReq_) batched'
|
|
delivered <- deliverMessagesB msgReqs
|
|
let msgs' = concat $ L.zipWith flattenMsgs batched' delivered
|
|
pqEnc = findLastPQEnc delivered
|
|
when (length msgs' /= length msgs_) $ logError "batchSendConnMessagesB: msgs_ and msgs' length mismatch"
|
|
pure (msgs', pqEnc)
|
|
Nothing -> pure ([], Nothing)
|
|
where
|
|
msgBatchReq_ :: MsgBatch -> ChatMsgReq
|
|
msgBatchReq_ (MsgBatch batchBody sndMsgs) =
|
|
(conn, msgFlags, (vrValue batchBody, map (\SndMessage {msgId} -> msgId) sndMsgs))
|
|
flattenMsgs :: Either ChatError MsgBatch -> Either ChatError ([Int64], PQEncryption) -> [Either ChatError SndMessage]
|
|
flattenMsgs (Right (MsgBatch _ sndMsgs)) (Right _) = map Right sndMsgs
|
|
flattenMsgs (Right (MsgBatch _ sndMsgs)) (Left ce) = replicate (length sndMsgs) (Left ce)
|
|
flattenMsgs (Left ce) _ = [Left ce] -- restore original ChatError
|
|
findLastPQEnc :: NonEmpty (Either ChatError ([Int64], PQEncryption)) -> Maybe PQEncryption
|
|
findLastPQEnc = foldr' (\x acc -> case x of Right (_, pqEnc) -> Just pqEnc; Left _ -> acc) Nothing
|
|
|
|
batchSndMessagesJSON :: BatchMode -> NonEmpty (Either ChatError SndMessage) -> [Either ChatError MsgBatch]
|
|
batchSndMessagesJSON mode = batchMessages mode maxEncodedMsgLength . L.toList
|
|
|
|
compressToLimit :: MonadError ChatError m => Int -> MsgBody -> m MsgBody
|
|
compressToLimit maxLen s
|
|
| B.length s <= maxLen = pure s
|
|
| B.length s' <= maxLen = pure s'
|
|
| otherwise = throwError $ ChatError $ CEException "large compressed body"
|
|
where
|
|
s' = compressedBatchMsgBody_ s
|
|
|
|
compressConnInfo :: PQSupport -> MsgBody -> CM MsgBody
|
|
compressConnInfo pqSup = compressToLimit $ e2eEncConnInfoLength pqSup - 2 - maxReplyQueueFraming
|
|
|
|
maxReplyQueueFraming :: Int
|
|
maxReplyQueueFraming = 256
|
|
|
|
encodeConnInfo :: MsgEncodingI e => ChatMsgEvent e -> CM ByteString
|
|
encodeConnInfo = encodeConnInfoPQ PQSupportOff
|
|
|
|
encodeConnInfoPQ :: MsgEncodingI e => PQSupport -> ChatMsgEvent e -> CM ByteString
|
|
encodeConnInfoPQ pqSup chatMsgEvent = do
|
|
cxt <- chatStoreCxt
|
|
let info = ChatMessage {chatVRange = vr cxt, msgId = Nothing, chatMsgEvent}
|
|
case encodeChatMessage maxEncodedProfileMsgLength info of
|
|
ECMEncoded connInfo -> compressConnInfo pqSup connInfo
|
|
ECMLarge -> throwChatError $ CEException "large info"
|
|
|
|
-- conn-info wrapped as a signed element, so the receiver can verify the signature over the body
|
|
encodeSignedConnInfo :: MsgEncodingI e => PQSupport -> MsgSigning -> ChatMsgEvent e -> CM ByteString
|
|
encodeSignedConnInfo pqSup signing chatMsgEvent = do
|
|
vr <- chatVersionRange
|
|
let info = ChatMessage {chatVRange = vr, msgId = Nothing, chatMsgEvent}
|
|
case encodeChatMessage maxEncodedProfileMsgLength info of
|
|
ECMEncoded body -> compressConnInfo pqSup $ encodeBatchElement (Just $ signChatMsgBody signing body) body
|
|
ECMLarge -> throwChatError $ CEException "large signed info"
|
|
|
|
encodeConnInfoSigning :: MsgEncodingI e => PQSupport -> Maybe MsgSigning -> ChatMsgEvent e -> CM ByteString
|
|
encodeConnInfoSigning pqSup = maybe (encodeConnInfoPQ pqSup) (encodeSignedConnInfo pqSup)
|
|
|
|
-- signed XMember for a relay-group join: proves the joiner holds the member key it asserts, and carries
|
|
-- viaRelay = the target relay's memberId inside the signed body so a sibling relay can't accept a replay
|
|
encodeXMemberConnInfo :: PQSupport -> GroupInfoKeys -> MemberId -> Profile -> CM ByteString
|
|
encodeXMemberConnInfo pqSup (GIK gInfo@GroupInfo {membership = GroupMember {memberId}} gks) relayMemberId profileToSend =
|
|
let memberPrivKey' = memberPrivKey gks
|
|
xMemberEvt = XMember profileToSend memberId (MemberKey $ C.publicKey memberPrivKey') (Just relayMemberId)
|
|
bindingData = groupBindingData gInfo memberId (C.publicKey memberPrivKey')
|
|
signing = MsgSigning CBGroup bindingData KRMember memberPrivKey'
|
|
in encodeSignedConnInfo pqSup signing xMemberEvt
|
|
|
|
encodeXGrpAcpt :: User -> GroupInfoKeys -> VersionRangeChat -> CM ByteString
|
|
encodeXGrpAcpt user g@(GIK gInfo@GroupInfo {membership = GroupMember {memberId}} gks) peerVRange = do
|
|
let incognitoProfile = incognitoMembershipProfile gInfo
|
|
profile <- presentUserBadge user incognitoProfile (groupPresHeader gInfo) (userProfileInGroup user gInfo $ fromLocalProfile <$> incognitoProfile)
|
|
let msg = XGrpAcpt memberId (Just $ groupMemberKey gks) (Just profile)
|
|
signing_ = if maxVersion peerVRange >= relayWebCapVersion then groupMsgSigning False g msg else Nothing
|
|
encodeConnInfoSigning PQSupportOff signing_ msg
|
|
|
|
deliverMessage :: Connection -> CMEventTag e -> MsgBody -> MessageId -> CM (Int64, PQEncryption)
|
|
deliverMessage conn cmEventTag msgBody msgId = do
|
|
let msgFlags = MsgFlags {notification = hasNotification cmEventTag}
|
|
deliverMessage' conn msgFlags msgBody msgId
|
|
|
|
deliverMessage' :: Connection -> MsgFlags -> MsgBody -> MessageId -> CM (Int64, PQEncryption)
|
|
deliverMessage' conn msgFlags msgBody msgId =
|
|
deliverMessages ((conn, msgFlags, (vrValue msgBody, [msgId])) :| []) >>= \case
|
|
r :| [] -> case r of
|
|
Right ([deliveryId], pqEnc) -> pure (deliveryId, pqEnc)
|
|
Right (deliveryIds, _) -> throwChatError $ CEInternalError $ "deliverMessage: expected 1 delivery id, got " <> show (length deliveryIds)
|
|
Left e -> throwError e
|
|
rs -> throwChatError $ CEInternalError $ "deliverMessage: expected 1 result, got " <> show (length rs)
|
|
|
|
-- [MessageId] - SndMessage ids inside MsgBatch, or single message id
|
|
type ChatMsgReq = (Connection, MsgFlags, (ValueOrRef MsgBody, [MessageId]))
|
|
|
|
deliverMessages :: NonEmpty ChatMsgReq -> CM (NonEmpty (Either ChatError ([Int64], PQEncryption)))
|
|
deliverMessages msgs = deliverMessagesB $ L.map Right msgs
|
|
|
|
deliverMessagesB :: NonEmpty (Either ChatError ChatMsgReq) -> CM (NonEmpty (Either ChatError ([Int64], PQEncryption)))
|
|
deliverMessagesB msgReqs = do
|
|
msgReqs' <- liftIO compressBodies
|
|
sent <- L.zipWith prepareBatch msgReqs' <$> withAgent (`sendMessagesB` snd (mapAccumL toAgent Nothing msgReqs'))
|
|
lift . void $ withStoreBatch' $ \db -> map (updatePQSndEnabled db) (rights . L.toList $ sent)
|
|
lift . withStoreBatch $ \db -> L.map (bindRight $ createDelivery db) sent
|
|
where
|
|
-- group sends share bodies between connections via VRRef, so the smallest limit applies to the batch
|
|
maxLen = if any connSupportsPQ msgReqs then maxEncodedMsgLengthPQ else maxEncodedMsgLength
|
|
connSupportsPQ = \case
|
|
Right (Connection {pqSupport = PQSupportOn}, _, _) -> True
|
|
_ -> False
|
|
compressBodies =
|
|
forME msgReqs $ \(conn, msgFlags, (mbr, msgIds)) -> runExceptT $ do
|
|
mbr' <- case mbr of
|
|
VRValue i msgBody -> VRValue i <$> compressToLimit maxLen msgBody
|
|
v -> pure v
|
|
pure (conn, msgFlags, (mbr', msgIds))
|
|
toAgent prev = \case
|
|
Right (conn@Connection {connId, pqEncryption}, msgFlags, (mbr, _msgIds)) ->
|
|
let cId = case prev of
|
|
Just prevId | prevId == connId -> ""
|
|
_ -> aConnId conn
|
|
in (Just connId, Right (cId, pqEncryption, msgFlags, mbr))
|
|
Left _ce -> (prev, Left (AP.INTERNAL "ChatError, skip")) -- as long as it is Left, the agent batchers should just step over it
|
|
prepareBatch (Right req) (Right ar) = Right (req, ar)
|
|
prepareBatch (Left ce) _ = Left ce -- restore original ChatError
|
|
prepareBatch _ (Left ae) = Left $ chatErrorAgent ae
|
|
createDelivery :: DB.Connection -> (ChatMsgReq, (AgentMsgId, PQEncryption)) -> IO (Either ChatError ([Int64], PQEncryption))
|
|
createDelivery db ((Connection {connId}, _, (_, msgIds)), (agentMsgId, pqEnc')) = do
|
|
Right . (,pqEnc') <$> mapM (createSndMsgDelivery db (SndMsgDelivery {connId, agentMsgId})) msgIds
|
|
updatePQSndEnabled :: DB.Connection -> (ChatMsgReq, (AgentMsgId, PQEncryption)) -> IO ()
|
|
updatePQSndEnabled db ((Connection {connId, pqSndEnabled}, _, _), (_, pqSndEnabled')) =
|
|
case (pqSndEnabled, pqSndEnabled') of
|
|
(Just b, b') | b' /= b -> updatePQ
|
|
(Nothing, PQEncOn) -> updatePQ
|
|
_ -> pure ()
|
|
where
|
|
updatePQ = updateConnPQSndEnabled db connId pqSndEnabled'
|
|
|
|
sendGroupMessage :: MsgEncodingI e => User -> GroupInfoKeys -> Maybe GroupChatScope -> [GroupMember] -> Bool -> ChatMsgEvent e -> CM SndMessage
|
|
sendGroupMessage user gInfo gcScope members sign chatMsgEvent = do
|
|
sendGroupMessages user gInfo gcScope False members sign (chatMsgEvent :| []) >>= \case
|
|
((Right msg) :| [], _) -> pure msg
|
|
_ -> throwChatError $ CEInternalError "sendGroupMessage: expected 1 message"
|
|
|
|
sendGroupMessage' :: MsgEncodingI e => User -> GroupInfoKeys -> [GroupMember] -> ChatMsgEvent e -> CM SndMessage
|
|
sendGroupMessage' user gInfo members chatMsgEvent =
|
|
sendGroupMessages_ user gInfo members False (chatMsgEvent :| []) >>= \case
|
|
((Right msg) :| [], _) -> pure msg
|
|
_ -> throwChatError $ CEInternalError "sendGroupMessage': expected 1 message"
|
|
|
|
-- The roster change being broadcast, projected onto the current roster members in broadcastRoster. This lets the
|
|
-- roster blob be built (and sent) before the change is applied to the owner's own member records, so the owner
|
|
-- never demotes/removes a member locally before the change has been propagated to relays.
|
|
data RosterDelta
|
|
= RDRoleChanged GroupMemberRole [GroupMember] -- these members now hold this role
|
|
| RDRemoved [GroupMember] -- these members are removed from the group
|
|
|
|
applyRosterDelta :: RosterDelta -> [GroupMember] -> [GroupMember]
|
|
applyRosterDelta delta current = case delta of
|
|
RDRoleChanged role changed -> map (\m -> (m :: GroupMember) {memberRole = role}) changed <> without changed
|
|
RDRemoved removed -> without removed
|
|
where
|
|
without ms = let ids = S.fromList (map groupMemberId' ms) in filter ((`S.notMember` ids) . groupMemberId') current
|
|
|
|
-- TODO [relays] improvement: publish roster_version in link data so the owner can recover the latest version
|
|
-- TODO after restoring from a stale backup (relays accept only strictly-greater versions)
|
|
-- Reserve and persist the next roster version (committed before the events that carry it, so a recipient never
|
|
-- advances past a version the owner hasn't recorded), then broadcast the matching blob with the change projected
|
|
-- onto the served roster (so it excludes demoted/removed members). Returns the reserved version for the delta
|
|
-- that follows. The blob send is best-effort - a failed send heals on the next change or on resume.
|
|
broadcastRoster :: User -> GroupInfoKeys -> RosterDelta -> CM VersionRoster
|
|
broadcastRoster user g@(GIK gInfo _) delta = do
|
|
let rosterVer = maybe (VersionRoster 0) (\(VersionRoster n) -> VersionRoster (n + 1)) (rosterVersion gInfo)
|
|
withStore' $ \db -> setGroupRosterVersion db gInfo rosterVer
|
|
sendRosterBlob rosterVer `catchAllErrors` eToView
|
|
pure rosterVer
|
|
where
|
|
sendRosterBlob rosterVer = do
|
|
cxt <- chatStoreCxt
|
|
(relays, rosterMems) <- withStore' $ \db ->
|
|
(,) <$> getGroupRelayMembers db cxt user gInfo <*> getGroupRosterMembers db cxt user gInfo
|
|
forM_ (L.nonEmpty relays) $ \relays' ->
|
|
sendRoster user g (L.toList relays') rosterVer (buildGroupRoster $ applyRosterDelta delta rosterMems)
|
|
|
|
-- Send the current roster (no version bump) to a newly added relay so it can serve joiners.
|
|
sendGroupRosterToRelay :: User -> GroupInfoKeys -> GroupMember -> CM ()
|
|
sendGroupRosterToRelay user g@(GIK gInfo _) relayMember =
|
|
forM_ (rosterVersion gInfo) $ \rosterVer -> do
|
|
cxt <- chatStoreCxt
|
|
rosterMems <- withStore' $ \db -> getGroupRosterMembers db cxt user gInfo
|
|
sendRoster user g [relayMember] rosterVer (buildGroupRoster rosterMems)
|
|
|
|
-- Row-less send (no files/snd_files rows, so no send-side cleanup); redelivery is the agent's.
|
|
sendRoster :: User -> GroupInfoKeys -> [GroupMember] -> VersionRoster -> [RosterMember] -> CM ()
|
|
sendRoster user gInfo members rosterVer roster = do
|
|
let blob = encodeRosterBlob roster
|
|
fileInv = InlineFileInvitation {fileSize = fromIntegral (B.length blob), fileDigest = FD.FileDigest $ LC.sha512Hash $ LB.fromStrict blob}
|
|
SndMessage {sharedMsgId} <- sendGroupMessage' user gInfo members (XGrpRoster GroupRoster {version = rosterVer, fileInv})
|
|
sendInlineBlobChunks user gInfo members sharedMsgId blob
|
|
|
|
-- Send a binary blob as BFileChunks under a shared_msg_id to the given members (chunked by fileChunkSize).
|
|
sendInlineBlobChunks :: User -> GroupInfoKeys -> [GroupMember] -> SharedMsgId -> ByteString -> CM ()
|
|
sendInlineBlobChunks user gInfo members sharedMsgId blob = do
|
|
chSize <- fromIntegral <$> asks (fileChunkSize . config)
|
|
go chSize 1 blob
|
|
where
|
|
go chSize chunkNo bytes = do
|
|
let (chunk, rest) = B.splitAt chSize bytes
|
|
void $ sendGroupMessage' user gInfo members (BFileChunk sharedMsgId (FileChunk chunkNo chunk))
|
|
unless (B.null rest) $ go chSize (chunkNo + 1) rest
|
|
|
|
-- Relay advertises its current web preview capability to channel owners.
|
|
-- Idempotent: sends only when the configured web domain differs from what was last sent, and only to
|
|
-- owners whose recorded chat version supports relayWebCapVersion (older apps can't parse XGrpRelayCap).
|
|
sendRelayCapIfNeeded :: User -> GroupInfoKeys -> CM ()
|
|
sendRelayCapIfNeeded user g@(GIK gInfo _) = do
|
|
ChatConfig {webPreviewConfig} <- asks config
|
|
let currentWebDomain = (\WebPreviewConfig {webDomain} -> webDomain) <$> webPreviewConfig
|
|
sentWebDomain <- withStore' (`getRelaySentWebDomain` gInfo)
|
|
when (currentWebDomain /= sentWebDomain) $ do
|
|
cxt <- chatStoreCxt
|
|
owners <- withStore' $ \db -> getGroupOwners db cxt user gInfo
|
|
let capableOwners = filter (\m -> memberCurrent m && m `supportsVersion` relayWebCapVersion) owners
|
|
unless (null capableOwners) $ do
|
|
void $ sendGroupMessage' user g capableOwners (XGrpRelayCap RelayCapabilities {webDomain = currentWebDomain})
|
|
withStore' $ \db -> updateRelaySentWebDomain db gInfo currentWebDomain
|
|
|
|
sendGroupMessages :: MsgEncodingI e => User -> GroupInfoKeys -> Maybe GroupChatScope -> ShowGroupAsSender -> [GroupMember] -> Bool -> NonEmpty (ChatMsgEvent e) -> CM (NonEmpty (Either ChatError SndMessage), GroupSndResult)
|
|
sendGroupMessages user gInfo scope asGroup members sign events = do
|
|
sendGroupProfileUpdate user gInfo scope asGroup members
|
|
sendGroupMessages_ user gInfo members sign events
|
|
|
|
-- per-item signer variant of sendGroupMessages (used for per-item delete signing); preserves the profile-update prelude
|
|
sendGroupSignedMessages :: MsgEncodingI e => User -> GroupInfoKeys -> Maybe GroupChatScope -> ShowGroupAsSender -> [GroupMember] -> NonEmpty (Maybe MsgSigning, ChatMsgEvent e) -> CM (NonEmpty (Either ChatError SndMessage), GroupSndResult)
|
|
sendGroupSignedMessages user gInfo@(GIK g _) scope asGroup members signedEvents = do
|
|
sendGroupProfileUpdate user gInfo scope asGroup members
|
|
sendGroupSignedMessages_ g members signedEvents
|
|
|
|
sendGroupProfileUpdate :: User -> GroupInfoKeys -> Maybe GroupChatScope -> ShowGroupAsSender -> [GroupMember] -> CM ()
|
|
sendGroupProfileUpdate user g@(GIK gInfo gks) scope asGroup members =
|
|
-- TODO [knocking] send current profile to pending member after approval?
|
|
when shouldSendProfileUpdate $
|
|
sendProfileUpdate `catchAllErrors` eToView
|
|
where
|
|
User {profile = p, userMemberProfileUpdatedAt} = user
|
|
GroupInfo {userMemberProfileSentAt} = gInfo
|
|
shouldSendProfileUpdate
|
|
| asGroup = False
|
|
| isJust scope = False -- why not sending profile updates to scopes?
|
|
| incognitoMembership gInfo = False
|
|
| otherwise =
|
|
case (userMemberProfileSentAt, userMemberProfileUpdatedAt) of
|
|
(Just lastSentTs, Just lastUpdateTs) -> lastSentTs < lastUpdateTs
|
|
(Nothing, Just _) -> True
|
|
_ -> False
|
|
sendProfileUpdate = do
|
|
-- shouldSendProfileUpdate excludes incognito membership, so the badge is presented
|
|
profileUpdate <- presentUserBadge user Nothing (groupPresHeader gInfo) $ redactedMemberProfile gInfo (membership gInfo) $ fromLocalProfile p
|
|
void $ sendGroupMessage' user g members $ XInfo profileUpdate (Just $ groupMemberKey gks)
|
|
currentTs <- liftIO getCurrentTime
|
|
withStore' $ \db -> updateUserMemberProfileSentAt db user gInfo currentTs
|
|
|
|
data GroupSndResult = GroupSndResult
|
|
{ sentTo :: [(GroupMemberId, Either ChatError [MessageId], Either ChatError ([Int64], PQEncryption))],
|
|
pending :: [(GroupMemberId, Either ChatError MessageId, Either ChatError ())],
|
|
forwarded :: [GroupMember]
|
|
}
|
|
|
|
sendGroupMessages_ :: MsgEncodingI e => User -> GroupInfoKeys -> [GroupMember] -> Bool -> NonEmpty (ChatMsgEvent e) -> CM (NonEmpty (Either ChatError SndMessage), GroupSndResult)
|
|
sendGroupMessages_ _user gInfo@(GIK g _) recipientMembers sign events =
|
|
sendGroupSignedMessages_ g recipientMembers $ L.map (\evt -> (groupMsgSigning sign gInfo evt, evt)) events
|
|
|
|
sendGroupSignedMessages_ :: MsgEncodingI e => GroupInfo -> [GroupMember] -> NonEmpty (Maybe MsgSigning, ChatMsgEvent e) -> CM (NonEmpty (Either ChatError SndMessage), GroupSndResult)
|
|
sendGroupSignedMessages_ gInfo@GroupInfo {groupId} recipientMembers signedEvents = do
|
|
sndMsgs_ <- lift $ createSndMessages idsEvts
|
|
recipientMembers' <- liftIO $ shuffleMembers recipientMembers
|
|
let msgFlags = MsgFlags {notification = any (hasNotification . toCMEventTag) events}
|
|
(toSend, toPending, forwarded, _, dups) =
|
|
foldr' (addMember recipientMembers') (([], []), [], [], S.empty, 0 :: Int) recipientMembers'
|
|
when (dups /= 0) $ logError $ "sendGroupMessages_: " <> tshow dups <> " duplicate members"
|
|
-- TODO PQ either somehow ensure that group members connections cannot have pqSupport/pqEncryption or pass Off's here
|
|
-- Deliver to toSend members
|
|
let (sendToMemIds, msgReqs) = prepareMsgReqs msgFlags sndMsgs_ toSend
|
|
delivered <- maybe (pure []) (fmap L.toList . deliverMessagesB) $ L.nonEmpty msgReqs
|
|
when (length delivered /= length sendToMemIds) $ logError "sendGroupMessages_: sendToMemIds and delivered length mismatch"
|
|
-- Save as pending for toPending members
|
|
let (pendingMemIds, pendingReqs) = preparePending sndMsgs_ toPending
|
|
stored <- lift $ withStoreBatch (\db -> map (bindRight $ createPendingMsg db) pendingReqs)
|
|
when (length stored /= length pendingMemIds) $ logError "sendGroupMessages_: pendingMemIds and stored length mismatch"
|
|
-- Zip for easier access to results
|
|
let sentTo = zipWith3 (\mId mReq r -> (mId, fmap (\(_, _, (_, msgIds)) -> msgIds) mReq, r)) sendToMemIds msgReqs delivered
|
|
pending = zipWith3 (\mId pReq r -> (mId, fmap snd pReq, r)) pendingMemIds pendingReqs stored
|
|
pure (sndMsgs_, GroupSndResult {sentTo, pending, forwarded})
|
|
where
|
|
events = L.map snd signedEvents
|
|
idsEvts = L.map (\(signing, evt) -> (GroupId groupId, signing, evt)) signedEvents
|
|
shuffleMembers :: [GroupMember] -> IO [GroupMember]
|
|
shuffleMembers ms = do
|
|
let (adminMs, otherMs) = partition isAdmin ms
|
|
liftM2 (<>) (shuffle adminMs) (shuffle otherMs)
|
|
where
|
|
isAdmin GroupMember {memberRole} = memberRole >= GRAdmin
|
|
addMember members m acc@(toSend@(toSendBin, toSendJson), pending, forwarded, !mIds, !dups) =
|
|
case memberSendAction gInfo events members m of
|
|
Just a
|
|
| mId `S.member` mIds -> (toSend, pending, forwarded, mIds, dups + 1)
|
|
| otherwise -> case a of
|
|
MSASend conn ->
|
|
let toSend' = case batchMode gInfo m of
|
|
BMBinary -> ((m, conn) : toSendBin, toSendJson)
|
|
BMJson -> (toSendBin, (m, conn) : toSendJson)
|
|
in (toSend', pending, forwarded, mIds', dups)
|
|
MSAPending -> (toSend, m : pending, forwarded, mIds', dups)
|
|
MSAForwarded -> (toSend, pending, m : forwarded, mIds', dups)
|
|
Nothing -> acc
|
|
where
|
|
mId = groupMemberId' m
|
|
mIds' = S.insert mId mIds
|
|
prepareMsgReqs :: MsgFlags -> NonEmpty (Either ChatError SndMessage) -> ([(GroupMember, Connection)], [(GroupMember, Connection)]) -> ([GroupMemberId], [Either ChatError ChatMsgReq])
|
|
prepareMsgReqs msgFlags msgs (toSendBin, toSendJson) =
|
|
batchReqs 1 BMBinary toSendBin <> batchReqs 2 BMJson toSendJson
|
|
where
|
|
batchReqs _ _ [] = ([], [])
|
|
batchReqs n mode toSend' = case L.nonEmpty (batchSndMessagesJSON mode msgs) of
|
|
Just batched -> foldMembers (n * (length batched + length msgs)) msgBatchMBR batched toSend'
|
|
Nothing -> ([], [])
|
|
foldMembers :: forall a. Int -> (Maybe Int -> Int -> a -> (ValueOrRef MsgBody, [MessageId])) -> NonEmpty (Either ChatError a) -> [(GroupMember, Connection)] -> ([GroupMemberId], [Either ChatError ChatMsgReq])
|
|
foldMembers lastRef mkMb mbs mems = snd $ foldr' foldMsgBodies (lastMemIdx_, ([], [])) mems
|
|
where
|
|
lastMemIdx_ = let len = length mems in if len > 1 then Just len else Nothing
|
|
foldMsgBodies :: (GroupMember, Connection) -> (Maybe Int, ([GroupMemberId], [Either ChatError ChatMsgReq])) -> (Maybe Int, ([GroupMemberId], [Either ChatError ChatMsgReq]))
|
|
foldMsgBodies (GroupMember {groupMemberId}, conn) (memIdx_, memIdsReqs) =
|
|
(subtract 1 <$> memIdx_,) $ snd $ foldr' addBody (lastRef, memIdsReqs) mbs
|
|
where
|
|
addBody :: Either ChatError a -> (Int, ([GroupMemberId], [Either ChatError ChatMsgReq])) -> (Int, ([GroupMemberId], [Either ChatError ChatMsgReq]))
|
|
addBody mb (i, (memIds, reqs)) =
|
|
let req = (conn,msgFlags,) . mkMb memIdx_ i <$> mb
|
|
in (i - 1, (groupMemberId : memIds, req : reqs))
|
|
msgBatchMBR :: Maybe Int -> Int -> MsgBatch -> (ValueOrRef MsgBody, [MessageId])
|
|
msgBatchMBR memIdx_ i (MsgBatch batchBody sndMsgs) = (vrValue_ memIdx_ i batchBody, map (\SndMessage {msgId} -> msgId) sndMsgs)
|
|
vrValue_ memIdx_ i v = case memIdx_ of
|
|
Nothing -> VRValue Nothing v -- sending to one member, do not reference bodies
|
|
Just 1 -> VRValue (Just i) v
|
|
Just _ -> VRRef i
|
|
preparePending :: NonEmpty (Either ChatError SndMessage) -> [GroupMember] -> ([GroupMemberId], [Either ChatError (GroupMemberId, MessageId)])
|
|
preparePending msgs_ =
|
|
foldr' foldMsgs ([], [])
|
|
where
|
|
foldMsgs :: GroupMember -> ([GroupMemberId], [Either ChatError (GroupMemberId, MessageId)]) -> ([GroupMemberId], [Either ChatError (GroupMemberId, MessageId)])
|
|
foldMsgs GroupMember {groupMemberId} memIdsReqs =
|
|
foldr' (\msg_ (memIds, reqs) -> (groupMemberId : memIds, fmap pendingReq msg_ : reqs)) memIdsReqs msgs_
|
|
where
|
|
pendingReq :: SndMessage -> (GroupMemberId, MessageId)
|
|
pendingReq SndMessage {msgId} = (groupMemberId, msgId)
|
|
createPendingMsg :: DB.Connection -> (GroupMemberId, MessageId) -> IO (Either ChatError ())
|
|
createPendingMsg db (groupMemberId, msgId) =
|
|
createPendingGroupMessage db groupMemberId msgId $> Right ()
|
|
|
|
batchMode :: GroupInfo -> GroupMember -> BatchMode
|
|
batchMode gInfo m
|
|
| useRelays' gInfo || m `supportsVersion` relayWebCapVersion = BMBinary
|
|
| otherwise = BMJson
|
|
|
|
data MemberSendAction = MSASend Connection | MSAPending | MSAForwarded
|
|
|
|
memberSendAction :: GroupInfo -> NonEmpty (ChatMsgEvent e) -> [GroupMember] -> GroupMember -> Maybe MemberSendAction
|
|
memberSendAction gInfo@GroupInfo {membership} events members m@GroupMember {memberStatus}
|
|
-- groups with relays require newer version - we don't need to check member version for batching and forwarding support
|
|
| useRelays' gInfo =
|
|
if
|
|
-- if user is chat relay, send to all non chat relay members
|
|
| isRelay membership && not (isRelay m) -> MSASend . snd <$> readyMemberConn m
|
|
-- if user is not chat relay, send only to chat relays
|
|
| not (isRelay membership) && isRelay m -> MSASend . snd <$> readyMemberConn m
|
|
| otherwise -> Nothing -- TODO [relays] MSAForwarded to create GSSForwarded snd statuses?
|
|
| otherwise = case memberConn m of
|
|
Nothing -> pendingOrForwarded
|
|
Just conn@Connection {connStatus}
|
|
| connDisabled conn || connStatus == ConnDeleted || isConnFailed connStatus || memberStatus == GSMemRejected -> Nothing
|
|
| connInactive conn -> Just MSAPending
|
|
| connStatus == ConnSndReady || connStatus == ConnReady -> Just (MSASend conn)
|
|
| otherwise -> pendingOrForwarded
|
|
where
|
|
pendingOrForwarded = case memberCategory m of
|
|
GCUserMember -> Nothing -- shouldn't happen
|
|
GCInviteeMember -> Just MSAPending
|
|
GCHostMember -> Just MSAPending
|
|
GCPreMember -> forwardSupportedOrPending (invitedByGroupMemberId membership)
|
|
GCPostMember -> forwardSupportedOrPending (invitedByGroupMemberId m)
|
|
where
|
|
forwardSupportedOrPending invitingMemberId_
|
|
| hasInvitingMember && all isForwardedGroupMsg events = Just MSAForwarded
|
|
| any isXGrpMsgForward events = Nothing
|
|
| otherwise = Just MSAPending
|
|
where
|
|
hasInvitingMember = case invitingMemberId_ of
|
|
Just invMemberId ->
|
|
-- can be optimized for large groups by replacing [GroupMember] with Map GroupMemberId GroupMember
|
|
any (\m' -> groupMemberId' m' == invMemberId) members
|
|
Nothing -> False
|
|
isXGrpMsgForward event = case event of
|
|
XGrpMsgForward {} -> True
|
|
_ -> False
|
|
|
|
-- Should match memberSendAction logic
|
|
readyMemberConn :: GroupMember -> Maybe (GroupMemberId, Connection)
|
|
readyMemberConn GroupMember {groupMemberId, activeConn = Just conn@Connection {connStatus}, memberStatus}
|
|
| (connStatus == ConnReady || connStatus == ConnSndReady)
|
|
&& not (connDisabled conn)
|
|
&& not (connInactive conn)
|
|
&& memberStatus /= GSMemRejected =
|
|
Just (groupMemberId, conn)
|
|
| otherwise = Nothing
|
|
readyMemberConn GroupMember {activeConn = Nothing} = Nothing
|
|
|
|
sendGroupMemberMessage :: MsgEncodingI e => GroupInfo -> GroupMember -> ChatMsgEvent e -> CM ()
|
|
sendGroupMemberMessage gInfo@GroupInfo {groupId} m@GroupMember {groupMemberId} chatMsgEvent = do
|
|
msg <- createSndMessage chatMsgEvent (GroupId groupId)
|
|
messageMember msg `catchAllErrors` eToView
|
|
where
|
|
messageMember :: SndMessage -> CM ()
|
|
messageMember SndMessage {msgId, msgBody} = forM_ (memberSendAction gInfo (chatMsgEvent :| []) [m] m) $ \case
|
|
MSASend conn -> void $ deliverMessage conn (toCMEventTag chatMsgEvent) msgBody msgId
|
|
MSAPending -> withStore' $ \db -> createPendingGroupMessage db groupMemberId msgId
|
|
MSAForwarded -> pure ()
|
|
|
|
-- Send pre-encoded forwarded message preserving original signature
|
|
sendFwdMemberMessage :: GroupMember -> GrpMsgForward -> VerifiedMsg 'Json -> CM ()
|
|
sendFwdMemberMessage member fwd verifiedMsg =
|
|
forM_ (readyMemberConn member) $ \(_, conn) -> do
|
|
let body = encodeBinaryBatch [encodeFwdElement fwd verifiedMsg]
|
|
void $ withAgent $ \a -> sendMessages a [(aConnId conn, PQEncOff, MsgFlags {notification = msgHasNotification verifiedMsg}, VRValue Nothing body)]
|
|
|
|
-- TODO ensure order - pending messages interleave with user input messages
|
|
sendPendingGroupMessages :: User -> GroupInfo -> GroupMember -> Connection -> CM ()
|
|
sendPendingGroupMessages user gInfo GroupMember {groupMemberId} conn = do
|
|
msgs <- withStore' $ \db -> getPendingGroupMessages db groupMemberId
|
|
forM_ (L.nonEmpty msgs) $ \msgs' -> do
|
|
void $ batchSendConnMessages gInfo user conn MsgFlags {notification = True} msgs'
|
|
lift . void . withStoreBatch' $ \db -> L.map (\SndMessage {msgId} -> deletePendingGroupMessage db groupMemberId msgId) msgs'
|
|
|
|
saveDirectRcvMSG :: forall e. MsgEncodingI e => Connection -> MsgMeta -> ChatMessage e -> CM (Connection, RcvMessage)
|
|
saveDirectRcvMSG conn@Connection {connId} agentMsgMeta chatMsg@ChatMessage {chatVRange, msgId = sharedMsgId_, chatMsgEvent} = do
|
|
conn' <- case encoding @e of
|
|
SJson -> updatePeerChatVRange conn chatVRange
|
|
SBinary -> pure conn
|
|
let agentMsgId = fst $ recipient agentMsgMeta
|
|
brokerTs = metaBrokerTs agentMsgMeta
|
|
newMsg = NewRcvMessage {chatMsgEvent, verifiedMsg = VMUnsigned chatMsg, brokerTs}
|
|
rcvMsgDelivery = RcvMsgDelivery {connId, agentMsgId, agentMsgMeta}
|
|
msg <- withStore $ \db -> createNewMessageAndRcvMsgDelivery db (ConnectionId connId) newMsg sharedMsgId_ rcvMsgDelivery Nothing
|
|
pure (conn', msg)
|
|
|
|
saveGroupRcvMsg :: forall e. MsgEncodingI e => User -> GroupId -> GroupMember -> Connection -> MsgMeta -> VerifiedMsg e -> CM (GroupMember, Connection, RcvMessage)
|
|
saveGroupRcvMsg user groupId authorMember conn@Connection {connId} agentMsgMeta verifiedMsg = do
|
|
let ChatMessage {chatVRange, msgId = sharedMsgId_, chatMsgEvent} = verifiedChatMsg verifiedMsg
|
|
-- binary messages (file chunks) carry only the initial-version sentinel, not the sender's range;
|
|
-- applying it would downgrade the member's negotiated version and suppress version-gated delivery
|
|
(am'@GroupMember {memberId = amMemId, groupMemberId = amGroupMemId}, conn') <- case encoding @e of
|
|
SBinary -> pure (authorMember, conn)
|
|
SJson -> updateMemberChatVRange authorMember conn chatVRange
|
|
let agentMsgId = fst $ recipient agentMsgMeta
|
|
brokerTs = metaBrokerTs agentMsgMeta
|
|
newMsg = NewRcvMessage {chatMsgEvent, verifiedMsg, brokerTs}
|
|
rcvMsgDelivery = RcvMsgDelivery {connId, agentMsgId, agentMsgMeta}
|
|
msg <-
|
|
withStore (\db -> createNewMessageAndRcvMsgDelivery db (GroupId groupId) newMsg sharedMsgId_ rcvMsgDelivery $ Just amGroupMemId)
|
|
`catchAllErrors` \e -> case e of
|
|
ChatErrorStore (SEDuplicateGroupMessage _ _ _ forwardedByGroupMemberId_) -> do
|
|
unlessM isMainApp $ toView $ CEvtDuplicateGroupMessage user am'
|
|
forM_ forwardedByGroupMemberId_ $ \forwardedByGroupMemberId -> do
|
|
cxt <- chatStoreCxt
|
|
fm <- withStore $ \db -> getGroupMember db cxt user groupId forwardedByGroupMemberId
|
|
forM_ (memberConn fm) $ \fmConn ->
|
|
void $ sendDirectMemberMessage fmConn (XGrpMemCon amMemId) groupId
|
|
throwError e
|
|
_ -> throwError e
|
|
pure (am', conn', msg)
|
|
|
|
saveGroupFwdRcvMsg :: MsgEncodingI e => User -> GroupInfo -> GroupMember -> Maybe GroupMember -> VerifiedMsg e -> UTCTime -> CM (Maybe RcvMessage)
|
|
saveGroupFwdRcvMsg user gInfo@GroupInfo {groupId} forwardingMember refAuthorMember_ verifiedMsg brokerTs = do
|
|
let ChatMessage {msgId = sharedMsgId_, chatMsgEvent} = verifiedChatMsg verifiedMsg
|
|
newMsg = NewRcvMessage {chatMsgEvent, verifiedMsg, brokerTs}
|
|
fwdMemberId = Just $ groupMemberId' forwardingMember
|
|
refAuthorId = groupMemberId' <$> refAuthorMember_
|
|
-- TODO [relays] TBC highlighting difference between deduplicated messages (useRelays branch)
|
|
withStore' (\db -> runExceptT $ createNewRcvMessage db (GroupId groupId) newMsg sharedMsgId_ refAuthorId fwdMemberId) >>= \case
|
|
Right msg -> pure $ Just msg
|
|
Left e@SEDuplicateGroupMessage {authorGroupMemberId, forwardedByGroupMemberId} -> do
|
|
unlessM isMainApp $ toView $ CEvtDuplicateGroupMessage user forwardingMember
|
|
if
|
|
| useRelays' gInfo -> pure Nothing -- with chat relays, duplicates are expected
|
|
| otherwise -> case (authorGroupMemberId, forwardedByGroupMemberId) of
|
|
(Just authorGMId, Nothing) -> do
|
|
cxt <- chatStoreCxt
|
|
am@GroupMember {memberId = amMemberId} <- withStore $ \db -> getGroupMember db cxt user groupId authorGMId
|
|
if maybe False (\ref -> sameMemberId (memberId' ref) am) refAuthorMember_
|
|
then forM_ (memberConn forwardingMember) $ \fmConn ->
|
|
void $ sendDirectMemberMessage fmConn (XGrpMemCon amMemberId) groupId
|
|
else toView $ CEvtMessageError user "error" "saveGroupFwdRcvMsg: referenced author member id doesn't match message member id"
|
|
throwError $ ChatErrorStore e
|
|
_ -> throwError $ ChatErrorStore e
|
|
Left e -> throwError $ ChatErrorStore e
|
|
|
|
isMainApp :: CM Bool
|
|
isMainApp = (SMSubscribe ==) <$> chatReadVar subscriptionMode
|
|
|
|
saveSndChatItem :: ChatTypeI c => User -> ChatDirection c 'MDSnd -> SndMessage -> CIContent 'MDSnd -> CM (ChatItem c 'MDSnd)
|
|
saveSndChatItem user cd msg content = saveSndChatItem' user cd msg content Nothing Nothing Nothing Nothing False
|
|
|
|
-- TODO [mentions] optimize by avoiding unnecesary parsing of control messages
|
|
saveSndChatItem' :: ChatTypeI c => User -> ChatDirection c 'MDSnd -> SndMessage -> CIContent 'MDSnd -> Maybe (CIFile 'MDSnd) -> Maybe (CIQuote c) -> Maybe CIForwardedFrom -> Maybe CITimed -> Bool -> CM (ChatItem c 'MDSnd)
|
|
saveSndChatItem' user cd msg content ciFile quotedItem itemForwarded itemTimed live = do
|
|
let itemTexts = ciContentTexts content
|
|
saveSndChatItems user cd False [Right NewSndChatItemData {msg, content, itemTexts, itemMentions = M.empty, ciFile, quotedItem, itemForwarded}] itemTimed live >>= \case
|
|
[Right ci] -> pure ci
|
|
_ -> throwChatError $ CEInternalError "saveSndChatItem': expected 1 item"
|
|
|
|
data NewSndChatItemData c = NewSndChatItemData
|
|
{ msg :: SndMessage,
|
|
content :: CIContent 'MDSnd,
|
|
itemTexts :: (Text, ParsedMarkdown),
|
|
itemMentions :: Map MemberName CIMention,
|
|
ciFile :: Maybe (CIFile 'MDSnd),
|
|
quotedItem :: Maybe (CIQuote c),
|
|
itemForwarded :: Maybe CIForwardedFrom
|
|
}
|
|
|
|
saveSndChatItems ::
|
|
forall c.
|
|
ChatTypeI c =>
|
|
User ->
|
|
ChatDirection c 'MDSnd ->
|
|
ShowGroupAsSender ->
|
|
[Either ChatError (NewSndChatItemData c)] ->
|
|
Maybe CITimed ->
|
|
Bool ->
|
|
CM [Either ChatError (ChatItem c 'MDSnd)]
|
|
saveSndChatItems user cd showGroupAsSender itemsData itemTimed live = do
|
|
createdAt <- liftIO getCurrentTime
|
|
cxt <- chatStoreCxt
|
|
when (contactChatDeleted cd || any (\NewSndChatItemData {content} -> ciRequiresAttention content) (rights itemsData)) $
|
|
void (withStore' $ \db -> updateChatTsStats db cxt user cd createdAt Nothing)
|
|
lift $ withStoreBatch (\db -> map (bindRight $ createItem db createdAt) itemsData)
|
|
where
|
|
createItem :: DB.Connection -> UTCTime -> NewSndChatItemData c -> IO (Either ChatError (ChatItem c 'MDSnd))
|
|
createItem db createdAt NewSndChatItemData {msg = msg@SndMessage {sharedMsgId, signedMsg_}, content, itemTexts = itemTexts@(_, ParsedMarkdown ft_ _), itemMentions, ciFile, quotedItem, itemForwarded} = do
|
|
let hasLink_ = ciContentHasLink content ft_
|
|
itemTs = roundDownToSecond createdAt
|
|
ciId <- createNewSndChatItem db user cd showGroupAsSender msg content quotedItem itemForwarded itemTimed live hasLink_ itemTs createdAt
|
|
forM_ ciFile $ \CIFile {fileId} -> updateFileTransferChatItemId db fileId ciId createdAt
|
|
let ci = mkChatItem_ cd showGroupAsSender ciId content itemTexts ciFile quotedItem (Just sharedMsgId) itemForwarded itemTimed live False hasLink_ itemTs Nothing (toMsgVerified (signMessagesRequired cd) (MSSVerified <$ signedMsg_)) createdAt
|
|
Right <$> case cd of
|
|
CDGroupSnd g _scope | not (null itemMentions) -> createGroupCIMentions db g ci itemMentions
|
|
_ -> pure ci
|
|
|
|
roundDownToSecond :: UTCTime -> UTCTime
|
|
roundDownToSecond t@UTCTime {utctDayTime} = t {utctDayTime = fromInteger (floor utctDayTime)}
|
|
|
|
saveRcvChatItemNoParse :: (ChatTypeI c, ChatTypeQuotable c) => User -> ChatDirection c 'MDRcv -> RcvMessage -> UTCTime -> CIContent 'MDRcv -> CM (ChatItem c 'MDRcv, ChatInfo c)
|
|
saveRcvChatItemNoParse user cd msg brokerTs = saveRcvChatItem user cd msg brokerTs . ciContentNoParse
|
|
|
|
saveRcvChatItem :: (ChatTypeI c, ChatTypeQuotable c) => User -> ChatDirection c 'MDRcv -> RcvMessage -> UTCTime -> (CIContent 'MDRcv, (Text, ParsedMarkdown)) -> CM (ChatItem c 'MDRcv, ChatInfo c)
|
|
saveRcvChatItem user cd msg@RcvMessage {sharedMsgId_} brokerTs content =
|
|
saveRcvChatItem' user cd msg sharedMsgId_ brokerTs content Nothing Nothing False M.empty
|
|
|
|
ciContentNoParse :: CIContent 'MDRcv -> (CIContent 'MDRcv, (Text, ParsedMarkdown))
|
|
ciContentNoParse content = (content, (ciContentToText content, ParsedMarkdown Nothing Nothing))
|
|
|
|
saveRcvChatItem' :: (ChatTypeI c, ChatTypeQuotable c) => User -> ChatDirection c 'MDRcv -> RcvMessage -> Maybe SharedMsgId -> UTCTime -> (CIContent 'MDRcv, (Text, ParsedMarkdown)) -> Maybe (CIFile 'MDRcv) -> Maybe CITimed -> Bool -> Map MemberName MsgMention -> CM (ChatItem c 'MDRcv, ChatInfo c)
|
|
saveRcvChatItem' user cd msg@RcvMessage {chatMsgEvent, msgSigned, forwardedByMember} sharedMsgId_ brokerTs (content, ts@(_, ParsedMarkdown ft_ _)) ciFile itemTimed live mentions = do
|
|
createdAt <- liftIO getCurrentTime
|
|
cxt <- chatStoreCxt
|
|
withStore' $ \db -> do
|
|
(mentions' :: Map MemberName CIMention, userMention) <- case toChatInfo cd of
|
|
GroupChat g@GroupInfo {membership} _ -> groupMentions db g membership
|
|
_ -> pure (M.empty, False)
|
|
cInfo' <-
|
|
if (ciRequiresAttention content || contactChatDeleted cd)
|
|
then updateChatTsStats db cxt user cd createdAt (memberChatStats userMention)
|
|
else pure $ toChatInfo cd
|
|
let showAsGroup = case cd of CDChannelRcv {} -> True; _ -> False
|
|
hasLink_ = ciContentHasLink content ft_
|
|
itemForwarded <- rcvForwardedFrom db user cd msg
|
|
(ciId, quotedItem) <- createNewRcvChatItem db user cd msg sharedMsgId_ content itemForwarded itemTimed live userMention hasLink_ brokerTs createdAt
|
|
forM_ ciFile $ \CIFile {fileId} -> updateFileTransferChatItemId db fileId ciId createdAt
|
|
let ci = mkChatItem_ cd showAsGroup ciId content ts ciFile quotedItem sharedMsgId_ itemForwarded itemTimed live userMention hasLink_ brokerTs forwardedByMember (toMsgVerified (signMessagesRequired cd) msgSigned) createdAt
|
|
ci' <- case toChatInfo cd of
|
|
GroupChat g _ | not (null mentions') -> createGroupCIMentions db g ci mentions'
|
|
_ -> pure ci
|
|
pure (ci', cInfo')
|
|
where
|
|
groupMentions db g membership = do
|
|
mentions' <- getRcvCIMentions db user g ft_ mentions
|
|
-- messages of blocked members are hidden, they should not mention user
|
|
let senderBlocked = case cd of
|
|
CDGroupRcv _g _scope m -> memberBlocked m
|
|
_ -> False
|
|
userReply = case cmToQuotedMsg chatMsgEvent of
|
|
Just QuotedMsg {msgRef = MsgRef {memberId = Just mId}} -> sameMemberId mId membership
|
|
_ -> False
|
|
in pure (mentions', userMentioned membership senderBlocked userReply mentions')
|
|
memberChatStats :: Bool -> Maybe (Int, MemberAttention, Int)
|
|
memberChatStats userMention = case cd of
|
|
CDGroupRcv _g (Just scope) m ->
|
|
let unread = fromEnum $ ciCreateStatus content == CISRcvNew
|
|
in Just (unread, memberAttentionChange unread (Just brokerTs) (Just m) scope, fromEnum userMention)
|
|
CDChannelRcv _g (Just scope) ->
|
|
let unread = fromEnum $ ciCreateStatus content == CISRcvNew
|
|
in Just (unread, memberAttentionChange unread (Just brokerTs) Nothing scope, fromEnum userMention)
|
|
_ -> Nothing
|
|
|
|
-- TODO [mentions] optimize by avoiding unnecessary parsing
|
|
mkChatItem :: (ChatTypeI c, MsgDirectionI d) => ChatDirection c d -> ShowGroupAsSender -> ChatItemId -> CIContent d -> Maybe (CIFile d) -> Maybe (CIQuote c) -> Maybe SharedMsgId -> Maybe CIForwardedFrom -> Maybe CITimed -> Bool -> Bool -> ChatItemTs -> Maybe GroupMemberId -> Maybe MsgVerified -> UTCTime -> ChatItem c d
|
|
mkChatItem cd showGroupAsSender ciId content file quotedItem sharedMsgId itemForwarded itemTimed live userMention itemTs forwardedByMember msgVerified currentTs =
|
|
let ts@(_, ParsedMarkdown ft_ _) = ciContentTexts content
|
|
hasLink_ = ciContentHasLink content ft_
|
|
in mkChatItem_ cd showGroupAsSender ciId content ts file quotedItem sharedMsgId itemForwarded itemTimed live userMention hasLink_ itemTs forwardedByMember msgVerified currentTs
|
|
|
|
mkChatItem_ :: (ChatTypeI c, MsgDirectionI d) => ChatDirection c d -> ShowGroupAsSender -> ChatItemId -> CIContent d -> (Text, ParsedMarkdown) -> Maybe (CIFile d) -> Maybe (CIQuote c) -> Maybe SharedMsgId -> Maybe CIForwardedFrom -> Maybe CITimed -> Bool -> Bool -> Bool -> ChatItemTs -> Maybe GroupMemberId -> Maybe MsgVerified -> UTCTime -> ChatItem c d
|
|
mkChatItem_ cd showGroupAsSender ciId content (itemText, ParsedMarkdown formattedText markdownBlocks) file quotedItem sharedMsgId itemForwarded itemTimed live userMention hasLink_ itemTs forwardedByMember msgVerified currentTs =
|
|
let itemStatus = ciCreateStatus content
|
|
meta = mkCIMeta ciId content itemText itemStatus Nothing sharedMsgId itemForwarded Nothing False itemTimed (justTrue live) userMention hasLink_ currentTs itemTs forwardedByMember showGroupAsSender msgVerified currentTs currentTs
|
|
in ChatItem {chatDir = toCIDirection cd, meta, content, mentions = M.empty, formattedText, markdownBlocks, quotedItem, reactions = [], file}
|
|
|
|
ciContentHasLink :: CIContent d -> Maybe MarkdownList -> Bool
|
|
ciContentHasLink content ft_ = case ciMsgContent content of
|
|
Just mc -> msgContentHasLink mc ft_
|
|
Nothing -> False
|
|
|
|
msgContentHasLink :: MsgContent -> Maybe MarkdownList -> Bool
|
|
msgContentHasLink mc ft_ = case msgContentTag mc of
|
|
MCLink_ -> True
|
|
_ -> maybe False hasLinks ft_
|
|
|
|
prepareAgentCreation :: User -> CommandFunction -> Bool -> SConnectionMode c -> CM (CommandId, ConnId)
|
|
prepareAgentCreation user cmdFunction enableNtfs cMode = do
|
|
cmdId <- withStore' $ \db -> createCommand db user Nothing cmdFunction
|
|
connId <- withAgent $ \a -> prepareConnectionToCreate a (aUserId user) enableNtfs cMode PQSupportOff
|
|
pure (cmdId, connId)
|
|
|
|
prepareAgentJoin :: User -> Bool -> ConnectionRequestUri c -> CM ((CommandId, ConnId), ProofPresHeader)
|
|
prepareAgentJoin user enableNtfs cReqUri = do
|
|
cmdId <- withStore' $ \db -> createCommand db user Nothing CFJoinConn
|
|
(connId, binding) <- withAgent $ \a -> prepareConnectionToJoin a (aUserId user) enableNtfs cReqUri PQSupportOff
|
|
pure ((cmdId, connId), directPresHeader binding)
|
|
|
|
joinAgentConnectionAsync :: CommandId -> Bool -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> SubscriptionMode -> CM ()
|
|
joinAgentConnectionAsync cmdId updateConn connId enableNtfs cReqUri cInfo subMode =
|
|
withAgent $ \a -> joinConnectionAsync a (aCorrId cmdId) updateConn connId enableNtfs cReqUri cInfo PQSupportOff subMode
|
|
|
|
allowAgentConnectionAsync :: MsgEncodingI e => User -> Connection -> ConfirmationId -> Maybe GroupInfoKeys -> ChatMsgEvent e -> CM ()
|
|
allowAgentConnectionAsync user conn@Connection {pqSupport} confId gInfo_ msg = do
|
|
let signing_ = case gInfo_ of
|
|
Just gInfo@(GIK g _) | useRelays' g || maxVersion (peerChatVRange conn) >= relayWebCapVersion -> groupMsgSigning False gInfo msg
|
|
_ -> Nothing
|
|
dm <- encodeConnInfoSigning pqSupport signing_ msg
|
|
allowAgentConnectionInfo user conn confId dm
|
|
|
|
allowAgentConnectionInfo :: User -> Connection -> ConfirmationId -> ByteString -> CM ()
|
|
allowAgentConnectionInfo user conn@Connection {connId} confId dm = do
|
|
cmdId <- withStore' $ \db -> createCommand db user (Just connId) CFAllowConn
|
|
withAgent $ \a -> allowConnectionAsync a (aCorrId cmdId) (aConnId conn) confId dm
|
|
withStore' $ \db -> updateConnectionStatus db conn ConnAccepted
|
|
|
|
prepareAgentAccept :: User -> Bool -> InvitationId -> PQSupport -> CM ((CommandId, ConnId), ProofPresHeader)
|
|
prepareAgentAccept user enableNtfs invId pqSup = do
|
|
cmdId <- withStore' $ \db -> createCommand db user Nothing CFAcceptContact
|
|
(connId, binding) <- withAgent $ \a -> prepareConnectionToAccept a (aUserId user) enableNtfs invId pqSup
|
|
pure ((cmdId, connId), directPresHeader binding)
|
|
|
|
agentAcceptContactAsync :: MsgEncodingI e => CommandId -> ConnId -> Bool -> InvitationId -> ChatMsgEvent e -> PQSupport -> SubscriptionMode -> CM ()
|
|
agentAcceptContactAsync cmdId connId enableNtfs invId msg pqSup subMode = do
|
|
dm <- encodeConnInfoPQ pqSup msg
|
|
withAgent $ \a -> acceptContactAsync a (aCorrId cmdId) connId enableNtfs invId dm pqSup subMode
|
|
|
|
deleteAgentConnectionAsync :: ConnId -> CM ()
|
|
deleteAgentConnectionAsync acId = deleteAgentConnectionAsync' acId False
|
|
{-# INLINE deleteAgentConnectionAsync #-}
|
|
|
|
deleteAgentConnectionAsync' :: ConnId -> Bool -> CM ()
|
|
deleteAgentConnectionAsync' acId waitDelivery = do
|
|
withAgent (\a -> deleteConnectionAsync a waitDelivery acId) `catchAllErrors` eToView
|
|
|
|
deleteAgentConnectionsAsync :: [ConnId] -> CM ()
|
|
deleteAgentConnectionsAsync acIds = deleteAgentConnectionsAsync' acIds False
|
|
{-# INLINE deleteAgentConnectionsAsync #-}
|
|
|
|
deleteAgentConnectionsAsync' :: [ConnId] -> Bool -> CM ()
|
|
deleteAgentConnectionsAsync' [] _ = pure ()
|
|
deleteAgentConnectionsAsync' acIds waitDelivery = do
|
|
withAgent (\a -> deleteConnectionsAsync a waitDelivery acIds) `catchAllErrors` eToView
|
|
|
|
setAgentConnShortLinkAsync :: User -> Connection -> UserConnLinkData 'CMContact -> Maybe CRClientData -> CM ()
|
|
setAgentConnShortLinkAsync user conn@Connection {connId} userLinkData crClientData_ = do
|
|
cmdId <- withStore' $ \db -> createCommand db user (Just connId) CFSetShortLink
|
|
withAgent $ \a -> setConnShortLinkAsync a (aCorrId cmdId) (aConnId conn) userLinkData crClientData_
|
|
|
|
getAgentConnShortLinkAsync :: User -> CommandFunction -> Maybe Connection -> ShortLinkContact -> CM (CommandId, ConnId)
|
|
getAgentConnShortLinkAsync user cmdFunc conn_ shortLink = do
|
|
shortLink' <- restoreShortLink' shortLink
|
|
cmdId <- withStore' $ \db -> createCommand db user (dbConnId <$> conn_) cmdFunc
|
|
connId <- withAgent $ \a -> getConnShortLinkAsync a (aUserId user) (aCorrId cmdId) (aConnId <$> conn_) shortLink'
|
|
pure (cmdId, connId)
|
|
|
|
agentXFTPDeleteRcvFile :: RcvFileId -> FileTransferId -> CM ()
|
|
agentXFTPDeleteRcvFile aFileId fileId = do
|
|
lift $ withAgent' (`xftpDeleteRcvFile` aFileId)
|
|
withStore' $ \db -> setRcvFTAgentDeleted db fileId
|
|
|
|
agentXFTPDeleteRcvFiles :: [(XFTPRcvFile, FileTransferId)] -> CM' ()
|
|
agentXFTPDeleteRcvFiles rcvFiles = do
|
|
let rcvFiles' = filter (not . agentRcvFileDeleted . fst) rcvFiles
|
|
rfIds = mapMaybe fileIds rcvFiles'
|
|
withAgent' $ \a -> xftpDeleteRcvFiles a (map fst rfIds)
|
|
void . withStoreBatch' $ \db -> map (setRcvFTAgentDeleted db . snd) rfIds
|
|
where
|
|
fileIds :: (XFTPRcvFile, FileTransferId) -> Maybe (RcvFileId, FileTransferId)
|
|
fileIds (XFTPRcvFile {agentRcvFileId = Just (AgentRcvFileId aFileId)}, fileId) = Just (aFileId, fileId)
|
|
fileIds _ = Nothing
|
|
|
|
agentXFTPDeleteSndFileRemote :: User -> XFTPSndFile -> FileTransferId -> CM' ()
|
|
agentXFTPDeleteSndFileRemote user xsf fileId =
|
|
agentXFTPDeleteSndFilesRemote user [(xsf, fileId)]
|
|
|
|
agentXFTPDeleteSndFilesRemote :: User -> [(XFTPSndFile, FileTransferId)] -> CM' ()
|
|
agentXFTPDeleteSndFilesRemote user sndFiles = do
|
|
(_errs, redirects) <- partitionEithers <$> withStoreBatch' (\db -> map (lookupFileTransferRedirectMeta db user . snd) sndFiles)
|
|
let redirects' = mapMaybe mapRedirectMeta $ concat redirects
|
|
sndFilesAll = redirects' <> sndFiles
|
|
sndFilesAll' = filter (not . agentSndFileDeleted . fst) sndFilesAll
|
|
-- while file is being prepared and uploaded, it would not have description available;
|
|
-- this partitions files into those with and without descriptions -
|
|
-- files with description are deleted remotely, files without description are deleted internally
|
|
(sfsNoDescr, sfsWithDescr) <- partitionSndDescr sndFilesAll' [] []
|
|
withAgent' $ \a -> xftpDeleteSndFilesInternal a sfsNoDescr
|
|
withAgent' $ \a -> xftpDeleteSndFilesRemote a (aUserId user) sfsWithDescr
|
|
void . withStoreBatch' $ \db -> map (setSndFTAgentDeleted db user . snd) sndFilesAll'
|
|
where
|
|
mapRedirectMeta :: FileTransferMeta -> Maybe (XFTPSndFile, FileTransferId)
|
|
mapRedirectMeta FileTransferMeta {fileId = fileId, xftpSndFile = Just sndFileRedirect} = Just (sndFileRedirect, fileId)
|
|
mapRedirectMeta _ = Nothing
|
|
partitionSndDescr ::
|
|
[(XFTPSndFile, FileTransferId)] ->
|
|
[SndFileId] ->
|
|
[(SndFileId, ValidFileDescription 'FSender)] ->
|
|
CM' ([SndFileId], [(SndFileId, ValidFileDescription 'FSender)])
|
|
partitionSndDescr [] filesWithoutDescr filesWithDescr = pure (filesWithoutDescr, filesWithDescr)
|
|
partitionSndDescr ((XFTPSndFile {agentSndFileId = AgentSndFileId aFileId, privateSndFileDescr}, _) : xsfs) filesWithoutDescr filesWithDescr =
|
|
case privateSndFileDescr of
|
|
Nothing -> partitionSndDescr xsfs (aFileId : filesWithoutDescr) filesWithDescr
|
|
Just sfdText ->
|
|
tryAllErrors' (parseFileDescription sfdText) >>= \case
|
|
Left _ -> partitionSndDescr xsfs (aFileId : filesWithoutDescr) filesWithDescr
|
|
Right sfd -> partitionSndDescr xsfs filesWithoutDescr ((aFileId, sfd) : filesWithDescr)
|
|
|
|
connRequestPQEncryption :: ConnectionRequestUri c -> Maybe PQEncryption
|
|
connRequestPQEncryption = \case
|
|
CRContactUri _ rks -> pqEnc . snd <$> rks
|
|
CRInvitationUri _ e2e -> Just $ pqEnc e2e
|
|
where
|
|
pqEnc (CR.E2ERatchetParamsUri _ _ _ pq) = PQEncryption $ isJust pq
|
|
|
|
createRcvFeatureItems :: User -> Contact -> Contact -> CM' ()
|
|
createRcvFeatureItems user ct ct' =
|
|
createFeatureItems user ct ct' CDDirectRcv CIRcvChatFeature CIRcvChatPreference contactPreference
|
|
|
|
createSndFeatureItems :: User -> Contact -> Contact -> CM' ()
|
|
createSndFeatureItems user ct ct' =
|
|
createFeatureItems user ct ct' CDDirectSnd CISndChatFeature CISndChatPreference getPref
|
|
where
|
|
getPref ContactUserPreference {userPreference} = case userPreference of
|
|
CUPContact {preference} -> preference
|
|
CUPUser {preference} -> preference
|
|
|
|
-- Used when contact is changed after creating initial feature items via createFeatureEnabledItems_
|
|
-- (APIChangePreparedContactUser, APIConnectPreparedContact with incognito = True);
|
|
-- creates feature items with CDDirectRcv direction so that changed feature items stay in the same place in chat view
|
|
createContactChangedFeatureItems :: User -> Contact -> Contact -> CM' ()
|
|
createContactChangedFeatureItems user ct ct' =
|
|
createFeatureItems user ct ct' CDDirectRcv CIRcvChatFeature CIRcvChatPreference getPref
|
|
where
|
|
getPref ContactUserPreference {userPreference} = case userPreference of
|
|
CUPContact {preference} -> preference
|
|
CUPUser {preference} -> preference
|
|
|
|
type FeatureContent a d = ChatFeature -> a -> Maybe Int -> CIContent d
|
|
|
|
createFeatureEnabledItems :: User -> Contact -> CM ()
|
|
createFeatureEnabledItems user ct = createFeatureEnabledItems_ user ct >>= toView . CEvtNewChatItems user
|
|
|
|
createFeatureEnabledItems_ :: User -> Contact -> CM [AChatItem]
|
|
createFeatureEnabledItems_ user ct@Contact {mergedPreferences} =
|
|
forM allChatFeatures $ \(ACF f) -> do
|
|
let state = featureState $ getContactUserPreference f mergedPreferences
|
|
createChatItem user (CDDirectRcv ct) False (uncurry (CIRcvChatFeature $ chatFeature f) state) Nothing Nothing Nothing
|
|
|
|
createFeatureItems ::
|
|
MsgDirectionI d =>
|
|
User ->
|
|
Contact ->
|
|
Contact ->
|
|
(Contact -> ChatDirection 'CTDirect d) ->
|
|
FeatureContent PrefEnabled d ->
|
|
FeatureContent FeatureAllowed d ->
|
|
(forall f. ContactUserPreference (FeaturePreference f) -> FeaturePreference f) ->
|
|
CM' ()
|
|
createFeatureItems user ct ct' = createContactsFeatureItems user [(ct, ct')]
|
|
|
|
createContactsFeatureItems ::
|
|
forall d.
|
|
MsgDirectionI d =>
|
|
User ->
|
|
[(Contact, Contact)] ->
|
|
(Contact -> ChatDirection 'CTDirect d) ->
|
|
FeatureContent PrefEnabled d ->
|
|
FeatureContent FeatureAllowed d ->
|
|
(forall f. ContactUserPreference (FeaturePreference f) -> FeaturePreference f) ->
|
|
CM' ()
|
|
createContactsFeatureItems user cts chatDir ciFeature ciOffer getPref = do
|
|
let dirsCIContents = map contactChangedFeatures cts
|
|
(errs, acis) <- partitionEithers <$> createChatItems user Nothing dirsCIContents
|
|
unless (null errs) $ toView' $ CEvtChatErrors errs
|
|
toView' $ CEvtNewChatItems user acis
|
|
where
|
|
contactChangedFeatures :: (Contact, Contact) -> (ChatDirection 'CTDirect d, ShowGroupAsSender, [(CIContent d, Maybe SharedMsgId, Maybe MsgSigStatus)])
|
|
contactChangedFeatures (Contact {mergedPreferences = cups}, ct'@Contact {mergedPreferences = cups'}) = do
|
|
let contents = mapMaybe (\(ACF f) -> featureCIContent_ f) allChatFeatures
|
|
(chatDir ct', False, contents)
|
|
where
|
|
featureCIContent_ :: forall f. FeatureI f => SChatFeature f -> Maybe (CIContent d, Maybe SharedMsgId, Maybe MsgSigStatus)
|
|
featureCIContent_ f
|
|
| state /= state' = Just (fContent ciFeature state', Nothing, Nothing)
|
|
| prefState /= prefState' = Just (fContent ciOffer prefState', Nothing, Nothing)
|
|
| otherwise = Nothing
|
|
where
|
|
fContent :: FeatureContent a d -> (a, Maybe Int) -> CIContent d
|
|
fContent ci (s, param) = ci f' s param
|
|
f' = chatFeature f
|
|
state = featureState cup
|
|
state' = featureState cup'
|
|
prefState = preferenceState $ getPref cup
|
|
prefState' = preferenceState $ getPref cup'
|
|
cup = getContactUserPreference f cups
|
|
cup' = getContactUserPreference f cups'
|
|
|
|
groupFeatures :: GroupInfo -> [AGroupFeature]
|
|
groupFeatures g = if useRelays' g then channelGroupFeatures else regularGroupFeatures
|
|
|
|
createGroupFeatureChangedItems :: MsgDirectionI d => User -> ChatDirection 'CTGroup d -> (GroupFeature -> GroupPreference -> Maybe Int -> Maybe GroupMemberRole -> CIContent d) -> GroupInfo -> GroupInfo -> CM ()
|
|
createGroupFeatureChangedItems user cd ciContent GroupInfo {fullGroupPreferences = gps} g'@GroupInfo {fullGroupPreferences = gps'} =
|
|
forM_ (groupFeatures g') $ \(AGF f) -> do
|
|
let state = groupFeatureState $ getGroupPreference f gps
|
|
pref' = getGroupPreference f gps'
|
|
state'@(_, param', role') = groupFeatureState pref'
|
|
when (state /= state') $
|
|
createInternalChatItem user cd (ciContent (toGroupFeature f) (toGroupPreference pref') param' role') Nothing
|
|
|
|
sameGroupProfileInfo :: GroupProfile -> GroupProfile -> Bool
|
|
sameGroupProfileInfo p p' = p {groupPreferences = Nothing} == p' {groupPreferences = Nothing}
|
|
|
|
createGroupFeatureItems :: MsgDirectionI d => User -> ChatDirection 'CTGroup d -> (GroupFeature -> GroupPreference -> Maybe Int -> Maybe GroupMemberRole -> CIContent d) -> GroupInfo -> CM ()
|
|
createGroupFeatureItems user cd ciContent g = createGroupFeatureItems_ user cd False ciContent g >>= toView . CEvtNewChatItems user
|
|
|
|
createGroupFeatureItems_ :: MsgDirectionI d => User -> ChatDirection 'CTGroup d -> ShowGroupAsSender -> (GroupFeature -> GroupPreference -> Maybe Int -> Maybe GroupMemberRole -> CIContent d) -> GroupInfo -> CM [AChatItem]
|
|
createGroupFeatureItems_ user cd showGroupAsSender ciContent g@GroupInfo {fullGroupPreferences} =
|
|
forM (groupFeatures g) $ \(AGF f) -> do
|
|
let p = getGroupPreference f fullGroupPreferences
|
|
(_, param, role) = groupFeatureState p
|
|
createChatItem user cd showGroupAsSender (ciContent (toGroupFeature f) (toGroupPreference p) param role) Nothing Nothing Nothing
|
|
|
|
createInternalChatItem :: (ChatTypeI c, MsgDirectionI d) => User -> ChatDirection c d -> CIContent d -> Maybe UTCTime -> CM ()
|
|
createInternalChatItem user cd content itemTs_ = do
|
|
ci <- createChatItem user cd False content Nothing Nothing itemTs_
|
|
toView $ CEvtNewChatItems user [ci]
|
|
|
|
createChatItem :: (ChatTypeI c, MsgDirectionI d) => User -> ChatDirection c d -> ShowGroupAsSender -> CIContent d -> Maybe SharedMsgId -> Maybe MsgSigStatus -> Maybe UTCTime -> CM AChatItem
|
|
createChatItem user cd showGroupAsSender content sharedMsgId msgSigned itemTs_ =
|
|
lift (createChatItems user itemTs_ [(cd, showGroupAsSender, [(content, sharedMsgId, msgSigned)])]) >>= \case
|
|
[Right ci] -> pure ci
|
|
[Left e] -> throwError e
|
|
rs -> throwChatError $ CEInternalError $ "createInternalChatItem: expected 1 result, got " <> show (length rs)
|
|
|
|
-- Supports items with shared msg ID that are created for all conversation parties, but were not communicated via the usual messages.
|
|
-- This includes address welcome message and contact request message.
|
|
createChatItems ::
|
|
forall c d.
|
|
(ChatTypeI c, MsgDirectionI d) =>
|
|
User ->
|
|
Maybe UTCTime ->
|
|
[(ChatDirection c d, ShowGroupAsSender, [(CIContent d, Maybe SharedMsgId, Maybe MsgSigStatus)])] ->
|
|
CM' [Either ChatError AChatItem]
|
|
createChatItems user itemTs_ dirsCIContents = do
|
|
createdAt <- liftIO getCurrentTime
|
|
let itemTs = fromMaybe (roundDownToSecond createdAt) itemTs_
|
|
cxt <- asks storeCxt
|
|
void . withStoreBatch' $ \db -> map (updateChat db cxt createdAt) dirsCIContents
|
|
withStoreBatch' $ \db -> concatMap (createACIs db itemTs createdAt) dirsCIContents
|
|
where
|
|
updateChat :: DB.Connection -> StoreCxt -> UTCTime -> (ChatDirection c d, ShowGroupAsSender, [(CIContent d, Maybe SharedMsgId, Maybe MsgSigStatus)]) -> IO ()
|
|
updateChat db cxt createdAt (cd, _, contents)
|
|
| any (\(content, _, _) -> ciRequiresAttention content) contents || contactChatDeleted cd = void $ updateChatTsStats db cxt user cd createdAt memberChatStats
|
|
| otherwise = pure ()
|
|
where
|
|
memberChatStats :: Maybe (Int, MemberAttention, Int)
|
|
memberChatStats = case cd of
|
|
CDGroupRcv _g (Just scope) m -> do
|
|
let unread = length $ filter (\(content, _, _) -> ciRequiresAttention content) contents
|
|
in Just (unread, memberAttentionChange unread itemTs_ (Just m) scope, 0)
|
|
_ -> Nothing
|
|
createACIs :: DB.Connection -> UTCTime -> UTCTime -> (ChatDirection c d, ShowGroupAsSender, [(CIContent d, Maybe SharedMsgId, Maybe MsgSigStatus)]) -> [IO AChatItem]
|
|
createACIs db itemTs createdAt (cd, showGroupAsSender, contents) = map createACI contents
|
|
where
|
|
createACI (content, sharedMsgId, msgSigned) = do
|
|
let hasLink_ = ciContentHasLink content Nothing
|
|
msgVerified = toMsgVerified False msgSigned
|
|
ciId <- createNewChatItemNoMsg db user cd showGroupAsSender content sharedMsgId hasLink_ msgVerified itemTs createdAt
|
|
let ci = mkChatItem cd showGroupAsSender ciId content Nothing Nothing Nothing Nothing Nothing False False itemTs Nothing msgVerified createdAt
|
|
pure $ AChatItem (chatTypeI @c) (msgDirection @d) (toChatInfo cd) ci
|
|
|
|
-- rcvMem_ Nothing means message from channel - treated same as message from moderator,
|
|
-- e.g. it can reset unanswered counter if newer than last unanswered message.
|
|
memberAttentionChange :: Int -> (Maybe UTCTime) -> Maybe GroupMember -> GroupChatScopeInfo -> MemberAttention
|
|
memberAttentionChange unread brokerTs_ rcvMem_ = \case
|
|
GCSIMemberSupport (Just suppMem)
|
|
| maybe False ((groupMemberId' suppMem ==) . groupMemberId') rcvMem_ -> MAInc unread brokerTs_
|
|
| msgIsNewerThanLastUnanswered -> MAReset
|
|
| otherwise -> MAInc 0 Nothing
|
|
where
|
|
msgIsNewerThanLastUnanswered = case (supportChat suppMem >>= lastMsgFromMemberTs, brokerTs_) of
|
|
(Just lastMsgTs, Just brokerTs) -> lastMsgTs < brokerTs
|
|
_ -> False
|
|
GCSIMemberSupport Nothing -> MAInc 0 Nothing
|
|
|
|
createLocalChatItems ::
|
|
User ->
|
|
ChatDirection 'CTLocal 'MDSnd ->
|
|
NonEmpty (CIContent 'MDSnd, Maybe (CIFile 'MDSnd), Maybe CIForwardedFrom, (Text, ParsedMarkdown)) ->
|
|
UTCTime ->
|
|
CM [ChatItem 'CTLocal 'MDSnd]
|
|
createLocalChatItems user cd itemsData createdAt = do
|
|
cxt <- chatStoreCxt
|
|
void $ withStore' $ \db -> updateChatTsStats db cxt user cd createdAt Nothing
|
|
(errs, items) <- lift $ partitionEithers <$> withStoreBatch' (\db -> map (createItem db) $ L.toList itemsData)
|
|
unless (null errs) $ toView $ CEvtChatErrors errs
|
|
pure items
|
|
where
|
|
createItem :: DB.Connection -> (CIContent 'MDSnd, Maybe (CIFile 'MDSnd), Maybe CIForwardedFrom, (Text, ParsedMarkdown)) -> IO (ChatItem 'CTLocal 'MDSnd)
|
|
createItem db (content, ciFile, itemForwarded, ts@(_, ParsedMarkdown ft_ _)) = do
|
|
let hasLink_ = ciContentHasLink content ft_
|
|
itemTs = roundDownToSecond createdAt
|
|
ciId <- createNewChatItem_ db user cd False Nothing Nothing content (Nothing, Nothing, Nothing, Nothing, Nothing) itemForwarded Nothing False False hasLink_ itemTs Nothing Nothing Nothing Nothing createdAt
|
|
forM_ ciFile $ \CIFile {fileId} -> updateFileTransferChatItemId db fileId ciId createdAt
|
|
pure $ mkChatItem_ cd False ciId content ts ciFile Nothing Nothing itemForwarded Nothing False False hasLink_ itemTs Nothing Nothing createdAt
|
|
|
|
withUser' :: (User -> CM ChatResponse) -> CM ChatResponse
|
|
withUser' action =
|
|
asks currentUser
|
|
>>= readTVarIO
|
|
>>= maybe (throwChatError CENoActiveUser) action
|
|
|
|
withUser :: (User -> CM ChatResponse) -> CM ChatResponse
|
|
withUser action = withUser' $ \user ->
|
|
ifM (lift chatStarted) (action user) (throwChatError CEChatNotStarted)
|
|
|
|
withUser_ :: CM ChatResponse -> CM ChatResponse
|
|
withUser_ = withUser . const
|
|
|
|
withUserId' :: UserId -> (User -> CM ChatResponse) -> CM ChatResponse
|
|
withUserId' userId action = withUser' $ \user -> do
|
|
checkSameUser userId user
|
|
action user
|
|
|
|
withUserId :: UserId -> (User -> CM ChatResponse) -> CM ChatResponse
|
|
withUserId userId action = withUser $ \user -> do
|
|
checkSameUser userId user
|
|
action user
|
|
|
|
checkSameUser :: UserId -> User -> CM ()
|
|
checkSameUser userId User {userId = activeUserId} = when (userId /= activeUserId) $ throwChatError (CEDifferentActiveUser userId activeUserId)
|
|
|
|
chatStarted :: CM' Bool
|
|
chatStarted = fmap isJust . readTVarIO =<< asks agentAsync
|
|
|
|
waitChatStartedAndActivated :: CM' ()
|
|
waitChatStartedAndActivated = do
|
|
agentStarted <- asks agentAsync
|
|
chatActivated <- asks chatActivated
|
|
atomically $ do
|
|
started <- readTVar agentStarted
|
|
activated <- readTVar chatActivated
|
|
unless (isJust started && activated) retry
|
|
|
|
chatStoreCxt :: CM StoreCxt
|
|
chatStoreCxt = asks storeCxt
|
|
{-# INLINE chatStoreCxt #-}
|
|
|
|
chatVersionRange :: CM VersionRangeChat
|
|
chatVersionRange = lift chatVersionRange'
|
|
{-# INLINE chatVersionRange #-}
|
|
|
|
chatVersionRange' :: CM' VersionRangeChat
|
|
chatVersionRange' = do
|
|
ChatConfig {chatVRange} <- asks config
|
|
pure chatVRange
|
|
{-# INLINE chatVersionRange' #-}
|
|
|
|
adminContactReq :: ConnReqContact
|
|
adminContactReq =
|
|
either error id $ strDecode "simplex:/contact#/?v=1&smp=smp%3A%2F%2FPQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo%3D%40smp6.simplex.im%2FK1rslx-m5bpXVIdMZg9NLUZ_8JBm8xTt%23MCowBQYDK2VuAyEALDeVe-sG8mRY22LsXlPgiwTNs9dbiLrNuA7f3ZMAJ2w%3D"
|
|
|
|
contactCReqHash :: ConnReqContact -> ConnReqUriHash
|
|
contactCReqHash (CRContactUri crData _) = ConnReqUriHash . C.sha256Hash . strEncode $ CRContactUri crData Nothing
|
|
|
|
simplexChatImage :: ImageData
|
|
simplexChatImage = ImageData "data:image/jpg;base64,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"
|
|
|
|
simplexTeamContactProfile :: Profile
|
|
simplexTeamContactProfile =
|
|
Profile
|
|
{ displayName = "Ask SimpleX Team",
|
|
fullName = "",
|
|
shortDescr = Just "Send questions about SimpleX Chat app and your suggestions",
|
|
description = Nothing,
|
|
image = Just simplexChatImage,
|
|
contactLink = Just $ CLFull adminContactReq,
|
|
peerType = Nothing,
|
|
preferences = Nothing,
|
|
badge = Nothing,
|
|
contactDomain = Nothing
|
|
}
|
|
|
|
timeItToView :: String -> CM' a -> CM' a
|
|
timeItToView s action = do
|
|
t1 <- liftIO getCurrentTime
|
|
a <- action
|
|
t2 <- liftIO getCurrentTime
|
|
let diff = diffToMilliseconds $ diffUTCTime t2 t1
|
|
toView' $ CEvtTimedAction s diff
|
|
pure a
|
|
|
|
epochStart :: UTCTime
|
|
epochStart = UTCTime (fromGregorian 1970 1 1) (secondsToDiffTime 0)
|
|
|
|
drgRandomBytes :: Int -> CM ByteString
|
|
drgRandomBytes n = asks random >>= atomically . C.randomBytes n
|