LCOV - code coverage report
Current view: top level - src/jamidht - conversationrepository.h (source / functions) Coverage Total Hit
Test: jami-coverage-filtered.info Lines: 90.0 % 20 18
Test Date: 2026-07-06 08:25:38 Functions: 90.0 % 10 9

            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              : #include "def.h"
      19              : #include "vcard.h"
      20              : #include "git_def.h"
      21              : #include "jamidht/commit_message.h"
      22              : 
      23              : #include <opendht/default_types.h>
      24              : 
      25              : #include <optional>
      26              : #include <memory>
      27              : #include <stdexcept>
      28              : #include <string>
      29              : #include <vector>
      30              : 
      31              : namespace jami {
      32              : 
      33              : using DeviceId = dht::PkId;
      34              : 
      35              : constexpr auto EFETCH = 1;
      36              : constexpr auto EINVALIDMODE = 2;
      37              : constexpr auto EVALIDFETCH = 3;
      38              : constexpr auto EUNAUTHORIZED = 4;
      39              : constexpr auto ECOMMIT = 5;
      40              : constexpr auto EUNRECOVERABLE = 6;
      41              : 
      42              : class JamiAccount;
      43              : 
      44              : /**
      45              :  * Exception thrown when a cloned conversation repository fails commit validation.
      46              :  * Unlike network errors, this failure is permanent: the remote history is immutable,
      47              :  * so cloning the same conversation again will fail the same way.
      48              :  */
      49              : class InvalidRepositoryError : public std::runtime_error
      50              : {
      51              : public:
      52            3 :     explicit InvalidRepositoryError(const std::string& what)
      53            3 :         : std::runtime_error(what)
      54            3 :     {}
      55              : };
      56              : 
      57              : struct LogOptions
      58              : {
      59              :     std::string from {};
      60              :     std::string to {};
      61              :     uint64_t nbOfCommits {0};  // maximum number of commits wanted
      62              :     bool skipMerge {false};    // Do not include merge commits in the log. Used by the module to get
      63              :                                // last interaction without potential merges
      64              :     bool includeTo {false};    // If we want or not the "to" commit [from-to] or [from-to)
      65              :     bool fastLog {false};      // Do not parse content, used mostly to count
      66              :     bool logIfNotFound {true}; // Add a warning in the log if commit is not found
      67              : 
      68              :     std::string authorUri {}; // filter commits from author
      69              : };
      70              : 
      71              : struct Filter
      72              : {
      73              :     std::string author;
      74              :     std::string lastId;
      75              :     std::string regexSearch;
      76              :     std::string type;
      77              :     int64_t after {0};
      78              :     int64_t before {0};
      79              :     uint32_t maxResult {0};
      80              :     bool caseSensitive {false};
      81              : };
      82              : 
      83              : struct GitAuthor
      84              : {
      85              :     std::string name {};
      86              :     std::string email {};
      87              : };
      88              : 
      89              : struct ConversationCommit
      90              : {
      91              :     std::string id {};
      92              :     std::vector<std::string> parents {};
      93              :     GitAuthor author {};
      94              :     std::vector<uint8_t> signed_content {};
      95              :     std::vector<uint8_t> signature {};
      96              :     CommitMessage commitMsg {};
      97              :     std::string linearized_parent {};
      98              :     std::string authorId {};
      99              :     int64_t timestamp {0};
     100              : };
     101              : 
     102              : enum class MemberRole { ADMIN = 0, MEMBER, INVITED, BANNED, LEFT };
     103              : 
     104              : namespace MemberPath {
     105              : 
     106              : static const std::filesystem::path ADMINS {"admins"};
     107              : static const std::filesystem::path MEMBERS {"members"};
     108              : static const std::filesystem::path INVITED {"invited"};
     109              : static const std::filesystem::path BANNED {"banned"};
     110              : static const std::filesystem::path DEVICES {"devices"};
     111              : 
     112              : } // namespace MemberPath
     113              : 
     114              : struct ConversationMember
     115              : {
     116              :     std::string uri;
     117              :     MemberRole role;
     118              : 
     119          203 :     std::map<std::string, std::string> map() const
     120              :     {
     121          203 :         std::string rolestr;
     122          203 :         if (role == MemberRole::ADMIN) {
     123          101 :             rolestr = "admin";
     124          102 :         } else if (role == MemberRole::MEMBER) {
     125           51 :             rolestr = "member";
     126           51 :         } else if (role == MemberRole::INVITED) {
     127           45 :             rolestr = "invited";
     128            6 :         } else if (role == MemberRole::BANNED) {
     129            6 :             rolestr = "banned";
     130            0 :         } else if (role == MemberRole::LEFT) {
     131            0 :             rolestr = "left"; // For one to one
     132              :         }
     133              : 
     134         1015 :         return {{"uri", uri}, {"role", rolestr}};
     135          406 :     }
     136        13959 :     MSGPACK_DEFINE(uri, role)
     137              : };
     138              : 
     139              : enum class CallbackResult { Skip, Break, Ok };
     140              : 
     141              : using PreConditionCb = std::function<CallbackResult(const std::string&, const GitAuthor&, const GitCommit&)>;
     142              : using PostConditionCb = std::function<bool(const std::string&, const GitAuthor&, ConversationCommit&)>;
     143              : using OnMembersChanged = std::function<void(const std::set<std::string>&)>;
     144              : 
     145              : /**
     146              :  * This class gives access to the git repository that represents the conversation
     147              :  */
     148              : class LIBJAMI_TEST_EXPORT ConversationRepository
     149              : {
     150              : public:
     151              : #ifdef LIBJAMI_TEST
     152              :     static bool DISABLE_RESET; // Some tests inject bad files so resetHard() will break the test
     153              : 
     154              :     // If true, clone and fetch operations will be performed directly using the target repo's path,
     155              :     // avoiding the need for setting up a GitServer and a DHTNet connection.
     156              :     static bool FETCH_FROM_LOCAL_REPOS;
     157              : #endif
     158              :     /**
     159              :      * Creates a new repository, with initial files, where the first commit hash is the conversation id
     160              :      * @param account       The related account
     161              :      * @param mode          The wanted mode
     162              :      * @param otherMember   The other uri
     163              :      * @return  the conversation repository object
     164              :      */
     165              :     static LIBJAMI_TEST_EXPORT std::unique_ptr<ConversationRepository> createConversation(
     166              :         const std::shared_ptr<JamiAccount>& account,
     167              :         ConversationMode mode = ConversationMode::INVITES_ONLY,
     168              :         const std::string& otherMember = "");
     169              : 
     170              :     /**
     171              :      * Clones a conversation on a remote device
     172              :      * @note This will use the socket registered for the conversation with JamiAccount::addGitSocket()
     173              :      * @param account           The account getting the conversation
     174              :      * @param deviceId          Remote device
     175              :      * @param conversationId    Conversation to clone
     176              :      * @throws InvalidRepositoryError if the cloned repository fails commit validation. This is a
     177              :      *         permanent failure (the remote history is immutable); transient network errors do not
     178              :      *         throw but return an empty repository instead. The sole caller,
     179              :      *         ConversationModule::Impl::handlePendingConversation(), catches this to stop retrying;
     180              :      *         any new caller must handle it as well.
     181              :      */
     182              :     static LIBJAMI_TEST_EXPORT std::pair<std::unique_ptr<ConversationRepository>, std::vector<ConversationCommit>>
     183              :     cloneConversation(const std::shared_ptr<JamiAccount>& account,
     184              :                       const std::string& deviceId,
     185              :                       const std::string& conversationId);
     186              : 
     187              :     /**
     188              :      * Open a conversation repository for an account and an id
     189              :      * @param account       The related account
     190              :      * @param id            The conversation id
     191              :      */
     192              :     ConversationRepository(const std::shared_ptr<JamiAccount>& account, const std::string& id);
     193              :     ~ConversationRepository();
     194              : 
     195              :     /**
     196              :      * Write the certificate in /members and commit the change
     197              :      * @param uri    Member to add
     198              :      * @return the commit id if successful
     199              :      */
     200              :     std::string addMember(const std::string& uri);
     201              : 
     202              :     /**
     203              :      * Fetch a remote repository via the given socket
     204              :      * @note This will use the socket registered for the conversation with JamiAccount::addGitSocket()
     205              :      * @note will create a remote identified by the deviceId
     206              :      * @param remoteDeviceId    Remote device id to fetch
     207              :      * @return if the operation was successful
     208              :      */
     209              :     bool fetch(const std::string& remoteDeviceId);
     210              : 
     211              :     /**
     212              :      * Merge the history of the conversation with another peer
     213              :      * @param uri                    The peer uri
     214              :      * @param disconnectFromPeerCb   Callback to disconnect from peer when banning
     215              :      * @return                       A vector of media maps representing the merged history
     216              :      */
     217              :     std::vector<std::map<std::string, std::string>> mergeHistory(
     218              :         const std::string& uri, std::function<void(const std::string&)>&& disconnectFromPeerCb = {});
     219              : 
     220              :     /**
     221              :      * Retrieve remote head. Can be useful after a fetch operation
     222              :      * @param remoteDeviceId        The remote name
     223              :      * @param branch                Remote branch to check (default: main)
     224              :      * @return the commit id pointed
     225              :      */
     226              :     std::string remoteHead(const std::string& remoteDeviceId, const std::string& branch = "main") const;
     227              : 
     228              :     /**
     229              :      * Return the conversation id
     230              :      */
     231              :     const std::string& id() const;
     232              : 
     233              :     /**
     234              :      * Add a new commit to the conversation
     235              :      * @param msg           The commit message of the commit
     236              :      * @param verifyDevice  If we need to validate that certificates are correct (used for testing)
     237              :      * @return <empty> on failure, else the message id
     238              :      */
     239              :     std::string commitMessage(const std::string& msg, bool verifyDevice = true);
     240              : 
     241              :     std::vector<std::string> commitMessages(const std::vector<std::string>& msgs);
     242              : 
     243              :     /**
     244              :      * Amend a commit message
     245              :      * @param id      The commit to amend
     246              :      * @param msg     The commit message of the commit
     247              :      * @return <empty> on failure, else the message id
     248              :      */
     249              :     std::string amend(const std::string& id, const std::string& msg);
     250              : 
     251              :     /**
     252              :      * Get commits depending on the options we pass
     253              :      * @return a list of commits
     254              :      */
     255              :     std::vector<ConversationCommit> log(const LogOptions& options = {}) const;
     256              :     void log(PreConditionCb&& preCondition,
     257              :              std::function<void(ConversationCommit&&)>&& emplaceCb,
     258              :              PostConditionCb&& postCondition,
     259              :              const std::string& from = "",
     260              :              bool logIfNotFound = true) const;
     261              : 
     262              :     /**
     263              :      * Check if a commit exists in the repository
     264              :      * @param commitId The commit id to check
     265              :      * @return true if the commit was found, false if not or if an error occurred
     266              :      */
     267              :     bool hasCommit(const std::string& commitId) const;
     268              :     std::optional<ConversationCommit> getCommit(const std::string& commitId) const;
     269              : 
     270              :     /**
     271              :      * Get parent via topological + date sort in branch main of a commit
     272              :      * @param commitId      id to choice
     273              :      */
     274              :     std::optional<std::string> linearizedParent(const std::string& commitId) const;
     275              : 
     276              :     /**
     277              :      * Merge another branch into the main branch
     278              :      * @param merge_id      The reference to merge
     279              :      * @param force         Should be false, skip validateDevice() ; used for test purpose
     280              :      * @return a pair containing if the merge was successful and the merge commit id
     281              :      * generated if one (can be a fast forward merge without commit)
     282              :      */
     283              :     std::pair<bool, std::string> merge(const std::string& merge_id, bool force = false);
     284              : 
     285              :     /**
     286              :      * Get current diff stats between two commits
     287              :      * @param oldId     Old commit
     288              :      * @param newId     Recent commit (empty value will compare to the empty repository)
     289              :      * @note "HEAD" is also accepted as parameter for newId
     290              :      * @return diff stats
     291              :      */
     292              :     std::string diffStats(const std::string& newId, const std::string& oldId = "") const;
     293              : 
     294              :     /**
     295              :      * Get changed files from a git diff
     296              :      * @param diffStats     The stats to analyze
     297              :      * @return get the changed files from a git diff
     298              :      */
     299              :     static std::vector<std::string> changedFiles(std::string_view diffStats);
     300              : 
     301              :     /**
     302              :      * Join a repository
     303              :      * @return commit Id
     304              :      */
     305              :     std::string join();
     306              : 
     307              :     /**
     308              :      * Erase self from repository
     309              :      * @return commit Id
     310              :      */
     311              :     std::string leave();
     312              : 
     313              :     /**
     314              :      * Erase repository
     315              :      */
     316              :     void erase();
     317              : 
     318              :     /**
     319              :      * Get conversation's mode
     320              :      * @return the mode
     321              :      */
     322              :     ConversationMode mode() const;
     323              : 
     324              :     /**
     325              :      * The voting system is divided in two parts. The voting phase where
     326              :      * admins can decide an action (such as kicking someone)
     327              :      * and the resolving phase, when > 50% of the admins voted, we can
     328              :      * considered the vote as finished
     329              :      */
     330              :     /**
     331              :      * Add a vote to kick a device or a user
     332              :      * @param uri       identified of the user/device
     333              :      * @param type      device, members, admins or invited
     334              :      * @return the commit id or empty if failed
     335              :      */
     336              :     std::string voteKick(const std::string& uri, const std::string& type);
     337              :     /**
     338              :      * Add a vote to re-add a user
     339              :      * @param uri       identified of the user
     340              :      * @param type      device, members, admins or invited
     341              :      * @return the commit id or empty if failed
     342              :      */
     343              :     std::string voteUnban(const std::string& uri, const std::string_view type);
     344              :     /**
     345              :      * Validate if a vote is finished
     346              :      * @param uri       identified of the user/device
     347              :      * @param type      device, members, admins or invited
     348              :      * @param voteType  "ban" or "unban"
     349              :      * @return the commit id or empty if failed
     350              :      */
     351              :     std::string resolveVote(const std::string& uri, const std::string_view type, const std::string& voteType);
     352              : 
     353              :     /**
     354              :      * Validate a fetch with remote device
     355              :      * @param remotedevice
     356              :      * @return the validated commits and if an error occurs
     357              :      */
     358              :     std::pair<std::vector<ConversationCommit>, bool> validFetch(const std::string& remoteDevice) const;
     359              : 
     360              :     /**
     361              :      * Validate a clone
     362              :      * @return the validated commits and false if an error occurs
     363              :      */
     364              :     std::pair<std::vector<ConversationCommit>, bool> validClone() const;
     365              : 
     366              :     /**
     367              :      * Verify the signature against the given commit
     368              :      * @param userDevice    the email of the sender (i.e. their device's public key)
     369              :      * @param commitId      the id of the commit
     370              :      */
     371              :     bool isValidUserAtCommit(const std::string& userDevice,
     372              :                              const std::string& commitId,
     373              :                              const git_buf& sig,
     374              :                              const git_buf& sig_data) const;
     375              : 
     376              :     /**
     377              :      * Validate that commits are not malformed
     378              :      * @param commitsToValidate     the list of commits
     379              :      */
     380              :     bool validCommits(const std::vector<ConversationCommit>& commitsToValidate) const;
     381              : 
     382              :     /**
     383              :      * Delete branch with remote
     384              :      * @param remoteDevice
     385              :      */
     386              :     void removeBranchWith(const std::string& remoteDevice);
     387              : 
     388              :     /**
     389              :      * One to one util, get initial members
     390              :      * @return initial members
     391              :      */
     392              :     std::vector<std::string> getInitialMembers() const;
     393              : 
     394              :     /**
     395              :      * Get conversation's members
     396              :      * @return members
     397              :      */
     398              :     std::vector<ConversationMember> members() const;
     399              : 
     400              :     /**
     401              :      * Get conversation's devices
     402              :      * @param ignoreExpired     If we want to ignore expired devices
     403              :      * @return members
     404              :      */
     405              :     std::map<std::string, std::vector<DeviceId>> devices(bool ignoreExpired = true) const;
     406              : 
     407              :     /**
     408              :      * @param filter           If we want to remove one member
     409              :      * @param filteredRoles    If we want to ignore some roles
     410              :      * @return members' uris
     411              :      */
     412              :     std::set<std::string> memberUris(std::string_view filter, const std::set<MemberRole>& filteredRoles) const;
     413              : 
     414              :     /**
     415              :      * To use after a merge with member's events, refresh members knowledge
     416              :      */
     417              :     void refreshMembers() const;
     418              : 
     419              :     void onMembersChanged(OnMembersChanged&& cb);
     420              : 
     421              :     /**
     422              :      * Because conversations can contains non contacts certificates, this methods
     423              :      * loads certificates in conversations into the cert store
     424              :      * @param blocking      if we need to wait that certificates are pinned
     425              :      */
     426              :     void pinCertificates(bool blocking = false);
     427              :     /**
     428              :      * Retrieve the uri from a deviceId
     429              :      * @note used by swarm manager (peersToSyncWith)
     430              :      * @param deviceId
     431              :      * @return corresponding issuer
     432              :      */
     433              :     std::string uriFromDevice(const std::string& deviceId) const;
     434              : 
     435              :     /**
     436              :      * Change repository's infos
     437              :      * @param map       New infos (supported keys: title, description, avatar)
     438              :      * @return the commit id
     439              :      */
     440              :     std::string updateInfos(const std::map<std::string, std::string>& map);
     441              : 
     442              :     /**
     443              :      * Retrieve current infos (title, description, avatar, mode)
     444              :      * @return infos
     445              :      */
     446              :     std::map<std::string, std::string> infos() const;
     447              :     static std::map<std::string, std::string> infosFromVCard(vCard::utils::VCardData&& details);
     448              : 
     449              :     /**
     450              :      * Convert ConversationCommit to MapStringString for the client
     451              :      */
     452              :     std::vector<std::map<std::string, std::string>> convCommitsToMap(
     453              :         const std::vector<ConversationCommit>& commits) const;
     454              :     std::optional<std::map<std::string, std::string>> convCommitToMap(const ConversationCommit& commit) const;
     455              : 
     456              :     /**
     457              :      * Get current HEAD hash
     458              :      */
     459              :     std::string getHead() const;
     460              : 
     461              : private:
     462              :     ConversationRepository() = delete;
     463              :     class Impl;
     464              :     std::unique_ptr<Impl> pimpl_;
     465              : };
     466              : 
     467              : } // namespace jami
     468        13993 : MSGPACK_ADD_ENUM(jami::MemberRole);
     469         3485 : MSGPACK_ADD_ENUM(jami::ConversationMode);
        

Generated by: LCOV version 2.0-1