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 :
18 : #include "message_engine.h"
19 : #include "sip/sipaccountbase.h"
20 : #include "manager.h"
21 :
22 : #include "client/jami_signal.h"
23 : #include "jami/account_const.h"
24 :
25 : #include <dhtnet/fileutils.h>
26 : #include <opendht/thread_pool.h>
27 : #include <fmt/std.h>
28 :
29 : #include <fstream>
30 :
31 : namespace jami {
32 : namespace im {
33 :
34 708 : MessageEngine::MessageEngine(SIPAccountBase& acc, const std::filesystem::path& path)
35 708 : : account_(acc)
36 708 : , savePath_(path)
37 708 : , ioContext_(Manager::instance().ioContext())
38 708 : , saveTimer_(*ioContext_)
39 : {
40 708 : dhtnet::fileutils::check_dir(savePath_.parent_path());
41 708 : }
42 :
43 : MessageToken
44 14384 : MessageEngine::sendMessage(const std::string& to,
45 : const std::string& deviceId,
46 : const std::map<std::string, std::string>& payloads,
47 : uint64_t refreshToken)
48 : {
49 14384 : if (payloads.empty() or to.empty())
50 0 : return 0;
51 14387 : MessageToken token = 0;
52 : {
53 14387 : std::lock_guard lock(messagesMutex_);
54 14394 : auto& peerMessages = deviceId.empty() ? messages_[to] : messagesDevices_[deviceId];
55 14392 : if (refreshToken != 0) {
56 12247 : for (auto& m : peerMessages) {
57 889 : if (m.token == refreshToken) {
58 889 : token = refreshToken;
59 889 : m.to = to;
60 889 : m.payloads = payloads;
61 889 : m.status = MessageStatus::IDLE;
62 889 : break;
63 : }
64 : }
65 : }
66 14397 : if (token == 0) {
67 13505 : token = std::uniform_int_distribution<MessageToken> {1, JAMI_ID_MAX_VAL}(account_.rand);
68 13513 : auto& m = peerMessages.emplace_back(Message {token});
69 13486 : m.to = to;
70 13489 : m.payloads = payloads;
71 : }
72 14395 : scheduleSave();
73 14408 : }
74 28816 : asio::post(*ioContext_, [this, to, deviceId]() { retrySend(to, deviceId, true); });
75 14388 : return token;
76 : }
77 :
78 : void
79 2101 : MessageEngine::onPeerOnline(const std::string& peer, const std::string& deviceId, bool retryOnTimeout)
80 : {
81 2101 : retrySend(peer, deviceId, retryOnTimeout);
82 2101 : }
83 :
84 : void
85 16510 : MessageEngine::retrySend(const std::string& peer, const std::string& deviceId, bool retryOnTimeout)
86 : {
87 : struct PendingMsg
88 : {
89 : MessageToken token;
90 : std::string to;
91 : std::map<std::string, std::string> payloads;
92 : };
93 16510 : std::vector<PendingMsg> pending {};
94 16508 : auto now = clock::now();
95 : {
96 16509 : std::lock_guard lock(messagesMutex_);
97 16510 : auto& m = deviceId.empty() ? messages_ : messagesDevices_;
98 16510 : auto p = m.find(deviceId.empty() ? peer : deviceId);
99 16509 : if (p == m.end())
100 1299 : return;
101 15209 : auto& messages = p->second;
102 :
103 30281 : for (auto& m : messages) {
104 15071 : if (m.status == MessageStatus::IDLE) {
105 15063 : m.status = MessageStatus::SENDING;
106 15063 : m.retried++;
107 15063 : m.last_op = now;
108 15063 : pending.emplace_back(PendingMsg {m.token, m.to, m.payloads});
109 : }
110 : }
111 16509 : }
112 : // avoid locking while calling callback
113 30273 : for (const auto& p : pending) {
114 60252 : JAMI_DEBUG("[Account {:s}] [message {:d}] Reattempt sending", account_.getAccountID(), p.token);
115 15063 : if (p.payloads.find("application/im-gitmessage-id") == p.payloads.end())
116 596 : emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>(
117 596 : account_.getAccountID(),
118 : "",
119 596 : p.to,
120 1192 : std::to_string(p.token),
121 : (int) libjami::Account::MessageStates::SENDING);
122 15063 : account_.sendMessage(p.to, deviceId, p.payloads, p.token, retryOnTimeout, false);
123 : }
124 16509 : }
125 :
126 : MessageStatus
127 0 : MessageEngine::getStatus(MessageToken t) const
128 : {
129 0 : std::lock_guard lock(messagesMutex_);
130 0 : for (const auto& p : messages_) {
131 0 : for (const auto& m : p.second) {
132 0 : if (m.token == t)
133 0 : return m.status;
134 : }
135 : }
136 0 : return MessageStatus::UNKNOWN;
137 0 : }
138 :
139 : void
140 15062 : MessageEngine::onMessageSent(const std::string& peer, MessageToken token, bool ok, const std::string& deviceId)
141 : {
142 60241 : JAMI_DEBUG("[Account {:s}] [message {:d}] Message sent: {:s}",
143 : account_.getAccountID(),
144 : token,
145 : ok ? "success"sv : "failure"sv);
146 15062 : std::lock_guard lock(messagesMutex_);
147 15063 : auto& m = deviceId.empty() ? messages_ : messagesDevices_;
148 :
149 15062 : auto p = m.find(deviceId.empty() ? peer : deviceId);
150 15063 : if (p == m.end()) {
151 0 : JAMI_WARNING("[Account {:s}] onMessageSent: Peer not found: id:{} device:{}",
152 : account_.getAccountID(),
153 : peer,
154 : deviceId);
155 0 : return;
156 : }
157 :
158 30317 : auto f = std::find_if(p->second.begin(), p->second.end(), [&](const Message& m) { return m.token == token; });
159 15063 : if (f != p->second.end()) {
160 15063 : auto emit = f->payloads.find("application/im-gitmessage-id") == f->payloads.end();
161 15062 : if (f->status == MessageStatus::SENDING) {
162 15040 : if (ok) {
163 13198 : f->status = MessageStatus::SENT;
164 52792 : JAMI_LOG("[Account {:s}] [message {:d}] Status changed to SENT", account_.getAccountID(), token);
165 13199 : if (emit)
166 400 : emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>(
167 400 : account_.getAccountID(),
168 : "",
169 400 : f->to,
170 800 : std::to_string(token),
171 : static_cast<int>(libjami::Account::MessageStates::SENT));
172 13199 : p->second.erase(f);
173 13199 : scheduleSave();
174 1842 : } else if (f->retried >= MAX_RETRIES) {
175 4 : f->status = MessageStatus::FAILURE;
176 16 : JAMI_WARNING("[Account {:s}] [message {:d}] Status changed to FAILURE", account_.getAccountID(), token);
177 4 : if (emit)
178 0 : emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>(
179 0 : account_.getAccountID(),
180 : "",
181 0 : f->to,
182 0 : std::to_string(token),
183 : static_cast<int>(libjami::Account::MessageStates::FAILURE));
184 4 : p->second.erase(f);
185 4 : scheduleSave();
186 : } else {
187 1838 : f->status = MessageStatus::IDLE;
188 7352 : JAMI_DEBUG("[Account {:s}] [message {:d}] Status changed to IDLE", account_.getAccountID(), token);
189 : }
190 : } else {
191 88 : JAMI_DEBUG("[Account {:s}] [message {:d}] State is not SENDING", account_.getAccountID(), token);
192 : }
193 : } else {
194 0 : JAMI_DEBUG("[Account {:s}] [message {:d}] Unable to find message", account_.getAccountID(), token);
195 : }
196 15063 : }
197 :
198 : void
199 25 : MessageEngine::load()
200 : {
201 : try {
202 25 : decltype(messages_) root;
203 : {
204 25 : std::lock_guard lock(dhtnet::fileutils::getFileLock(savePath_));
205 25 : std::ifstream file;
206 25 : file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
207 25 : file.open(savePath_);
208 1 : if (file.is_open()) {
209 1 : msgpack::unpacker up;
210 1 : up.reserve_buffer(UINT16_MAX);
211 1 : while (file.read(up.buffer(), UINT16_MAX)) {
212 0 : up.buffer_consumed(file.gcount());
213 0 : msgpack::object_handle oh;
214 0 : if (up.next(oh)) {
215 0 : root = oh.get().as<std::map<std::string, std::list<Message>>>();
216 0 : break;
217 : }
218 0 : up.reserve_buffer(UINT16_MAX);
219 0 : }
220 1 : }
221 50 : }
222 0 : std::lock_guard lock(messagesMutex_);
223 0 : messages_ = std::move(root);
224 0 : if (not messages_.empty()) {
225 0 : JAMI_LOG("[Account {}] Loaded {} messages from {}", account_.getAccountID(), messages_.size(), savePath_);
226 : }
227 50 : } catch (const std::exception& e) {
228 100 : JAMI_LOG("[Account {}] Unable to load messages from {}: {}", account_.getAccountID(), savePath_, e.what());
229 25 : }
230 25 : }
231 :
232 : void
233 144 : MessageEngine::save() const
234 : {
235 144 : std::lock_guard lock(messagesMutex_);
236 144 : save_();
237 144 : }
238 :
239 : void
240 27594 : MessageEngine::scheduleSave()
241 : {
242 27594 : saveTimer_.expires_after(std::chrono::seconds(5));
243 27611 : saveTimer_.async_wait([this, w = account_.weak_from_this()](const std::error_code& ec) {
244 27611 : if (!ec)
245 143 : if (auto acc = w.lock())
246 143 : save();
247 27611 : });
248 27611 : }
249 :
250 : void
251 144 : MessageEngine::save_() const
252 : {
253 : try {
254 144 : std::ofstream file;
255 144 : file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
256 144 : file.open(savePath_, std::ios::trunc);
257 144 : if (file.is_open())
258 144 : msgpack::pack(file, messages_);
259 144 : } catch (const std::exception& e) {
260 0 : JAMI_ERROR("[Account {}] Unable to serialize pending messages: {}", account_.getAccountID(), e.what());
261 0 : }
262 144 : }
263 :
264 : } // namespace im
265 : } // namespace jami
|