Line data Source code
1 : /*
2 : * Copyright (C) 2004-2026 Savoir-faire Linux Inc.
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 : */
17 : #pragma once
18 :
19 : #include "jami.h"
20 : #include "jamidht/account_manager.h"
21 : #include "jamidht/conversation.h"
22 : #include "jamidht/conversationrepository.h"
23 : #include "jamidht/jami_contact.h"
24 :
25 : #include <mutex>
26 : #include <optional>
27 : #include <msgpack.hpp>
28 :
29 : namespace jami {
30 : static constexpr const char MIME_TYPE_INVITE[] {"application/invite"};
31 : static constexpr const char MIME_TYPE_GIT[] {"application/im-gitmessage-id"};
32 :
33 : class SIPCall;
34 :
35 : struct SyncMsg
36 : {
37 : DeviceSync ds;
38 : std::map<std::string, ConvInfo> c;
39 : std::map<std::string, ConversationRequest> cr;
40 : // p is conversation's preferences. It's not stored in c, as
41 : // we can update the preferences without touching any confInfo.
42 : std::map<std::string, std::map<std::string, std::string>> p;
43 : // Last displayed messages [[deprecated]]
44 : std::map<std::string, std::map<std::string, std::string>> ld;
45 : // Read & fetched status
46 : /*
47 : * {{ convId,
48 : * { memberUri,, {
49 : * {"fetch", "commitId"},
50 : * {"fetched_ts", "timestamp"},
51 : * {"read", "commitId"},
52 : * {"read_ts", "timestamp"}
53 : * }
54 : * }}
55 : */
56 : std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> ms;
57 :
58 782 : MSGPACK_DEFINE(ds, c, cr, p, ld, ms)
59 :
60 : /**
61 : * Whether this message carries contact/conversation *list* state, i.e.
62 : * contacts, devices, trust requests, conversations or conversation
63 : * requests. Propagating such a change may require (re)connecting to
64 : * devices that are not currently connected. Metadata-only messages
65 : * (preferences `p`, read/fetched status `ms`, deprecated last-displayed
66 : * `ld`) return false and only need to ride existing connections.
67 : */
68 1735 : bool affectsList() const
69 : {
70 1735 : return !ds.devices.empty() || !ds.peers.empty() || !ds.trust_requests.empty() || !c.empty() || !cr.empty();
71 : }
72 : };
73 :
74 : using ChannelCb = std::function<bool(const std::shared_ptr<dhtnet::ChannelSocket>&)>;
75 : using NeedSocketCb
76 : = std::function<void(const std::string&, const std::string&, ChannelCb&&, const std::string&, bool noNewSocket)>;
77 : using SengMsgCb
78 : = std::function<uint64_t(const std::string&, const DeviceId&, std::map<std::string, std::string>, uint64_t)>;
79 : using NeedsSyncingCb = std::function<void(std::shared_ptr<SyncMsg>&&)>;
80 : using OneToOneRecvCb = std::function<void(const std::string&, const std::string&)>;
81 :
82 : class ConversationModule
83 : {
84 : public:
85 : ConversationModule(std::shared_ptr<JamiAccount> account,
86 : std::shared_ptr<AccountManager> accountManager,
87 : NeedsSyncingCb&& needsSyncingCb,
88 : SengMsgCb&& sendMsgCb,
89 : NeedSocketCb&& onNeedSocket,
90 : NeedSocketCb&& onNeedSwarmSocket,
91 : OneToOneRecvCb&& oneToOneRecvCb,
92 : bool autoLoadConversations = true);
93 793 : ~ConversationModule() = default;
94 :
95 : void setAccountManager(std::shared_ptr<AccountManager> accountManager);
96 :
97 : /**
98 : * Refresh information about conversations
99 : */
100 : void loadConversations();
101 :
102 : void initPresence();
103 :
104 : void loadSingleConversation(const std::string& convId);
105 :
106 : #ifdef LIBJAMI_TEST
107 : void onBootstrapStatus(const std::function<void(std::string, Conversation::BootstrapStatus)>& cb);
108 : void onFetchCompleted(const std::function<void(const std::string&, const std::string&, bool)>& cb);
109 : #endif
110 :
111 : void monitor();
112 :
113 : /**
114 : * Bootstrap swarm managers to other peers
115 : */
116 : void bootstrap(const std::string& convId = "");
117 :
118 : /**
119 : * Clear not removed fetch
120 : */
121 : void clearPendingFetch();
122 :
123 : /**
124 : * Reload requests from file
125 : */
126 : void reloadRequests();
127 :
128 : /**
129 : * Return all conversation's id (including syncing ones)
130 : */
131 : std::vector<std::string> getConversations() const;
132 :
133 : /**
134 : * Get related conversation with member
135 : * @param uri The member to search for
136 : * @return the conversation id if found else empty
137 : */
138 : std::string getOneToOneConversation(const std::string& uri) const noexcept;
139 :
140 : /**
141 : * Replace linked conversation in contact's details
142 : * @param uri Of the contact
143 : * @param oldConv Current conversation
144 : * @param newConv
145 : * @return if replaced
146 : */
147 : bool updateConvForContact(const std::string& uri, const std::string& oldConv, const std::string& newConv);
148 :
149 : /**
150 : * Return conversation's requests
151 : */
152 : std::vector<std::map<std::string, std::string>> getConversationRequests() const;
153 :
154 : /**
155 : * Called when detecting a new trust request with linked one to one
156 : * @param uri Sender's URI
157 : * @param conversationId Related conversation's id
158 : * @param payload VCard
159 : * @param received Received time
160 : * @param invited Sender-embedded invite timestamp (default: unset, meaning unknown)
161 : */
162 : void onTrustRequest(const std::string& uri,
163 : const std::string& conversationId,
164 : const std::vector<uint8_t>& payload,
165 : TimePoint received,
166 : TimePoint invited = {});
167 :
168 : /**
169 : * Called when receiving a new conversation's request
170 : * @param from Sender
171 : * @param value Conversation's request
172 : */
173 : void onConversationRequest(const std::string& from, const Json::Value& value);
174 :
175 : /**
176 : * Retrieve author of a conversation request
177 : * @param convId Conversation's id
178 : * @return the author of the conversation request
179 : */
180 : std::string peerFromConversationRequest(const std::string& convId) const;
181 :
182 : /**
183 : * Called when a peer needs an invite for a conversation (generally after that they received
184 : * a commit notification for a conversation they don't have yet)
185 : * @param from
186 : * @param conversationId
187 : */
188 : void onNeedConversationRequest(const std::string& from, const std::string& conversationId);
189 :
190 : /**
191 : * Accept a conversation's request
192 : * @param convId
193 : * @param deviceId If a trust request is accepted from a device (can help to sync)
194 : */
195 : void acceptConversationRequest(const std::string& conversationId, const std::string& deviceId = "");
196 :
197 : /**
198 : * Decline a conversation's request
199 : * @param convId
200 : */
201 : void declineConversationRequest(const std::string& conversationId);
202 :
203 : /**
204 : * Clone conversation from a member
205 : * @param conversationId
206 : * @param uri
207 : */
208 : void cloneConversationFrom(const std::string& conversationId, const std::string& uri);
209 :
210 : /**
211 : * Starts a new conversation
212 : * @param mode Wanted mode
213 : * @param otherMember If needed (one to one)
214 : * @return conversation's id
215 : */
216 : std::string startConversation(ConversationMode mode = ConversationMode::INVITES_ONLY,
217 : const dht::InfoHash& otherMember = {});
218 :
219 : /**
220 : * Create a collaborative document: a swarm repository of its own (mode
221 : * DOCUMENT), announced in @p parentConversationId, holding CRDT
222 : * checkpoints instead of messages. The creator is its only member and
223 : * admin; other members join by opening it (see cloneDocumentFrom()).
224 : * @param parentConversationId the conversation that announces it
225 : * @param mimeType media type of what the document will hold
226 : * @return the document's repository id, empty on failure
227 : */
228 : std::string startDocument(const std::string& parentConversationId, const std::string& mimeType);
229 :
230 : /**
231 : * Clone a collaborative document from a member's devices — how a device
232 : * opts into holding a replica. The serving holder writes the `add` commit
233 : * at serve time, so the clone this device receives already contains its
234 : * invitation; the standard pending-conversation path then writes `join`.
235 : * Completion is reported through CollaborativeEditing::onRepositoryUpdated
236 : * rather than ConversationReady.
237 : * Every candidate is recorded as an authorized clone source, but the
238 : * fetch is only initiated from the first few: the fallback rounds walk
239 : * the rest, with backoff, if those fail.
240 : * @param documentId the document's repository id
241 : * @param candidates members to clone from, in order of preference
242 : */
243 : void cloneDocumentFrom(const std::string& documentId, const std::vector<std::string>& candidates);
244 :
245 : /**
246 : * Drop this device's replica of a collaborative document.The repository and
247 : * its swarm connections are torn down and the document is recorded as
248 : * removed so it is not recloned on restart.
249 : * @param documentId the document's repository id
250 : */
251 : void removeDocumentReplica(const std::string& documentId);
252 :
253 : /**
254 : * Store an attachment in a held collaborative document and notify the
255 : * swarm of the commit that carries it.
256 : * @param documentId the document's repository id
257 : * @param data the attachment content
258 : * @return the attachment id (content hash), empty on failure
259 : */
260 : std::string addDocumentAttachment(const std::string& documentId, const std::vector<uint8_t>& data);
261 :
262 : void createCommit(const std::string& conversationId,
263 : CommitMessage&& commitMessage,
264 : bool announce = true,
265 : OnCommitCb&& onCommit = {},
266 : OnDoneCb&& cb = {});
267 :
268 : void sendMessage(const std::string& conversationId,
269 : std::string message,
270 : const std::string& replyTo = "",
271 : bool announce = true,
272 : OnCommitCb&& onCommit = {},
273 : OnDoneCb&& cb = {});
274 :
275 : void editMessage(const std::string& conversationId, const std::string& newBody, const std::string& editedId);
276 : void reactToMessage(const std::string& conversationId, const std::string& newBody, const std::string& reactToId);
277 :
278 : /**
279 : * Add to the related conversation the call history message
280 : * @param uri Peer number
281 : * @param duration_ms The call duration in ms
282 : * @param reason
283 : */
284 : void addCallHistoryMessage(const std::string& uri, uint64_t duration_ms, const std::string& reason);
285 :
286 : // Received that a peer displayed a message
287 : bool onMessageDisplayed(const std::string& peer,
288 : const std::string& conversationId,
289 : const std::string& interactionId);
290 : std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> convMessageStatus() const;
291 :
292 : /**
293 : * Load conversation's messages and emit SwarmLoaded.
294 : * If plugin chat handlers are registered, body-overwrite transforms are applied
295 : * after loading and SwarmMessageUpdated is emitted for each affected message.
296 : * @param conversationId Conversation to load
297 : * @param fromMessage Start loading from this message id (empty = latest)
298 : * @param n Max interactions to load (0 = default)
299 : * @return id of the operation
300 : */
301 : uint32_t loadConversation(const std::string& conversationId, const std::string& fromMessage = "", size_t n = 0);
302 : uint32_t loadSwarmUntil(const std::string& conversationId,
303 : const std::string& fromMessage,
304 : const std::string& toMessage);
305 : /**
306 : * Clear loaded interactions
307 : * @param conversationId
308 : */
309 : void clearCache(const std::string& conversationId);
310 :
311 : // File transfer
312 : /**
313 : * Returns related transfer manager
314 : * @param id Conversation's id
315 : * @return nullptr if not found, else the manager
316 : */
317 : std::shared_ptr<TransferManager> dataTransfer(const std::string& id) const;
318 :
319 : /**
320 : * Get current transfer info
321 : * @return the TransferManager::info() result, or nullopt if the conversation is not loaded yet
322 : */
323 : std::optional<bool> fileTransferInfo(const std::string& conversationId,
324 : const std::string& fileId,
325 : std::string& path,
326 : int64_t& total,
327 : int64_t& progress);
328 :
329 : /**
330 : * Choose if we can accept channel request
331 : * @param member Member to check
332 : * @param fileId File transfer to check (needs to be waiting)
333 : * @param verifyShaSum For debug only
334 : * @return if we accept the channel request
335 : */
336 : bool onFileChannelRequest(const std::string& conversationId,
337 : const std::string& member,
338 : const std::string& fileId,
339 : bool verifyShaSum = true) const;
340 :
341 : /**
342 : * Ask conversation's members to send a file to this device
343 : * @param conversationId Related conversation
344 : * @param interactionId Related interaction
345 : * @param fileId Related fileId
346 : * @param path where to download the file
347 : */
348 : bool downloadFile(const std::string& conversationId,
349 : const std::string& interactionId,
350 : const std::string& fileId,
351 : const std::string& path);
352 :
353 : // Sync
354 : /**
355 : * Sync conversations with detected peer
356 : */
357 : void syncConversations(const std::string& peer, const std::string& deviceId);
358 :
359 : /**
360 : * Detect new conversations and request from other devices
361 : * @param msg Received data
362 : * @param peerId Sender
363 : * @param deviceId
364 : */
365 : void onSyncData(const SyncMsg& msg, const std::string& peerId, const std::string& deviceId);
366 :
367 : /**
368 : * Check if we need to share infos with a contact
369 : * @param memberUri
370 : * @param deviceId
371 : */
372 : bool needsSyncingWith(const std::string& memberUri) const;
373 :
374 : /**
375 : * Notify that a peer fetched a commit
376 : * @note: this definitely remove the repository when needed (when we left and someone fetched
377 : * the information)
378 : * @param conversationId Related conv
379 : * @param deviceId Device who synced
380 : * @param commit HEAD synced
381 : */
382 : void setFetched(const std::string& conversationId, const std::string& deviceId, const std::string& commit);
383 :
384 : /**
385 : * Launch fetch on new commit
386 : * @param peer Who sent the notification
387 : * @param deviceId Who sent the notification
388 : * @param conversationId Related conversation
389 : * @param commitId Commit to retrieve
390 : */
391 : void fetchNewCommits(const std::string& peer,
392 : const std::string& deviceId,
393 : const std::string& conversationId,
394 : const std::string& commitId);
395 :
396 : // Conversation's member
397 : /**
398 : * Adds a new member to a conversation (this will triggers a member event + new message on success)
399 : * @param conversationId
400 : * @param contactUri
401 : * @param sendRequest If we need to inform the peer (used for tests)
402 : */
403 : void addConversationMember(const std::string& conversationId,
404 : const dht::InfoHash& contactUri,
405 : bool sendRequest = true);
406 : /**
407 : * Remove a member from a conversation (this will trigger a member event + new message on success)
408 : * @param conversationId
409 : * @param contactUri
410 : * @param isDevice
411 : */
412 : void removeConversationMember(const std::string& conversationId,
413 : const dht::InfoHash& contactUri,
414 : bool isDevice = false);
415 : /**
416 : * Get members
417 : * @param conversationId
418 : * @param includeBanned
419 : * @return a map of members with their role and details
420 : */
421 : std::vector<std::map<std::string, std::string>> getConversationMembers(const std::string& conversationId,
422 : bool includeBanned = false) const;
423 : /**
424 : * Retrieve the number of interactions from interactionId to HEAD
425 : * @param convId
426 : * @param interactionId "" for getting the whole history
427 : * @param authorUri Stop when detect author
428 : * @return number of interactions since interactionId
429 : */
430 : uint32_t countInteractions(const std::string& convId,
431 : const std::string& toId,
432 : const std::string& fromId,
433 : const std::string& authorUri) const;
434 :
435 : /**
436 : * Search in conversations via a filter
437 : * @param req Id of the request
438 : * @param convId Leave empty to search in all conversation, else add the conversation's id
439 : * @param filter Parameters for the search
440 : * @note triggers messagesFound
441 : */
442 : void search(uint32_t req, const std::string& convId, const Filter& filter) const;
443 :
444 : // Conversation's infos management
445 : /**
446 : * Update metadatas from conversations (like title, avatar, etc)
447 : * @param conversationId
448 : * @param infos
449 : * @param sync If we need to sync with others (used for tests)
450 : */
451 : void updateConversationInfos(const std::string& conversationId,
452 : const std::map<std::string, std::string>& infos,
453 : bool sync = true);
454 : std::map<std::string, std::string> conversationInfos(const std::string& conversationId) const;
455 : /**
456 : * Update user's preferences (like color, notifications, etc) to be synced across devices
457 : * @param conversationId
458 : * @param preferences
459 : */
460 : void setConversationPreferences(const std::string& conversationId, const std::map<std::string, std::string>& prefs);
461 : std::map<std::string, std::string> getConversationPreferences(const std::string& conversationId,
462 : bool includeCreated = false) const;
463 : /**
464 : * Retrieve all conversation preferences to sync with other devices
465 : */
466 : std::map<std::string, std::map<std::string, std::string>> convPreferences() const;
467 : // Get the map into a VCard format for storing
468 : std::vector<uint8_t> conversationVCard(const std::string& conversationId) const;
469 :
470 : bool isMemberBanned(const std::string& convId, const std::string& uri) const;
471 : bool isDeviceBanned(const std::string& convId, const std::string& deviceId) const;
472 : bool isPeerAuthorized(const std::string& convId,
473 : const std::string& uri,
474 : const std::string& deviceId,
475 : bool includeInvited = false) const;
476 :
477 : /**
478 : * The read-only half of authorizeDocumentPeer(): whether this device could
479 : * vouch for the peer, without writing anything. This is what the channel
480 : * pre-check asks — accepting the channel commits us to nothing, the add
481 : * commit is only written when the clone is actually served.
482 : */
483 : bool mayServeDocument(const std::string& documentId, const std::string& uri, const std::string& deviceId) const;
484 :
485 : /**
486 : * Serve-time admission for collaborative documents, tried after
487 : * isPeerAuthorized() said no. A peer in good standing in the document's
488 : * parent conversation may open the document even though no member invited
489 : * it yet: the serving holder vouches for it by writing the `add` commit
490 : * itself, and only then lets the clone proceed. Peers banned from the
491 : * document, or documents this device does not hold, are refused.
492 : * @param documentId the document's repository id
493 : * @param uri requesting peer
494 : * @param deviceId requesting device
495 : * @param cb called with whether the peer may be served
496 : */
497 : void authorizeDocumentPeer(const std::string& documentId,
498 : const std::string& uri,
499 : const std::string& deviceId,
500 : std::function<void(bool)>&& cb);
501 :
502 : // Remove swarm
503 : /**
504 : * Remove one to one conversations related to a contact
505 : * @param uri Of the contact
506 : * @param ban If banned
507 : */
508 : void removeContact(const std::string& uri, bool ban);
509 :
510 : /**
511 : * Remove a conversation, but not the contact
512 : * @param conversationId
513 : * @return if successfully removed
514 : */
515 : bool removeConversation(const std::string& conversationId);
516 : /**
517 : * Search for an existing one-to-one conversation
518 : * that exactly matches the given set of member URIs.
519 : * @param excludedConversationId Conversation ID to be ignored during the search.
520 : * @param targetUris The set of member URIs that must match exactly.
521 : * @return The ID of the matching conversation if found, otherwise an empty string.
522 : */
523 : std::string findMatchingOneToOneConversation(const std::string& excludedConversationId,
524 : const std::set<std::string>& targetUris) const;
525 : /**
526 : * Check if we're hosting a specific conference
527 : * @param conversationId (empty to search all conv)
528 : * @param confId
529 : * @return true if hosting this conference
530 : */
531 : bool isHosting(const std::string& conversationId, const std::string& confId) const;
532 : /**
533 : * Return active calls
534 : * @param convId Which conversation to choose
535 : * @return {{"id":id}, {"uri":uri}, {"device":device}}
536 : */
537 : std::vector<std::map<std::string, std::string>> getActiveCalls(const std::string& conversationId) const;
538 : /**
539 : * Call the conversation
540 : * @param url Url to call (swarm:conversation or swarm:conv/account/device/conf to join)
541 : * @param mediaList The media list
542 : * @param cb Callback to pass which device to call (called in the same thread)
543 : * @return call if a call is started, else nullptr
544 : */
545 : std::shared_ptr<SIPCall> call(
546 : const std::string& url,
547 : const std::vector<libjami::MediaMap>& mediaList,
548 : std::function<void(const std::string&, const DeviceId&, const std::shared_ptr<SIPCall>&)>&& cb);
549 : void hostConference(const std::string& conversationId,
550 : const std::string& confId,
551 : const std::string& callId,
552 : const std::vector<libjami::MediaMap>& mediaList = {});
553 :
554 : // The following methods modify what is stored on the disk
555 : static void saveConvInfos(const std::string& accountId, const std::map<std::string, ConvInfo>& conversations);
556 : static void saveConvInfosToPath(const std::filesystem::path& path,
557 : const std::map<std::string, ConvInfo>& conversations);
558 : static void saveConvRequests(const std::string& accountId,
559 : const std::map<std::string, ConversationRequest>& conversationsRequests);
560 : static void saveConvRequestsToPath(const std::filesystem::path& path,
561 : const std::map<std::string, ConversationRequest>& conversationsRequests);
562 :
563 : static std::map<std::string, ConvInfo> convInfos(const std::string& accountId);
564 : static std::map<std::string, ConvInfo> convInfosFromPath(const std::filesystem::path& path);
565 : static std::map<std::string, ConversationRequest> convRequests(const std::string& accountId);
566 : static std::map<std::string, ConversationRequest> convRequestsFromPath(const std::filesystem::path& path);
567 : void addConvInfo(const ConvInfo& info);
568 :
569 : /**
570 : * Get a conversation
571 : * @param convId
572 : */
573 : std::shared_ptr<Conversation> getConversation(const std::string& convId);
574 : /**
575 : * Return current git socket used for a conversation
576 : * @param deviceId Related device
577 : * @param conversationId Related conversation
578 : * @return the related socket
579 : */
580 : std::shared_ptr<dhtnet::ChannelSocket> gitSocket(std::string_view deviceId, std::string_view convId) const;
581 : /** If @p expected is set, only remove the socket if it is still the registered one. */
582 : void removeGitSocket(std::string_view deviceId,
583 : std::string_view convId,
584 : const std::shared_ptr<dhtnet::ChannelSocket>& expected = {});
585 : /**
586 : * Clear all connection (swarm channels)
587 : */
588 : void shutdownConnections();
589 : /**
590 : * Add a swarm connection
591 : * @param conversationId
592 : * @param socket
593 : */
594 : void addSwarmChannel(const std::string& conversationId, std::shared_ptr<dhtnet::ChannelSocket> socket);
595 : /**
596 : * Notify conversations that a new device is connected.
597 : * This allows the DRT to decide whether to open a swarm channel.
598 : * @param peerUri The URI of the peer who owns the device
599 : * @param deviceId The device that connected
600 : */
601 : void addKnownDevice(const std::string& peerUri, const DeviceId& deviceId);
602 :
603 : /**
604 : * Triggers a bucket maintainance for DRTs
605 : */
606 : void connectivityChanged();
607 :
608 : /**
609 : * Get Typers object for a conversation
610 : * @param convId
611 : * @return the Typer object
612 : */
613 : std::shared_ptr<Typers> getTypers(const std::string& convId);
614 :
615 : private:
616 : class Impl;
617 : std::shared_ptr<Impl> pimpl_;
618 : };
619 :
620 : } // namespace jami
|