LCOV - code coverage report
Current view: top level - src - data_transfer.cpp (source / functions) Hit Total Coverage
Test: jami-coverage-filtered.info Lines: 339 387 87.6 %
Date: 2024-11-15 09:04:49 Functions: 42 51 82.4 %

          Line data    Source code
       1             : /*
       2             :  *  Copyright (C) 2004-2024 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             : 
      18             : #include "data_transfer.h"
      19             : 
      20             : #include "base64.h"
      21             : #include "fileutils.h"
      22             : #include "manager.h"
      23             : #include "client/ring_signal.h"
      24             : 
      25             : #include <mutex>
      26             : #include <cstdlib> // mkstemp
      27             : #include <filesystem>
      28             : 
      29             : #include <opendht/rng.h>
      30             : #include <opendht/thread_pool.h>
      31             : 
      32             : namespace jami {
      33             : 
      34             : libjami::DataTransferId
      35          61 : generateUID(std::mt19937_64& engine)
      36             : {
      37          61 :     return std::uniform_int_distribution<libjami::DataTransferId> {1, JAMI_ID_MAX_VAL}(engine);
      38             : }
      39             : 
      40         127 : FileInfo::FileInfo(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
      41             :                    const std::string& fileId,
      42             :                    const std::string& interactionId,
      43         127 :                    const libjami::DataTransferInfo& info)
      44         127 :     : fileId_(fileId)
      45         127 :     , interactionId_(interactionId)
      46         127 :     , info_(info)
      47         254 :     , channel_(channel)
      48         127 : {}
      49             : 
      50             : void
      51         150 : FileInfo::emit(libjami::DataTransferEventCode code)
      52             : {
      53         150 :     if (finishedCb_ && code >= libjami::DataTransferEventCode::finished)
      54          89 :         finishedCb_(uint32_t(code));
      55         150 :     if (interactionId_ != "") {
      56             :         // Else it's an internal transfer
      57          33 :         runOnMainThread([info = info_, iid = interactionId_, fid = fileId_, code]() {
      58          33 :             emitSignal<libjami::DataTransferSignal::DataTransferEvent>(info.accountId,
      59          33 :                                                                        info.conversationId,
      60          33 :                                                                        iid,
      61          33 :                                                                        fid,
      62             :                                                                        uint32_t(code));
      63          33 :         });
      64             :     }
      65         150 : }
      66             : 
      67          66 : OutgoingFile::OutgoingFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
      68             :                            const std::string& fileId,
      69             :                            const std::string& interactionId,
      70             :                            const libjami::DataTransferInfo& info,
      71             :                            size_t start,
      72          66 :                            size_t end)
      73             :     : FileInfo(channel, fileId, interactionId, info)
      74          66 :     , start_(start)
      75          66 :     , end_(end)
      76             : {
      77          66 :     std::filesystem::path fpath(info_.path);
      78          66 :     if (!std::filesystem::is_regular_file(fpath)) {
      79          38 :         channel_->shutdown();
      80          38 :         return;
      81             :     }
      82          28 :     stream_.open(fpath, std::ios::binary | std::ios::in);
      83          28 :     if (!stream_ || !stream_.is_open()) {
      84           0 :         channel_->shutdown();
      85           0 :         return;
      86             :     }
      87          66 : }
      88             : 
      89          66 : OutgoingFile::~OutgoingFile()
      90             : {
      91          66 :     if (stream_ && stream_.is_open())
      92           0 :         stream_.close();
      93          66 :     if (channel_)
      94          66 :         channel_->shutdown();
      95          66 : }
      96             : 
      97             : void
      98          66 : OutgoingFile::process()
      99             : {
     100          66 :     if (!channel_ or !stream_ or !stream_.is_open())
     101          38 :         return;
     102          28 :     auto correct = false;
     103          28 :     stream_.seekg(start_, std::ios::beg);
     104             :     try {
     105          28 :         std::vector<char> buffer(UINT16_MAX, 0);
     106          28 :         std::error_code ec;
     107          28 :         auto pos = start_;
     108          74 :         while (!stream_.eof()) {
     109          46 :             stream_.read(buffer.data(),
     110          46 :                          end_ > start_ ? std::min(end_ - pos, buffer.size()) : buffer.size());
     111          46 :             auto gcount = stream_.gcount();
     112          46 :             pos += gcount;
     113          46 :             channel_->write(reinterpret_cast<const uint8_t*>(buffer.data()), gcount, ec);
     114          46 :             if (ec)
     115           0 :                 break;
     116             :         }
     117          28 :         if (!ec)
     118          28 :             correct = true;
     119          28 :         stream_.close();
     120          28 :     } catch (...) {
     121           0 :     }
     122          28 :     if (!isUserCancelled_) {
     123             :         // NOTE: emit(code) MUST be changed to improve handling of multiple destinations
     124             :         // But for now, we can just avoid to emit errors to the client, because for outgoing
     125             :         // transfer in a swarm, for outgoingFiles, we know that the file is ok. And the peer
     126             :         // will retry the transfer if they need, so we don't need to show errors.
     127          28 :         if (!interactionId_.empty() && !correct)
     128           0 :             return;
     129          28 :         auto code = correct ? libjami::DataTransferEventCode::finished
     130             :                             : libjami::DataTransferEventCode::closed_by_peer;
     131          28 :         emit(code);
     132             :     }
     133             : }
     134             : 
     135             : void
     136           0 : OutgoingFile::cancel()
     137             : {
     138             :     // Remove link, not original file
     139           0 :     auto path = fileutils::get_data_dir() / "conversation_data" / info_.accountId
     140           0 :                 / info_.conversationId / fileId_;
     141           0 :     if (std::filesystem::is_symlink(path))
     142           0 :         dhtnet::fileutils::remove(path);
     143           0 :     isUserCancelled_ = true;
     144           0 :     emit(libjami::DataTransferEventCode::closed_by_host);
     145           0 : }
     146             : 
     147          61 : IncomingFile::IncomingFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
     148             :                            const libjami::DataTransferInfo& info,
     149             :                            const std::string& fileId,
     150             :                            const std::string& interactionId,
     151          61 :                            const std::string& sha3Sum)
     152             :     : FileInfo(channel, fileId, interactionId, info)
     153          61 :     , sha3Sum_(sha3Sum)
     154         122 :     , path_(info.path + ".tmp")
     155             : {
     156          61 :     stream_.open(path_,
     157             :                  std::ios::binary | std::ios::out | std::ios::app);
     158          61 :     if (!stream_)
     159           0 :         return;
     160             : 
     161          61 :     emit(libjami::DataTransferEventCode::ongoing);
     162           0 : }
     163             : 
     164          61 : IncomingFile::~IncomingFile()
     165             : {
     166          61 :     if (channel_)
     167          61 :         channel_->setOnRecv({});
     168             :     {
     169          61 :         std::lock_guard<std::mutex> lk(streamMtx_);
     170          61 :         if (stream_ && stream_.is_open())
     171           0 :             stream_.close();
     172          61 :     }
     173          61 :     if (channel_)
     174          61 :         channel_->shutdown();
     175          61 : }
     176             : 
     177             : void
     178           1 : IncomingFile::cancel()
     179             : {
     180           1 :     isUserCancelled_ = true;
     181           1 :     emit(libjami::DataTransferEventCode::closed_by_peer);
     182           1 :     if (channel_)
     183           1 :         channel_->shutdown();
     184           1 : }
     185             : 
     186             : void
     187          61 : IncomingFile::process()
     188             : {
     189          61 :     channel_->setOnRecv([w = weak_from_this()](const uint8_t* buf, size_t len) {
     190          26 :         if (auto shared = w.lock()) {
     191             :             // No need to lock, setOnRecv is resetted before closing
     192          26 :             if (shared->stream_.is_open())
     193          26 :                 shared->stream_.write(reinterpret_cast<const char*>(buf), len);
     194          26 :             shared->info_.bytesProgress = shared->stream_.tellp();
     195          26 :         }
     196          26 :         return len;
     197             :     });
     198          61 :     channel_->onShutdown([w = weak_from_this()] {
     199          61 :         auto shared = w.lock();
     200          61 :         if (!shared)
     201           0 :             return;
     202             :         {
     203          61 :             std::lock_guard<std::mutex> lk(shared->streamMtx_);
     204          61 :             if (shared->stream_ && shared->stream_.is_open())
     205          61 :                 shared->stream_.close();
     206          61 :         }
     207          61 :         auto correct = shared->sha3Sum_.empty();
     208          61 :         std::error_code ec;
     209          61 :         if (!correct) {
     210          16 :             if (shared->isUserCancelled_) {
     211           1 :                 std::filesystem::remove(shared->path_, ec);
     212             :             } else {
     213          15 :                 auto sha3Sum = fileutils::sha3File(shared->path_);
     214          15 :                 if (shared->sha3Sum_ == sha3Sum) {
     215          36 :                     JAMI_LOG("New file received: {}", shared->info_.path);
     216          12 :                     correct = true;
     217             :                 } else {
     218           3 :                     if (shared->info_.totalSize != 0
     219           3 :                         && shared->info_.totalSize < shared->info_.bytesProgress) {
     220           6 :                         JAMI_WARNING("Removing {} larger than announced: {}/{}", shared->info_.path, shared->info_.bytesProgress, shared->info_.totalSize);
     221           2 :                         std::filesystem::remove(shared->path_, ec);
     222             :                     } else {
     223           3 :                         JAMI_WARNING("Invalid sha3sum detected for {}, incomplete file: {}/{}", shared->info_.path, shared->info_.bytesProgress, shared->info_.totalSize);
     224             :                     }
     225             :                 }
     226          15 :             }
     227          16 :             if (ec) {
     228           0 :                 JAMI_ERROR("Failed to remove file {}: {}", shared->path_, ec.message());
     229             :             }
     230             :         }
     231          61 :         if (correct) {
     232          57 :             std::filesystem::rename(shared->path_, shared->info_.path, ec);
     233          57 :             if (ec) {
     234           0 :                 JAMI_ERROR("Failed to rename file from {} to {}: {}", shared->path_, shared->info_.path, ec.message());
     235           0 :                 correct = false;
     236             :             }
     237             :         }
     238          61 :         if (shared->isUserCancelled_)
     239           1 :             return;
     240          60 :         auto code = correct ? libjami::DataTransferEventCode::finished
     241             :                             : libjami::DataTransferEventCode::closed_by_host;
     242          60 :         shared->emit(code);
     243          61 :     });
     244          61 : }
     245             : 
     246             : //==============================================================================
     247             : 
     248             : class TransferManager::Impl
     249             : {
     250             : public:
     251        1052 :     Impl(const std::string& accountId,
     252             :          const std::string& accountUri,
     253             :          const std::string& to,
     254             :          const std::mt19937_64& rand)
     255        1052 :         : accountId_(accountId)
     256        1052 :         , accountUri_(accountUri)
     257        1052 :         , to_(to)
     258        1052 :         , rand_(rand)
     259             :     {
     260        1052 :         if (!to_.empty()) {
     261         768 :             conversationDataPath_ = fileutils::get_data_dir() / accountId_ / "conversation_data"
     262        1152 :                                     / to_;
     263         384 :             dhtnet::fileutils::check_dir(conversationDataPath_);
     264         384 :             waitingPath_ = conversationDataPath_ / "waiting";
     265             :         }
     266        1052 :         profilesPath_ = fileutils::get_data_dir() / accountId_ / "profiles";
     267        1052 :         accountProfilePath_ = fileutils::get_data_dir() / accountId / "profile.vcf";
     268        1052 :         loadWaiting();
     269        1052 :     }
     270             : 
     271        1052 :     ~Impl()
     272             :     {
     273        1052 :         std::lock_guard lk {mapMutex_};
     274        1090 :         for (const auto& [channel, _of] : outgoings_) {
     275          38 :             channel->shutdown();
     276             :         }
     277        1052 :         outgoings_.clear();
     278        1052 :         incomings_.clear();
     279        1052 :         vcards_.clear();
     280        1052 :     }
     281             : 
     282        1052 :     void loadWaiting()
     283             :     {
     284             :         try {
     285             :             // read file
     286        2104 :             auto file = fileutils::loadFile(waitingPath_);
     287             :             // load values
     288           0 :             msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size());
     289           0 :             std::lock_guard lk {mapMutex_};
     290           0 :             oh.get().convert(waitingIds_);
     291        1052 :         } catch (const std::exception& e) {
     292        1052 :             return;
     293        1052 :         }
     294             :     }
     295          19 :     void saveWaiting()
     296             :     {
     297          19 :         std::ofstream file(waitingPath_, std::ios::trunc | std::ios::binary);
     298          19 :         msgpack::pack(file, waitingIds_);
     299          19 :     }
     300             : 
     301             :     std::string accountId_ {};
     302             :     std::string accountUri_ {};
     303             :     std::string to_ {};
     304             :     std::filesystem::path waitingPath_ {};
     305             :     std::filesystem::path profilesPath_ {};
     306             :     std::filesystem::path accountProfilePath_ {};
     307             :     std::filesystem::path conversationDataPath_ {};
     308             : 
     309             :     std::mutex mapMutex_ {};
     310             :     std::map<std::string, WaitingRequest> waitingIds_ {};
     311             :     std::map<std::shared_ptr<dhtnet::ChannelSocket>, std::shared_ptr<OutgoingFile>> outgoings_ {};
     312             :     std::map<std::string, std::shared_ptr<IncomingFile>> incomings_ {};
     313             :     std::map<std::pair<std::string, std::string>, std::shared_ptr<IncomingFile>> vcards_ {};
     314             : 
     315             :     std::mt19937_64 rand_;
     316             : };
     317             : 
     318        1052 : TransferManager::TransferManager(const std::string& accountId,
     319             :                                  const std::string& accountUri,
     320             :                                  const std::string& to,
     321        1052 :                                  const std::mt19937_64& rand)
     322        1052 :     : pimpl_ {std::make_unique<Impl>(accountId, accountUri, to, rand)}
     323        1052 : {}
     324             : 
     325        1052 : TransferManager::~TransferManager() {}
     326             : 
     327             : void
     328          68 : TransferManager::transferFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
     329             :                               const std::string& fileId,
     330             :                               const std::string& interactionId,
     331             :                               const std::string& path,
     332             :                               size_t start,
     333             :                               size_t end,
     334             :                               OnFinishedCb onFinished)
     335             : {
     336          68 :     std::lock_guard lk {pimpl_->mapMutex_};
     337          68 :     if (pimpl_->outgoings_.find(channel) != pimpl_->outgoings_.end())
     338           2 :         return;
     339          66 :     libjami::DataTransferInfo info;
     340          66 :     info.accountId = pimpl_->accountId_;
     341          66 :     info.conversationId = pimpl_->to_;
     342          66 :     info.path = path;
     343          66 :     auto f = std::make_shared<OutgoingFile>(channel, fileId, interactionId, info, start, end);
     344          66 :     f->onFinished([w = weak(), channel, onFinished = std::move(onFinished)](uint32_t code) {
     345          28 :         if (code == uint32_t(libjami::DataTransferEventCode::finished) && onFinished) {
     346           5 :             onFinished();
     347             :         }
     348             :         // schedule destroy outgoing transfer as not needed
     349          28 :         dht::ThreadPool().computation().run([w, channel] {
     350          28 :             if (auto sthis_ = w.lock()) {
     351          28 :                 auto& pimpl = sthis_->pimpl_;
     352          28 :                 std::lock_guard lk {pimpl->mapMutex_};
     353          28 :                 auto itO = pimpl->outgoings_.find(channel);
     354          28 :                 if (itO != pimpl->outgoings_.end())
     355          28 :                     pimpl->outgoings_.erase(itO);
     356          56 :             }
     357          28 :         });
     358          28 :     });
     359          66 :     pimpl_->outgoings_.emplace(channel, f);
     360          66 :     dht::ThreadPool::io().run([w = std::weak_ptr<OutgoingFile>(f)] {
     361          66 :         if (auto of = w.lock())
     362          66 :             of->process();
     363          66 :     });
     364          68 : }
     365             : 
     366             : bool
     367           1 : TransferManager::cancel(const std::string& fileId)
     368             : {
     369           1 :     std::lock_guard lk {pimpl_->mapMutex_};
     370             :     // Remove from waiting, this avoid auto-download
     371           1 :     auto itW = pimpl_->waitingIds_.find(fileId);
     372           1 :     if (itW != pimpl_->waitingIds_.end()) {
     373           1 :         pimpl_->waitingIds_.erase(itW);
     374           1 :         JAMI_DBG() << "Cancel " << fileId;
     375           1 :         pimpl_->saveWaiting();
     376             :     }
     377           1 :     auto itC = pimpl_->incomings_.find(fileId);
     378           1 :     if (itC == pimpl_->incomings_.end())
     379           0 :         return false;
     380           1 :     itC->second->cancel();
     381           1 :     return true;
     382           1 : }
     383             : 
     384             : bool
     385           2 : TransferManager::info(const std::string& fileId,
     386             :                       std::string& path,
     387             :                       int64_t& total,
     388             :                       int64_t& progress) const noexcept
     389             : {
     390           2 :     std::unique_lock lk {pimpl_->mapMutex_};
     391           2 :     if (pimpl_->to_.empty())
     392           0 :         return false;
     393             : 
     394           2 :     auto itI = pimpl_->incomings_.find(fileId);
     395           2 :     auto itW = pimpl_->waitingIds_.find(fileId);
     396           2 :     path = this->path(fileId).string();
     397           2 :     if (itI != pimpl_->incomings_.end()) {
     398           0 :         total = itI->second->info().totalSize;
     399           0 :         progress = itI->second->info().bytesProgress;
     400           0 :         return true;
     401           2 :     } else if (std::filesystem::is_regular_file(path)) {
     402           1 :         std::ifstream transfer(path, std::ios::binary);
     403           1 :         transfer.seekg(0, std::ios::end);
     404           1 :         progress = transfer.tellg();
     405           1 :         if (itW != pimpl_->waitingIds_.end()) {
     406           0 :             total = itW->second.totalSize;
     407             :         } else {
     408             :             // If not waiting it's finished
     409           1 :             total = progress;
     410             :         }
     411           1 :         return true;
     412           2 :     } else if (itW != pimpl_->waitingIds_.end()) {
     413           0 :         total = itW->second.totalSize;
     414           0 :         progress = 0;
     415           0 :         return true;
     416             :     }
     417             :     // Else we don't know infos there.
     418           1 :     progress = 0;
     419           1 :     return false;
     420           2 : }
     421             : 
     422             : void
     423          11 : TransferManager::waitForTransfer(const std::string& fileId,
     424             :                                  const std::string& interactionId,
     425             :                                  const std::string& sha3sum,
     426             :                                  const std::string& path,
     427             :                                  std::size_t total)
     428             : {
     429          11 :     std::unique_lock lk(pimpl_->mapMutex_);
     430          11 :     auto itW = pimpl_->waitingIds_.find(fileId);
     431          11 :     if (itW != pimpl_->waitingIds_.end())
     432           0 :         return;
     433          11 :     pimpl_->waitingIds_[fileId] = {fileId, interactionId, sha3sum, path, total};
     434          11 :     pimpl_->saveWaiting();
     435          11 : }
     436             : 
     437             : void
     438          11 : TransferManager::onIncomingFileTransfer(const std::string& fileId,
     439             :                                         const std::shared_ptr<dhtnet::ChannelSocket>& channel)
     440             : {
     441          11 :     std::lock_guard lk(pimpl_->mapMutex_);
     442             :     // Check if not already an incoming file for this id and that we are waiting this file
     443          11 :     auto itC = pimpl_->incomings_.find(fileId);
     444          11 :     if (itC != pimpl_->incomings_.end()) {
     445           0 :         channel->shutdown();
     446           0 :         return;
     447             :     }
     448          11 :     auto itW = pimpl_->waitingIds_.find(fileId);
     449          11 :     if (itW == pimpl_->waitingIds_.end()) {
     450           0 :         channel->shutdown();
     451           0 :         return;
     452             :     }
     453             : 
     454          11 :     libjami::DataTransferInfo info;
     455          11 :     info.accountId = pimpl_->accountId_;
     456          11 :     info.conversationId = pimpl_->to_;
     457          11 :     info.path = itW->second.path;
     458          11 :     info.totalSize = itW->second.totalSize;
     459             : 
     460             :     // Generate the file path within the conversation data directory
     461             :     // using the file id if no path has been specified, otherwise create
     462             :     // a symlink(Note: this will not work on Windows).
     463          11 :     auto filePath = path(fileId);
     464          11 :     if (info.path.empty()) {
     465           0 :         info.path = filePath.string();
     466             :     } else {
     467             :         // We don't need to check if this is an existing symlink here, as
     468             :         // the attempt to create one should report the error string correctly.
     469          11 :         fileutils::createFileLink(filePath, info.path);
     470             :     }
     471          11 :     info.bytesProgress = fileutils::size(info.path);
     472          11 :     if (info.bytesProgress < 0)
     473          11 :         info.bytesProgress = 0;
     474             : 
     475          11 :     auto ifile = std::make_shared<IncomingFile>(std::move(channel),
     476             :                                                 info,
     477             :                                                 fileId,
     478          11 :                                                 itW->second.interactionId,
     479          22 :                                                 itW->second.sha3sum);
     480          11 :     auto res = pimpl_->incomings_.emplace(fileId, std::move(ifile));
     481          11 :     if (res.second) {
     482          11 :         res.first->second->onFinished([w = weak(), fileId](uint32_t code) {
     483             :             // schedule destroy transfer as not needed
     484          11 :             dht::ThreadPool().computation().run([w, fileId, code] {
     485          11 :                 if (auto sthis_ = w.lock()) {
     486          11 :                     auto& pimpl = sthis_->pimpl_;
     487          11 :                     std::lock_guard lk {pimpl->mapMutex_};
     488          11 :                     auto itO = pimpl->incomings_.find(fileId);
     489          11 :                     if (itO != pimpl->incomings_.end())
     490          11 :                         pimpl->incomings_.erase(itO);
     491          11 :                     if (code == uint32_t(libjami::DataTransferEventCode::finished)) {
     492           7 :                         auto itW = pimpl->waitingIds_.find(fileId);
     493           7 :                         if (itW != pimpl->waitingIds_.end()) {
     494           7 :                             pimpl->waitingIds_.erase(itW);
     495           7 :                             pimpl->saveWaiting();
     496             :                         }
     497             :                     }
     498          22 :                 }
     499          11 :             });
     500          11 :         });
     501          11 :         res.first->second->process();
     502             :     }
     503          11 : }
     504             : 
     505             : std::filesystem::path
     506          37 : TransferManager::path(const std::string& fileId) const
     507             : {
     508          37 :     return pimpl_->conversationDataPath_ / fileId;
     509             : }
     510             : 
     511             : void
     512          51 : TransferManager::onIncomingProfile(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
     513             :                                    const std::string& sha3Sum)
     514             : {
     515          51 :     if (!channel)
     516           1 :         return;
     517             : 
     518          51 :     auto chName = channel->name();
     519          51 :     std::string_view name = chName;
     520          51 :     auto sep = name.find_last_of('?');
     521          51 :     if (sep != std::string::npos)
     522           5 :         name = name.substr(0, sep);
     523             : 
     524          51 :     auto lastSep = name.find_last_of('/');
     525          51 :     auto fileId = name.substr(lastSep + 1);
     526             : 
     527          51 :     auto deviceId = channel->deviceId().toString();
     528          51 :     auto cert = channel->peerCertificate();
     529          51 :     if (!cert || !cert->issuer || fileId.find(".vcf") == std::string::npos)
     530           1 :         return;
     531             : 
     532          55 :     auto uri = fileId == "profile.vcf" ? cert->issuer->getId().toString()
     533          55 :                                        : std::string(fileId.substr(0, fileId.size() - 4 /*.vcf*/));
     534             : 
     535          50 :     std::lock_guard lk(pimpl_->mapMutex_);
     536          50 :     auto idx = std::make_pair(deviceId, uri);
     537             :     // Check if not already an incoming file for this id and that we are waiting this file
     538          50 :     auto itV = pimpl_->vcards_.find(idx);
     539          50 :     if (itV != pimpl_->vcards_.end()) {
     540           0 :         channel->shutdown();
     541           0 :         return;
     542             :     }
     543             : 
     544          50 :     auto tid = generateUID(pimpl_->rand_);
     545          50 :     libjami::DataTransferInfo info;
     546          50 :     info.accountId = pimpl_->accountId_;
     547          50 :     info.conversationId = pimpl_->to_;
     548             : 
     549         100 :     auto recvDir = fileutils::get_cache_dir() / pimpl_->accountId_ / "vcard";
     550          50 :     dhtnet::fileutils::recursive_mkdir(recvDir);
     551          50 :     info.path = (recvDir / fmt::format("{:s}_{:s}_{}", deviceId, uri, tid)).string();
     552             : 
     553          50 :     auto ifile = std::make_shared<IncomingFile>(std::move(channel), info, "profile.vcf", "", sha3Sum);
     554          50 :     auto res = pimpl_->vcards_.emplace(idx, std::move(ifile));
     555          50 :     if (res.second) {
     556         200 :         res.first->second->onFinished([w = weak(),
     557          50 :                                        uri = std::move(uri),
     558          50 :                                        deviceId = std::move(deviceId),
     559          50 :                                        accountId = pimpl_->accountId_,
     560          50 :                                        cert = std::move(cert),
     561             :                                        path = info.path](uint32_t code) {
     562         250 :             dht::ThreadPool().computation().run([w,
     563          50 :                                                  uri = std::move(uri),
     564          50 :                                                  deviceId = std::move(deviceId),
     565          50 :                                                  accountId = std::move(accountId),
     566          50 :                                                  path = std::move(path),
     567          50 :                                                  code] {
     568          50 :                 if (auto sthis_ = w.lock()) {
     569          50 :                     auto& pimpl = sthis_->pimpl_;
     570             : 
     571          50 :                     auto destPath = sthis_->profilePath(uri);
     572             :                     try {
     573             :                         // Move profile to destination path
     574          50 :                         std::lock_guard lock(dhtnet::fileutils::getFileLock(destPath));
     575          50 :                         dhtnet::fileutils::recursive_mkdir(destPath.parent_path());
     576          50 :                         std::filesystem::rename(path, destPath);
     577          50 :                         if (!pimpl->accountUri_.empty() && uri == pimpl->accountUri_) {
     578             :                             // If this is the account profile, link or copy it to the account profile path
     579           1 :                             if (!fileutils::createFileLink(pimpl->accountProfilePath_, destPath)) {
     580           0 :                                 std::error_code ec;
     581           0 :                                 std::filesystem::copy_file(destPath, pimpl->accountProfilePath_, ec);
     582             :                             }
     583             :                         }
     584          50 :                     } catch (const std::exception& e) {
     585           0 :                         JAMI_ERROR("{}", e.what());
     586           0 :                     }
     587             : 
     588          50 :                     std::lock_guard lk {pimpl->mapMutex_};
     589          50 :                     auto itO = pimpl->vcards_.find({deviceId, uri});
     590          50 :                     if (itO != pimpl->vcards_.end())
     591          50 :                         pimpl->vcards_.erase(itO);
     592          50 :                     if (code == uint32_t(libjami::DataTransferEventCode::finished)) {
     593          50 :                         emitSignal<libjami::ConfigurationSignal::ProfileReceived>(accountId,
     594          50 :                                                                                   uri,
     595         100 :                                                                                   destPath.string());
     596             :                     }
     597         100 :                 }
     598          50 :             });
     599          50 :         });
     600          50 :         res.first->second->process();
     601             :     }
     602          53 : }
     603             : 
     604             : std::filesystem::path
     605          62 : TransferManager::profilePath(const std::string& contactId) const
     606             : {
     607         124 :     return pimpl_->profilesPath_ / fmt::format("{}.vcf", base64::encode(contactId));
     608             : }
     609             : 
     610             : std::vector<WaitingRequest>
     611        2268 : TransferManager::waitingRequests() const
     612             : {
     613        2268 :     std::vector<WaitingRequest> res;
     614        2268 :     std::lock_guard lk(pimpl_->mapMutex_);
     615        2268 :     for (const auto& [fileId, req] : pimpl_->waitingIds_) {
     616           0 :         auto itC = pimpl_->incomings_.find(fileId);
     617           0 :         if (itC == pimpl_->incomings_.end())
     618           0 :             res.emplace_back(req);
     619             :     }
     620        4536 :     return res;
     621        2268 : }
     622             : 
     623             : bool
     624           1 : TransferManager::isWaiting(const std::string& fileId) const
     625             : {
     626           1 :     std::lock_guard lk(pimpl_->mapMutex_);
     627           2 :     return pimpl_->waitingIds_.find(fileId) != pimpl_->waitingIds_.end();
     628           1 : }
     629             : 
     630             : } // namespace jami

Generated by: LCOV version 1.14