| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include "Utils.h" |
| 6 | |
| 7 | #include <array> |
| 8 | #include <cmath> |
| 9 | #include <unordered_set> |
| 10 | #include <variant> |
| 11 | |
| 12 | #include <QApplication> |
| 13 | #include <QBuffer> |
| 14 | #include <QComboBox> |
| 15 | #include <QCryptographicHash> |
| 16 | #include <QFile> |
| 17 | #include <QGuiApplication> |
| 18 | #include <QImageReader> |
| 19 | #include <QProcessEnvironment> |
| 20 | #include <QRandomGenerator64> |
| 21 | #include <QScreen> |
| 22 | #include <QSettings> |
| 23 | #include <QStringBuilder> |
| 24 | #include <QTextBoundaryFinder> |
| 25 | #include <QTextDocument> |
| 26 | #include <QTimer> |
| 27 | #include <QWindow> |
| 28 | #include <QXmlStreamReader> |
| 29 | |
| 30 | #include <fmt/ranges.h> |
| 31 | #include <nlohmann/json.hpp> |
| 32 | |
| 33 | #include <cmark.h> |
| 34 | |
| 35 | #include <mtx/responses/messages.hpp> |
| 36 | |
| 37 | #include "Cache.h" |
| 38 | #include "Cache_p.h" |
| 39 | #include "ChatPage.h" |
| 40 | #include "Config.h" |
| 41 | #include "EventAccessors.h" |
| 42 | #include "Logging.h" |
| 43 | #include "MatrixClient.h" |
| 44 | #include "UserSettingsPage.h" |
| 45 | |
| 46 | static QString |
| 47 | getQuoteBody(const RelatedInfo &related); |
| 48 | |
| 49 | //! Match widgets/events with a description message. |
| 50 | namespace { |
| 51 | template<class T> |
| 52 | QString |
| 53 | messageDescription(const QString &username, |
| 54 | const QString &body, |
| 55 | const bool isLocal, |
| 56 | bool containsSpoiler) |
| 57 | { |
| 58 | using Audio = mtx::events::RoomEvent<mtx::events::msg::Audio>; |
| 59 | using Emote = mtx::events::RoomEvent<mtx::events::msg::Emote>; |
| 60 | using File = mtx::events::RoomEvent<mtx::events::msg::File>; |
| 61 | using Image = mtx::events::RoomEvent<mtx::events::msg::Image>; |
| 62 | using Notice = mtx::events::RoomEvent<mtx::events::msg::Notice>; |
| 63 | using Sticker = mtx::events::Sticker; |
| 64 | using Text = mtx::events::RoomEvent<mtx::events::msg::Text>; |
| 65 | using Unknown = mtx::events::RoomEvent<mtx::events::msg::Unknown>; |
| 66 | using Video = mtx::events::RoomEvent<mtx::events::msg::Video>; |
| 67 | using ElementEffect = mtx::events::RoomEvent<mtx::events::msg::ElementEffect>; |
| 68 | using CallInvite = mtx::events::RoomEvent<mtx::events::voip::CallInvite>; |
| 69 | using CallAnswer = mtx::events::RoomEvent<mtx::events::voip::CallAnswer>; |
| 70 | using CallHangUp = mtx::events::RoomEvent<mtx::events::voip::CallHangUp>; |
| 71 | using CallReject = mtx::events::RoomEvent<mtx::events::voip::CallReject>; |
| 72 | using Encrypted = mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>; |
| 73 | |
| 74 | if (std::is_same<T, Audio>::value) { |
| 75 | if (isLocal) |
| 76 | return QCoreApplication::translate("message-description sent:", |
| 77 | "You sent an audio clip"); |
| 78 | else |
| 79 | return QCoreApplication::translate("message-description sent:", "%1 sent an audio clip") |
| 80 | .arg(username); |
| 81 | } else if (std::is_same<T, Image>::value) { |
| 82 | if (isLocal) |
| 83 | return QCoreApplication::translate("message-description sent:", "You sent an image"); |
| 84 | else |
| 85 | return QCoreApplication::translate("message-description sent:", "%1 sent an image") |
| 86 | .arg(username); |
| 87 | } else if (std::is_same<T, File>::value) { |
| 88 | if (isLocal) |
| 89 | return QCoreApplication::translate("message-description sent:", "You sent a file"); |
| 90 | else |
| 91 | return QCoreApplication::translate("message-description sent:", "%1 sent a file") |
| 92 | .arg(username); |
| 93 | } else if (std::is_same<T, Video>::value) { |
| 94 | if (isLocal) |
| 95 | return QCoreApplication::translate("message-description sent:", "You sent a video"); |
| 96 | else |
| 97 | return QCoreApplication::translate("message-description sent:", "%1 sent a video") |
| 98 | .arg(username); |
| 99 | } else if (std::is_same<T, Sticker>::value) { |
| 100 | if (isLocal) |
| 101 | return QCoreApplication::translate("message-description sent:", "You sent a sticker"); |
| 102 | else |
| 103 | return QCoreApplication::translate("message-description sent:", "%1 sent a sticker") |
| 104 | .arg(username); |
| 105 | } else if (std::is_same<T, Notice>::value) { |
| 106 | if (isLocal) |
| 107 | return QCoreApplication::translate("message-description sent:", |
| 108 | "You sent a notification"); |
| 109 | else |
| 110 | return QCoreApplication::translate("message-description sent:", |
| 111 | "%1 sent a notification") |
| 112 | .arg(username); |
| 113 | } else if (std::is_same<T, Text>::value || std::is_same<T, Unknown>::value) { |
| 114 | if (containsSpoiler) { |
| 115 | if (isLocal) |
| 116 | return QCoreApplication::translate("message-description sent:", |
| 117 | "You sent a spoiler."); |
| 118 | else |
| 119 | return QCoreApplication::translate("message-description sent:", |
| 120 | "%1 sent a spoiler.") |
| 121 | .arg(username); |
| 122 | } |
| 123 | |
| 124 | if (isLocal) |
| 125 | return QCoreApplication::translate("message-description sent:", "You: %1").arg(body); |
| 126 | else |
| 127 | return QCoreApplication::translate("message-description sent:", "%1: %2") |
| 128 | .arg(username, body); |
| 129 | } else if (std::is_same<T, ElementEffect>::value) { |
| 130 | if (body.isEmpty()) { |
| 131 | // TODO: what is the best way to handle this? |
| 132 | if (isLocal) |
| 133 | return QCoreApplication::translate("message-description sent:", |
| 134 | "You sent a chat effect"); |
| 135 | else |
| 136 | return QCoreApplication::translate("message-description sent:", |
| 137 | "%1 sent a chat effect") |
| 138 | .arg(username); |
| 139 | } else { |
| 140 | if (containsSpoiler) { |
| 141 | if (isLocal) |
| 142 | return QCoreApplication::translate("message-description sent:", |
| 143 | "You sent a spoiler."); |
| 144 | else |
| 145 | return QCoreApplication::translate("message-description sent:", |
| 146 | "%1 sent a spoiler.") |
| 147 | .arg(username); |
| 148 | } |
| 149 | |
| 150 | if (isLocal) |
| 151 | return QCoreApplication::translate("message-description sent:", "You: %1") |
| 152 | .arg(body); |
| 153 | else |
| 154 | return QCoreApplication::translate("message-description sent:", "%1: %2") |
| 155 | .arg(username, body); |
| 156 | } |
| 157 | } else if (std::is_same<T, Emote>::value) { |
| 158 | if (containsSpoiler) { |
| 159 | return QCoreApplication::translate("message-description sent:", |
| 160 | "* %1 spoils something.") |
| 161 | .arg(username); |
| 162 | } |
| 163 | |
| 164 | return QStringLiteral("* %1 %2").arg(username, body); |
| 165 | } else if (std::is_same<T, Encrypted>::value) { |
| 166 | if (isLocal) |
| 167 | return QCoreApplication::translate("message-description sent:", |
| 168 | "You sent an encrypted message"); |
| 169 | else |
| 170 | return QCoreApplication::translate("message-description sent:", |
| 171 | "%1 sent an encrypted message") |
| 172 | .arg(username); |
| 173 | } else if (std::is_same<T, CallInvite>::value) { |
| 174 | if (isLocal) |
| 175 | return QCoreApplication::translate("message-description sent:", "You placed a call"); |
| 176 | else |
| 177 | return QCoreApplication::translate("message-description sent:", "%1 placed a call") |
| 178 | .arg(username); |
| 179 | } else if (std::is_same<T, CallAnswer>::value) { |
| 180 | if (isLocal) |
| 181 | return QCoreApplication::translate("message-description sent:", "You answered a call"); |
| 182 | else |
| 183 | return QCoreApplication::translate("message-description sent:", "%1 answered a call") |
| 184 | .arg(username); |
| 185 | } else if (std::is_same<T, CallHangUp>::value) { |
| 186 | if (isLocal) |
| 187 | return QCoreApplication::translate("message-description sent:", "You ended a call"); |
| 188 | else |
| 189 | return QCoreApplication::translate("message-description sent:", "%1 ended a call") |
| 190 | .arg(username); |
| 191 | } else if (std::is_same<T, CallReject>::value) { |
| 192 | if (isLocal) |
| 193 | return QCoreApplication::translate("message-description sent:", "You rejected a call"); |
| 194 | else |
| 195 | return QCoreApplication::translate("message-description sent:", "%1 rejected a call") |
| 196 | .arg(username); |
| 197 | } else { |
| 198 | return QCoreApplication::translate("utils", "Unknown Message Type"); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | template<class T, class Event> |
| 204 | static DescInfo |
| 205 | createDescriptionInfo(const Event &event, const QString &localUser, const QString &displayName) |
| 206 | { |
| 207 | const auto msg = std::get<T>(event); |
| 208 | const auto sender = QString::fromStdString(msg.sender); |
| 209 | |
| 210 | const auto username = displayName; |
| 211 | const auto ts = QDateTime::fromMSecsSinceEpoch(msg.origin_server_ts); |
| 212 | auto body = mtx::accessors::body(event); |
| 213 | auto formatted_body = mtx::accessors::formatted_body(event); |
| 214 | if (mtx::accessors::relations(event).reply_to()) { |
| 215 | body = utils::stripReplyFromBody(body); |
| 216 | formatted_body = utils::stripReplyFromFormattedBody(formatted_body); |
| 217 | } |
| 218 | |
| 219 | // Simplistic heuristic |
| 220 | bool containsSpoiler = formatted_body.find("<span data-mx-spoiler") != formatted_body.npos; |
| 221 | |
| 222 | return DescInfo{QString::fromStdString(msg.event_id), |
| 223 | sender, |
| 224 | messageDescription<T>( |
| 225 | username, QString::fromStdString(body), sender == localUser, containsSpoiler), |
| 226 | utils::descriptiveTime(ts), |
| 227 | msg.origin_server_ts, |
| 228 | ts}; |
| 229 | } |
| 230 | |
| 231 | std::string |
| 232 | utils::stripReplyFromBody(const std::string &bodyi) |
| 233 | { |
| 234 | QString body = QString::fromStdString(bodyi); |
| 235 | if (body.startsWith(QLatin1String("> <"))) { |
| 236 | auto segments = body.split('\n'); |
| 237 | while (!segments.isEmpty() && segments.begin()->startsWith('>')) |
| 238 | segments.erase(segments.cbegin()); |
| 239 | if (!segments.empty() && segments.first().isEmpty()) |
| 240 | segments.erase(segments.cbegin()); |
| 241 | body = segments.join('\n'); |
| 242 | } |
| 243 | |
| 244 | body.replace(QLatin1String("@room"), QString::fromUtf8("@\u2060room")); |
| 245 | return body.toStdString(); |
| 246 | } |
| 247 | |
| 248 | std::string |
| 249 | utils::stripReplyFromFormattedBody(const std::string &formatted_bodyi) |
| 250 | { |
| 251 | QString formatted_body = QString::fromStdString(formatted_bodyi); |
| 252 | static QRegularExpression replyRegex(QStringLiteral("<mx-reply>.*</mx-reply>"), |
| 253 | QRegularExpression::DotMatchesEverythingOption); |
| 254 | formatted_body.remove(replyRegex); |
| 255 | formatted_body.replace(QLatin1String("@room"), QString::fromUtf8("@\u2060room")); |
| 256 | return formatted_body.toStdString(); |
| 257 | } |
| 258 | |
| 259 | RelatedInfo |
| 260 | utils::stripReplyFallbacks(const mtx::events::collections::TimelineEvents &event, |
| 261 | std::string id, |
| 262 | QString room_id_) |
| 263 | { |
| 264 | RelatedInfo related = {}; |
| 265 | related.quoted_user = QString::fromStdString(mtx::accessors::sender(event)); |
| 266 | related.related_event = std::move(id); |
| 267 | related.type = mtx::accessors::msg_type(event); |
| 268 | |
| 269 | // get body, strip reply fallback, then transform the event to text, if it is a media event |
| 270 | // etc |
| 271 | related.quoted_body = QString::fromStdString(mtx::accessors::body(event)); |
| 272 | related.quoted_body = |
| 273 | QString::fromStdString(stripReplyFromBody(related.quoted_body.toStdString())); |
| 274 | related.quoted_body = getQuoteBody(related); |
| 275 | |
| 276 | // get quoted body and strip reply fallback |
| 277 | related.quoted_formatted_body = mtx::accessors::formattedBodyWithFallback(event); |
| 278 | related.quoted_formatted_body = QString::fromStdString( |
| 279 | stripReplyFromFormattedBody(related.quoted_formatted_body.toStdString())); |
| 280 | related.room = room_id_; |
| 281 | |
| 282 | return related; |
| 283 | } |
| 284 | |
| 285 | QString |
| 286 | utils::localUser() |
| 287 | { |
| 288 | return QString::fromStdString(http::client()->user_id().to_string()); |
| 289 | } |
| 290 | |
| 291 | bool |
| 292 | utils::codepointIsEmoji(uint code) |
| 293 | { |
| 294 | // TODO: Be more precise here. |
| 295 | return (code >= 0x2600 && code <= 0x27bf) || (code >= 0x2b00 && code <= 0x2bff) || |
| 296 | (code >= 0x1f000 && code <= 0x1faff) || code == 0x200d || code == 0xfe0f || |
| 297 | code == 0x231a || code == 0x231b || (code >= 0x23e9 && code <= 0x23ff) || |
| 298 | code == 0x25aa || code == 0x25ab || code == 0x25b6 || code == 0x25c0 || |
| 299 | (code >= 0x25fb && code <= 0x25fe) || (code >= 0x2460 && code <= 0x24ff); |
| 300 | } |
| 301 | |
| 302 | QString |
| 303 | utils::replaceEmoji(const QString &body) |
| 304 | { |
| 305 | if constexpr (QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)) { |
| 306 | return body; |
| 307 | } else { |
| 308 | QString fmtBody; |
| 309 | fmtBody.reserve(body.size()); |
| 310 | |
| 311 | QVector<uint> utf32_string = body.toUcs4(); |
| 312 | |
| 313 | bool insideFontBlock = false; |
| 314 | bool insideTag = false; |
| 315 | for (auto &code : utf32_string) { |
| 316 | if (code == U'<') |
| 317 | insideTag = true; |
| 318 | else if (code == U'>') |
| 319 | insideTag = false; |
| 320 | |
| 321 | if (!insideTag && utils::codepointIsEmoji(code)) { |
| 322 | if (!insideFontBlock) { |
| 323 | fmtBody += QStringLiteral("<font face=\"") % |
| 324 | UserSettings::instance()->emojiFont() % |
| 325 | (UserSettings::instance()->enlargeEmojiOnlyMessages() |
| 326 | ? QStringLiteral("\" size=\"4\">") |
| 327 | : QStringLiteral("\">")); |
| 328 | insideFontBlock = true; |
| 329 | } else if (code == 0xfe0f) { |
| 330 | // BUG(Nico): |
| 331 | // Workaround https://bugreports.qt.io/browse/QTBUG-97401 |
| 332 | // See also https://github.com/matrix-org/matrix-react-sdk/pull/1458/files |
| 333 | // Nheko bug: https://github.com/Nheko-Reborn/nheko/issues/439 |
| 334 | continue; |
| 335 | } |
| 336 | } else { |
| 337 | if (insideFontBlock) { |
| 338 | fmtBody += QStringLiteral("</font>"); |
| 339 | insideFontBlock = false; |
| 340 | } |
| 341 | } |
| 342 | if (QChar::requiresSurrogates(code)) { |
| 343 | QChar emoji[] = {static_cast<ushort>(QChar::highSurrogate(code)), |
| 344 | static_cast<ushort>(QChar::lowSurrogate(code))}; |
| 345 | fmtBody.append(emoji, 2); |
| 346 | } else { |
| 347 | fmtBody.append(QChar(static_cast<ushort>(code))); |
| 348 | } |
| 349 | } |
| 350 | if (insideFontBlock) { |
| 351 | fmtBody += QStringLiteral("</font>"); |
| 352 | } |
| 353 | |
| 354 | return fmtBody; |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | void |
| 359 | utils::setScaleFactor(float factor) |
| 360 | { |
| 361 | if (factor < 1 || factor > 3) |
| 362 | return; |
| 363 | |
| 364 | QSettings settings; |
| 365 | settings.setValue(QStringLiteral("settings/scale_factor"), factor); |
| 366 | } |
| 367 | |
| 368 | float |
| 369 | utils::scaleFactor() |
| 370 | { |
| 371 | QSettings settings; |
| 372 | return settings.value(QStringLiteral("settings/scale_factor"), -1).toFloat(); |
| 373 | } |
| 374 | |
| 375 | QString |
| 376 | utils::descriptiveTime(const QDateTime &then) |
| 377 | { |
| 378 | const auto now = QDateTime::currentDateTime(); |
| 379 | const auto days = then.daysTo(now); |
| 380 | |
| 381 | if (days == 0) |
| 382 | return QLocale::system().toString(then.time(), QLocale::ShortFormat); |
| 383 | else if (days < 2) |
| 384 | return QString(QCoreApplication::translate("descriptiveTime", "Yesterday")); |
| 385 | else if (days < 7) |
| 386 | return then.toString(QStringLiteral("dddd")); |
| 387 | |
| 388 | return QLocale::system().toString(then.date(), QLocale::ShortFormat); |
| 389 | } |
| 390 | |
| 391 | DescInfo |
| 392 | utils::getMessageDescription(const mtx::events::collections::TimelineEvents &event, |
| 393 | const QString &localUser, |
| 394 | const QString &displayName) |
| 395 | { |
| 396 | using Audio = mtx::events::RoomEvent<mtx::events::msg::Audio>; |
| 397 | using Emote = mtx::events::RoomEvent<mtx::events::msg::Emote>; |
| 398 | using File = mtx::events::RoomEvent<mtx::events::msg::File>; |
| 399 | using Image = mtx::events::RoomEvent<mtx::events::msg::Image>; |
| 400 | using Notice = mtx::events::RoomEvent<mtx::events::msg::Notice>; |
| 401 | using Text = mtx::events::RoomEvent<mtx::events::msg::Text>; |
| 402 | using Unknown = mtx::events::RoomEvent<mtx::events::msg::Unknown>; |
| 403 | using Video = mtx::events::RoomEvent<mtx::events::msg::Video>; |
| 404 | using ElementEffect = mtx::events::RoomEvent<mtx::events::msg::ElementEffect>; |
| 405 | using CallInvite = mtx::events::RoomEvent<mtx::events::voip::CallInvite>; |
| 406 | using CallAnswer = mtx::events::RoomEvent<mtx::events::voip::CallAnswer>; |
| 407 | using CallHangUp = mtx::events::RoomEvent<mtx::events::voip::CallHangUp>; |
| 408 | using CallReject = mtx::events::RoomEvent<mtx::events::voip::CallReject>; |
| 409 | using Encrypted = mtx::events::EncryptedEvent<mtx::events::msg::Encrypted>; |
| 410 | |
| 411 | if (std::holds_alternative<Audio>(event)) { |
| 412 | return createDescriptionInfo<Audio>(event, localUser, displayName); |
| 413 | } else if (std::holds_alternative<Emote>(event)) { |
| 414 | return createDescriptionInfo<Emote>(event, localUser, displayName); |
| 415 | } else if (std::holds_alternative<File>(event)) { |
| 416 | return createDescriptionInfo<File>(event, localUser, displayName); |
| 417 | } else if (std::holds_alternative<Image>(event)) { |
| 418 | return createDescriptionInfo<Image>(event, localUser, displayName); |
| 419 | } else if (std::holds_alternative<Notice>(event)) { |
| 420 | return createDescriptionInfo<Notice>(event, localUser, displayName); |
| 421 | } else if (std::holds_alternative<Text>(event)) { |
| 422 | return createDescriptionInfo<Text>(event, localUser, displayName); |
| 423 | } else if (std::holds_alternative<Unknown>(event)) { |
| 424 | return createDescriptionInfo<Unknown>(event, localUser, displayName); |
| 425 | } else if (std::holds_alternative<Video>(event)) { |
| 426 | return createDescriptionInfo<Video>(event, localUser, displayName); |
| 427 | } else if (std::holds_alternative<ElementEffect>(event)) { |
| 428 | return createDescriptionInfo<ElementEffect>(event, localUser, displayName); |
| 429 | } else if (std::holds_alternative<CallInvite>(event)) { |
| 430 | return createDescriptionInfo<CallInvite>(event, localUser, displayName); |
| 431 | } else if (std::holds_alternative<CallAnswer>(event)) { |
| 432 | return createDescriptionInfo<CallAnswer>(event, localUser, displayName); |
| 433 | } else if (std::holds_alternative<CallHangUp>(event)) { |
| 434 | return createDescriptionInfo<CallHangUp>(event, localUser, displayName); |
| 435 | } else if (std::holds_alternative<CallReject>(event)) { |
| 436 | return createDescriptionInfo<CallReject>(event, localUser, displayName); |
| 437 | } else if (std::holds_alternative<mtx::events::Sticker>(event)) { |
| 438 | return createDescriptionInfo<mtx::events::Sticker>(event, localUser, displayName); |
| 439 | } else if (auto msg = std::get_if<Encrypted>(&event); msg != nullptr) { |
| 440 | const auto sender = QString::fromStdString(msg->sender); |
| 441 | |
| 442 | const auto username = displayName; |
| 443 | const auto ts = QDateTime::fromMSecsSinceEpoch(msg->origin_server_ts); |
| 444 | |
| 445 | DescInfo info; |
| 446 | info.userid = sender; |
| 447 | info.body = QStringLiteral(" %1").arg( |
| 448 | messageDescription<Encrypted>(username, QLatin1String(""), sender == localUser, false)); |
| 449 | info.timestamp = msg->origin_server_ts; |
| 450 | info.descriptiveTime = utils::descriptiveTime(ts); |
| 451 | info.event_id = QString::fromStdString(msg->event_id); |
| 452 | info.datetime = ts; |
| 453 | |
| 454 | return info; |
| 455 | } |
| 456 | |
| 457 | return DescInfo{}; |
| 458 | } |
| 459 | |
| 460 | QString |
| 461 | utils::firstChar(const QString &input) |
| 462 | { |
| 463 | if (input.isEmpty()) |
| 464 | return input; |
| 465 | |
| 466 | for (auto const &c : input.toStdU32String()) { |
| 467 | if (QString::fromUcs4(&c, 1) != QStringLiteral("#")) |
| 468 | return QString::fromUcs4(&c, 1).toUpper(); |
| 469 | } |
| 470 | |
| 471 | return QString::fromUcs4(&input.toStdU32String().at(0), 1).toUpper(); |
| 472 | } |
| 473 | |
| 474 | QString |
| 475 | utils::humanReadableFileSize(uint64_t bytes) |
| 476 | { |
| 477 | constexpr static const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"}; |
| 478 | constexpr static const int length = sizeof(units) / sizeof(units[0]); |
| 479 | |
| 480 | int u = 0; |
| 481 | double size = static_cast<double>(bytes); |
| 482 | while (size >= 1024.0 && u < length) { |
| 483 | ++u; |
| 484 | size /= 1024.0; |
| 485 | } |
| 486 | |
| 487 | return QString::number(size, 'g', 4) + ' ' + units[u]; |
| 488 | } |
| 489 | |
| 490 | int |
| 491 | utils::levenshtein_distance(const std::string &s1, const std::string &s2) |
| 492 | { |
| 493 | const auto nlen = s1.size(); |
| 494 | const auto hlen = s2.size(); |
| 495 | |
| 496 | if (hlen == 0) |
| 497 | return -1; |
| 498 | if (nlen == 1) |
| 499 | return (int)s2.find(s1); |
| 500 | |
| 501 | std::vector<int> row1(hlen + 1, 0); |
| 502 | |
| 503 | for (size_t i = 0; i < nlen; ++i) { |
| 504 | std::vector<int> row2(1, (int)i + 1); |
| 505 | |
| 506 | for (size_t j = 0; j < hlen; ++j) { |
| 507 | const int cost = s1[i] != s2[j]; |
| 508 | row2.push_back(std::min(row1[j + 1] + 1, std::min(row2[j] + 1, row1[j] + cost))); |
| 509 | } |
| 510 | |
| 511 | row1.swap(row2); |
| 512 | } |
| 513 | |
| 514 | return *std::min_element(row1.begin(), row1.end()); |
| 515 | } |
| 516 | |
| 517 | QPixmap |
| 518 | utils::scaleImageToPixmap(const QImage &img, int size) |
| 519 | { |
| 520 | if (img.isNull()) |
| 521 | return QPixmap(); |
| 522 | |
| 523 | // Deprecated in 5.13: const double sz = |
| 524 | // std::ceil(QApplication::desktop()->screen()->devicePixelRatioF() * (double)size); |
| 525 | const int sz = static_cast<int>( |
| 526 | std::ceil(QGuiApplication::primaryScreen()->devicePixelRatio() * (double)size)); |
| 527 | return QPixmap::fromImage(img.scaled(sz, sz, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); |
| 528 | } |
| 529 | |
| 530 | QPixmap |
| 531 | utils::scaleDown(uint64_t maxWidth, uint64_t maxHeight, const QPixmap &source) |
| 532 | { |
| 533 | if (source.isNull()) |
| 534 | return QPixmap(); |
| 535 | |
| 536 | const double widthRatio = (double)maxWidth / (double)source.width(); |
| 537 | const double heightRatio = (double)maxHeight / (double)source.height(); |
| 538 | const double minAspectRatio = std::min(widthRatio, heightRatio); |
| 539 | |
| 540 | // Size of the output image. |
| 541 | int w, h = 0; |
| 542 | |
| 543 | if (minAspectRatio > 1) { |
| 544 | w = source.width(); |
| 545 | h = source.height(); |
| 546 | } else { |
| 547 | w = static_cast<int>(static_cast<double>(source.width()) * minAspectRatio); |
| 548 | h = static_cast<int>(static_cast<double>(source.height()) * minAspectRatio); |
| 549 | } |
| 550 | |
| 551 | return source.scaled(w, h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); |
| 552 | } |
| 553 | |
| 554 | QString |
| 555 | utils::mxcToHttp(const QUrl &url, const QString &server, int port) |
| 556 | { |
| 557 | auto mxcParts = mtx::client::utils::parse_mxc_url(url.toString().toStdString()); |
| 558 | |
| 559 | return QStringLiteral("https://%1:%2/_matrix/media/r0/download/%3/%4") |
| 560 | .arg(server) |
| 561 | .arg(port) |
| 562 | .arg(QString::fromStdString(mxcParts.server), QString::fromStdString(mxcParts.media_id)); |
| 563 | } |
| 564 | |
| 565 | QString |
| 566 | utils::humanReadableFingerprint(const std::string &ed25519_) |
| 567 | { |
| 568 | auto ed25519 = QString::fromStdString(ed25519_); |
| 569 | QString fingerprint; |
| 570 | for (int i = 0; i < ed25519.length(); i = i + 4) { |
| 571 | fingerprint.append(QStringView(ed25519).mid(i, 4)); |
| 572 | if (i > 0 && i == 20) |
| 573 | fingerprint.append('\n'); |
| 574 | else if (i < ed25519.length()) |
| 575 | fingerprint.append(' '); |
| 576 | } |
| 577 | return fingerprint; |
| 578 | } |
| 579 | |
| 580 | QString |
| 581 | utils::linkifyMessage(const QString &body) |
| 582 | { |
| 583 | // Convert to valid XML. |
| 584 | auto doc = body; |
| 585 | doc.replace(conf::strings::url_regex, conf::strings::url_html); |
| 586 | |
| 587 | static QRegularExpression matrixURIRegex( |
| 588 | QStringLiteral("\\b(?<![\"'])(?>(matrix:[\\S]{5,}))(?![\"'])\\b")); |
| 589 | doc.replace(matrixURIRegex, conf::strings::url_html); |
| 590 | |
| 591 | return doc; |
| 592 | } |
| 593 | |
| 594 | QString |
| 595 | utils::escapeMentionMarkdown(QString input) |
| 596 | { |
| 597 | input = input.toHtmlEscaped(); |
| 598 | |
| 599 | constexpr std::array<char, 10> markdownChars = { |
| 600 | '\\', |
| 601 | '`', |
| 602 | '*', |
| 603 | '_', |
| 604 | /*'{', '}',*/ '[', |
| 605 | ']', |
| 606 | '<', |
| 607 | '>', |
| 608 | /* '(', ')', '#', '-', '+', '.', '!', */ '~', |
| 609 | '|', |
| 610 | }; |
| 611 | |
| 612 | QByteArray replacement = "\\\\"; |
| 613 | |
| 614 | for (char c : markdownChars) { |
| 615 | replacement[1] = c; |
| 616 | input.replace(QChar::fromLatin1(c), QLatin1StringView(replacement)); |
| 617 | } |
| 618 | |
| 619 | return input; |
| 620 | } |
| 621 | |
| 622 | QString |
| 623 | utils::escapeBlacklistedHtml(const QString &rawStr) |
| 624 | { |
| 625 | static const std::set<QByteArray> allowedTags = { |
| 626 | "font", "/font", "del", "/del", "h1", "/h1", "h2", "/h2", |
| 627 | "h3", "/h3", "h4", "/h4", "h5", "/h5", "h6", "/h6", |
| 628 | "blockquote", "/blockquote", "p", "/p", "a", "/a", "ul", "/ul", |
| 629 | "ol", "/ol", "sup", "/sup", "sub", "/sub", "li", "/li", |
| 630 | "b", "/b", "i", "/i", "u", "/u", "strong", "/strong", |
| 631 | "em", "/em", "strike", "/strike", "code", "/code", "hr", "hr/", |
| 632 | "br", "br/", "div", "/div", "table", "/table", "thead", "/thead", |
| 633 | "tbody", "/tbody", "tr", "/tr", "th", "/th", "td", "/td", |
| 634 | "caption", "/caption", "pre", "/pre", "span", "/span", "img", "/img", |
| 635 | "details", "/details", "summary", "/summary"}; |
| 636 | constexpr static const std::array tagNameEnds = {' ', '>'}; |
| 637 | constexpr static const std::array attrNameEnds = {' ', '>', '=', '\t', '\r', '\n', '/', '\f'}; |
| 638 | constexpr static const std::array attrValueEnds = {' ', '\t', '\r', '\n', '\f', '>'}; |
| 639 | constexpr static const std::array spaceChars = {' ', '\t', '\r', '\n', '\f'}; |
| 640 | |
| 641 | QByteArray data = rawStr.toUtf8(); |
| 642 | QByteArray buffer; |
| 643 | const int length = data.size(); |
| 644 | buffer.reserve(length); |
| 645 | const auto end = data.cend(); |
| 646 | for (auto pos = data.cbegin(); pos < end;) { |
| 647 | auto tagStart = std::find(pos, end, '<'); |
| 648 | buffer.append(pos, static_cast<int>(tagStart - pos)); |
| 649 | if (tagStart == end) |
| 650 | break; |
| 651 | |
| 652 | const auto tagNameStart = tagStart + 1; |
| 653 | const auto tagNameEnd = |
| 654 | std::find_first_of(tagNameStart, end, tagNameEnds.begin(), tagNameEnds.end()); |
| 655 | |
| 656 | const auto tagName = |
| 657 | QByteArray(tagNameStart, static_cast<int>(tagNameEnd - tagNameStart)).toLower(); |
| 658 | |
| 659 | if (allowedTags.find(tagName) == allowedTags.end()) { |
| 660 | // not allowed -> escape |
| 661 | buffer.append("<"); |
| 662 | pos = tagNameStart; |
| 663 | continue; |
| 664 | } else { |
| 665 | buffer.append(tagStart, static_cast<int>(tagNameEnd - tagStart)); |
| 666 | |
| 667 | pos = tagNameEnd; |
| 668 | |
| 669 | if (tagNameEnd != end) { |
| 670 | auto attrStart = tagNameEnd; |
| 671 | auto attrsEnd = std::find(attrStart, end, '>'); |
| 672 | // we don't want to consume the slash of self closing tags as part of an attribute. |
| 673 | // However, obviously we don't want to move backwards, if there are no attributes. |
| 674 | if (*(attrsEnd - 1) == '/' && attrStart < attrsEnd) |
| 675 | attrsEnd -= 1; |
| 676 | |
| 677 | pos = attrsEnd; |
| 678 | |
| 679 | auto consumeSpaces = [attrsEnd](auto p) { |
| 680 | while (p < attrsEnd && |
| 681 | std::find(spaceChars.begin(), spaceChars.end(), *p) != spaceChars.end()) |
| 682 | p++; |
| 683 | return p; |
| 684 | }; |
| 685 | |
| 686 | attrStart = consumeSpaces(attrStart); |
| 687 | |
| 688 | while (attrStart < attrsEnd) { |
| 689 | auto attrEnd = std::find_first_of( |
| 690 | attrStart, attrsEnd, attrNameEnds.begin(), attrNameEnds.end()); |
| 691 | |
| 692 | auto attrName = |
| 693 | QByteArray(attrStart, static_cast<int>(attrEnd - attrStart)).toLower(); |
| 694 | |
| 695 | auto sanitizeValue = [&attrName, tagName](QByteArray val) { |
| 696 | if (tagName == QByteArrayLiteral("del") || |
| 697 | (attrName == QByteArrayLiteral("src") && !val.startsWith("mxc://"))) |
| 698 | return QByteArray(); |
| 699 | else |
| 700 | return val; |
| 701 | }; |
| 702 | |
| 703 | attrStart = consumeSpaces(attrEnd); |
| 704 | |
| 705 | if (attrName.isEmpty()) { |
| 706 | buffer.append(QUrl::toPercentEncoding(QString(QByteArray(attrStart, 1)))); |
| 707 | attrStart++; |
| 708 | continue; |
| 709 | } else if (attrStart < attrsEnd) { |
| 710 | if (*attrStart == '=') { |
| 711 | attrStart = consumeSpaces(attrStart + 1); |
| 712 | |
| 713 | if (attrStart < attrsEnd) { |
| 714 | // we fall through here if the value is empty to transform attr="" |
| 715 | // into attr, because otherwise we can't style it |
| 716 | if (*attrStart == '"') { |
| 717 | attrStart += 1; |
| 718 | auto valueEnd = std::find(attrStart, attrsEnd, '"'); |
| 719 | if (valueEnd == attrsEnd) |
| 720 | break; |
| 721 | |
| 722 | auto val = sanitizeValue(QByteArray( |
| 723 | attrStart, static_cast<int>(valueEnd - attrStart))); |
| 724 | attrStart = consumeSpaces(valueEnd + 1); |
| 725 | if (!val.isEmpty()) { |
| 726 | buffer.append(' '); |
| 727 | buffer.append(attrName); |
| 728 | buffer.append("=\""); |
| 729 | buffer.append(val); |
| 730 | buffer.append('"'); |
| 731 | continue; |
| 732 | } |
| 733 | } else if (*attrStart == '\'') { |
| 734 | attrStart += 1; |
| 735 | auto valueEnd = std::find(attrStart, attrsEnd, '\''); |
| 736 | if (valueEnd == attrsEnd) |
| 737 | break; |
| 738 | |
| 739 | auto val = sanitizeValue(QByteArray( |
| 740 | attrStart, static_cast<int>(valueEnd - attrStart))); |
| 741 | attrStart = consumeSpaces(valueEnd + 1); |
| 742 | if (!val.isEmpty()) { |
| 743 | buffer.append(' '); |
| 744 | buffer.append(attrName); |
| 745 | buffer.append("=\'"); |
| 746 | buffer.append(val); |
| 747 | buffer.append('\''); |
| 748 | continue; |
| 749 | } |
| 750 | } else { |
| 751 | auto valueEnd = std::find_first_of(attrStart, |
| 752 | attrsEnd, |
| 753 | attrValueEnds.begin(), |
| 754 | attrValueEnds.end()); |
| 755 | auto val = sanitizeValue(QByteArray( |
| 756 | attrStart, static_cast<int>(valueEnd - attrStart))); |
| 757 | attrStart = consumeSpaces(valueEnd); |
| 758 | |
| 759 | if (val.contains('"')) |
| 760 | continue; |
| 761 | |
| 762 | buffer.append(' '); |
| 763 | buffer.append(attrName); |
| 764 | buffer.append("=\""); |
| 765 | buffer.append(val); |
| 766 | buffer.append('"'); |
| 767 | continue; |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | // We don't really want tags on del tags and they make replacement in the |
| 774 | // frontend more expansive |
| 775 | if (tagName != QByteArrayLiteral("del")) { |
| 776 | buffer.append(' '); |
| 777 | buffer.append(attrName); |
| 778 | } |
| 779 | } |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | return QString::fromUtf8(buffer); |
| 785 | } |
| 786 | |
| 787 | static void |
| 788 | rainbowify(cmark_node *node) |
| 789 | { |
| 790 | // create iterator over node |
| 791 | cmark_iter *iter = cmark_iter_new(node); |
| 792 | |
| 793 | // First loop to get total text length |
| 794 | int textLen = 0; |
| 795 | while (cmark_iter_next(iter) != CMARK_EVENT_DONE) { |
| 796 | cmark_node *cur = cmark_iter_get_node(iter); |
| 797 | // only text nodes (no code or semilar) |
| 798 | if (cmark_node_get_type(cur) != CMARK_NODE_TEXT) |
| 799 | continue; |
| 800 | // count up by length of current node's text |
| 801 | QTextBoundaryFinder tbf(QTextBoundaryFinder::BoundaryType::Grapheme, |
| 802 | QString(cmark_node_get_literal(cur))); |
| 803 | while (tbf.toNextBoundary() != -1) |
| 804 | textLen++; |
| 805 | } |
| 806 | |
| 807 | // create new iter to start over |
| 808 | cmark_iter_free(iter); |
| 809 | iter = cmark_iter_new(node); |
| 810 | |
| 811 | // Second loop to rainbowify |
| 812 | int charIdx = 0; |
| 813 | while (cmark_iter_next(iter) != CMARK_EVENT_DONE) { |
| 814 | cmark_node *cur = cmark_iter_get_node(iter); |
| 815 | // only text nodes (no code or similar) |
| 816 | if (cmark_node_get_type(cur) != CMARK_NODE_TEXT) |
| 817 | continue; |
| 818 | |
| 819 | // get text in current node |
| 820 | QString nodeText(cmark_node_get_literal(cur)); |
| 821 | // create buffer to append rainbow text to |
| 822 | QString buf; |
| 823 | int boundaryStart = 0; |
| 824 | int boundaryEnd = 0; |
| 825 | // use QTextBoundaryFinder to iterate over graphemes |
| 826 | QTextBoundaryFinder tbf(QTextBoundaryFinder::BoundaryType::Grapheme, nodeText); |
| 827 | while ((boundaryEnd = tbf.toNextBoundary()) != -1) { |
| 828 | charIdx++; |
| 829 | // Split text to get current char |
| 830 | auto curChar = QStringView(nodeText).mid(boundaryStart, boundaryEnd - boundaryStart); |
| 831 | boundaryStart = boundaryEnd; |
| 832 | // Don't rainbowify whitespaces |
| 833 | if (curChar.trimmed().isEmpty() || utils::codepointIsEmoji(curChar.toUcs4().at(0))) { |
| 834 | buf.append(curChar); |
| 835 | continue; |
| 836 | } |
| 837 | |
| 838 | // get correct color for char index |
| 839 | // Use colors as described here: |
| 840 | // https://shark.comfsm.fm/~dleeling/cis/hsl_rainbow.html |
| 841 | auto color = QColor::fromHslF( |
| 842 | static_cast<float>((charIdx - 1.0) / textLen * (5. / 6.)), 0.9f, 0.5f); |
| 843 | // format color for HTML |
| 844 | auto colorString = color.name(QColor::NameFormat::HexRgb); |
| 845 | // create HTML element for current char |
| 846 | auto curCharColored = |
| 847 | QStringLiteral("<font color=\"%0\">%1</font>").arg(colorString).arg(curChar); |
| 848 | // append colored HTML element to buffer |
| 849 | buf.append(curCharColored); |
| 850 | } |
| 851 | |
| 852 | // create HTML_INLINE node to prevent HTML from being escaped |
| 853 | auto htmlNode = cmark_node_new(CMARK_NODE_HTML_INLINE); |
| 854 | // set content of HTML node to buffer contents |
| 855 | cmark_node_set_literal(htmlNode, buf.toUtf8().data()); |
| 856 | // replace current node with HTML node |
| 857 | cmark_node_replace(cur, htmlNode); |
| 858 | // free memory of old node |
| 859 | cmark_node_free(cur); |
| 860 | } |
| 861 | |
| 862 | cmark_iter_free(iter); |
| 863 | } |
| 864 | |
| 865 | static std::string |
| 866 | extract_spoiler_warning(std::string &inside_spoiler) |
| 867 | { |
| 868 | std::string spoiler_text; |
| 869 | if (auto spoilerTextEnd = inside_spoiler.find("|"); spoilerTextEnd != std::string::npos) { |
| 870 | spoiler_text = inside_spoiler.substr(0, spoilerTextEnd); |
| 871 | inside_spoiler = inside_spoiler.substr(spoilerTextEnd + 1); |
| 872 | } |
| 873 | return QString::fromStdString(spoiler_text).replace('"', """).toStdString(); |
| 874 | } |
| 875 | |
| 876 | // TODO(Nico): Add tests :D |
| 877 | static void |
| 878 | process_spoilers(cmark_node *node) |
| 879 | { |
| 880 | auto iter = cmark_iter_new(node); |
| 881 | |
| 882 | while (cmark_iter_next(iter) != CMARK_EVENT_DONE) { |
| 883 | cmark_node *cur = cmark_iter_get_node(iter); |
| 884 | |
| 885 | // only text nodes (no code or similar) |
| 886 | if (cmark_node_get_type(cur) != CMARK_NODE_TEXT) { |
| 887 | continue; |
| 888 | } |
| 889 | |
| 890 | std::string_view content = cmark_node_get_literal(cur); |
| 891 | |
| 892 | if (auto posStart = content.find("||"); posStart != std::string::npos) { |
| 893 | // we have the start of the spoiler |
| 894 | if (auto posEnd = content.find("||", posStart + 2); posEnd != std::string::npos) { |
| 895 | // we have the end of the spoiler in the same node |
| 896 | |
| 897 | std::string before_spoiler = std::string(content.substr(0, posStart)); |
| 898 | std::string inside_spoiler = |
| 899 | std::string(content.substr(posStart + 2, posEnd - 2 - posStart)); |
| 900 | std::string after_spoiler = std::string(content.substr(posEnd + 2)); |
| 901 | |
| 902 | std::string spoiler_text = extract_spoiler_warning(inside_spoiler); |
| 903 | |
| 904 | // create the new nodes |
| 905 | auto before_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 906 | cmark_node_set_literal(before_node, before_spoiler.c_str()); |
| 907 | auto after_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 908 | cmark_node_set_literal(after_node, after_spoiler.c_str()); |
| 909 | |
| 910 | auto block = cmark_node_new(cmark_node_type::CMARK_NODE_CUSTOM_INLINE); |
| 911 | cmark_node_set_on_enter( |
| 912 | block, ("<span data-mx-spoiler=\"" + spoiler_text + "\">").c_str()); |
| 913 | cmark_node_set_on_exit(block, "</span>"); |
| 914 | auto child_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 915 | cmark_node_set_literal(child_node, inside_spoiler.c_str()); |
| 916 | cmark_node_append_child(block, child_node); |
| 917 | |
| 918 | // insert the new nodes into the tree |
| 919 | cmark_node_replace(cur, block); |
| 920 | cmark_node_insert_before(block, before_node); |
| 921 | cmark_node_insert_after(block, after_node); |
| 922 | |
| 923 | // cleanup the replaced node |
| 924 | cmark_node_free(cur); |
| 925 | |
| 926 | // fixup the iterator |
| 927 | cmark_iter_reset(iter, block, CMARK_EVENT_EXIT); |
| 928 | |
| 929 | } else { |
| 930 | // no end found, but lets try sibling nodes |
| 931 | for (auto next = cmark_node_next(cur); next != nullptr; |
| 932 | next = cmark_node_next(next)) { |
| 933 | // only text nodes again |
| 934 | if (cmark_node_get_type(next) != CMARK_NODE_TEXT) |
| 935 | continue; |
| 936 | |
| 937 | std::string_view next_content = cmark_node_get_literal(next); |
| 938 | if (auto posEndNext = next_content.find("||"); |
| 939 | posEndNext != std::string_view::npos) { |
| 940 | // We found the end of the spoiler |
| 941 | std::string before_spoiler = std::string(content.substr(0, posStart)); |
| 942 | std::string after_spoiler = |
| 943 | std::string(next_content.substr(posEndNext + 2)); |
| 944 | |
| 945 | std::string inside_spoiler_start = |
| 946 | std::string(content.substr(posStart + 2)); |
| 947 | std::string inside_spoiler_end = |
| 948 | std::string(next_content.substr(0, posEndNext)); |
| 949 | |
| 950 | std::string spoiler_text = extract_spoiler_warning(inside_spoiler_start); |
| 951 | |
| 952 | // save all the nodes inside the spoiler for later |
| 953 | std::vector<cmark_node *> child_nodes; |
| 954 | for (auto kid = cmark_node_next(cur); kid != nullptr && kid != next; |
| 955 | kid = cmark_node_next(kid)) { |
| 956 | child_nodes.push_back(kid); |
| 957 | } |
| 958 | |
| 959 | // create the new nodes |
| 960 | auto before_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 961 | cmark_node_set_literal(before_node, before_spoiler.c_str()); |
| 962 | auto after_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 963 | cmark_node_set_literal(after_node, after_spoiler.c_str()); |
| 964 | |
| 965 | auto block = cmark_node_new(cmark_node_type::CMARK_NODE_CUSTOM_INLINE); |
| 966 | cmark_node_set_on_enter( |
| 967 | block, ("<span data-mx-spoiler=\"" + spoiler_text + "\">").c_str()); |
| 968 | cmark_node_set_on_exit(block, "</span>"); |
| 969 | |
| 970 | // create the content inside the spoiler by adding the old text at the start |
| 971 | // and the end as well as all the existing children |
| 972 | auto child_node_start = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 973 | cmark_node_set_literal(child_node_start, inside_spoiler_start.c_str()); |
| 974 | cmark_node_append_child(block, child_node_start); |
| 975 | for (auto &child : child_nodes) |
| 976 | cmark_node_append_child(block, child); |
| 977 | auto child_node_end = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 978 | cmark_node_set_literal(child_node_end, inside_spoiler_end.c_str()); |
| 979 | cmark_node_append_child(block, child_node_end); |
| 980 | |
| 981 | // insert the new nodes into the tree |
| 982 | cmark_node_replace(cur, block); |
| 983 | cmark_node_insert_before(block, before_node); |
| 984 | cmark_node_insert_after(block, after_node); |
| 985 | |
| 986 | // cleanup removed nodes |
| 987 | cmark_node_free(cur); |
| 988 | cmark_node_free(next); |
| 989 | |
| 990 | // fixup the iterator |
| 991 | cmark_iter_reset(iter, block, CMARK_EVENT_EXIT); |
| 992 | |
| 993 | break; |
| 994 | } |
| 995 | } |
| 996 | } |
| 997 | } |
| 998 | } |
| 999 | |
| 1000 | cmark_iter_free(iter); |
| 1001 | } |
| 1002 | |
| 1003 | static void |
| 1004 | process_strikethrough(cmark_node *node) |
| 1005 | { |
| 1006 | auto iter = cmark_iter_new(node); |
| 1007 | |
| 1008 | while (cmark_iter_next(iter) != CMARK_EVENT_DONE) { |
| 1009 | cmark_node *cur = cmark_iter_get_node(iter); |
| 1010 | |
| 1011 | // only text nodes (no code or similar) |
| 1012 | if (cmark_node_get_type(cur) != CMARK_NODE_TEXT) { |
| 1013 | continue; |
| 1014 | } |
| 1015 | |
| 1016 | std::string_view content = cmark_node_get_literal(cur); |
| 1017 | |
| 1018 | if (auto posStart = content.find("~~"); posStart != std::string::npos) { |
| 1019 | // we have the start of the strikethrough |
| 1020 | if (auto posEnd = content.find("~~", posStart + 2); posEnd != std::string::npos) { |
| 1021 | // we have the end of the strikethrough in the same node |
| 1022 | |
| 1023 | std::string before_strike = std::string(content.substr(0, posStart)); |
| 1024 | std::string inside_strike = |
| 1025 | std::string(content.substr(posStart + 2, posEnd - 2 - posStart)); |
| 1026 | std::string after_strike = std::string(content.substr(posEnd + 2)); |
| 1027 | |
| 1028 | // create the new nodes |
| 1029 | auto before_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1030 | cmark_node_set_literal(before_node, before_strike.c_str()); |
| 1031 | auto after_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1032 | cmark_node_set_literal(after_node, after_strike.c_str()); |
| 1033 | |
| 1034 | auto block = cmark_node_new(cmark_node_type::CMARK_NODE_CUSTOM_INLINE); |
| 1035 | cmark_node_set_on_enter(block, "<del>"); |
| 1036 | cmark_node_set_on_exit(block, "</del>"); |
| 1037 | auto child_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1038 | cmark_node_set_literal(child_node, inside_strike.c_str()); |
| 1039 | cmark_node_append_child(block, child_node); |
| 1040 | |
| 1041 | // insert the new nodes into the tree |
| 1042 | cmark_node_replace(cur, block); |
| 1043 | cmark_node_insert_before(block, before_node); |
| 1044 | cmark_node_insert_after(block, after_node); |
| 1045 | |
| 1046 | // cleanup the replaced node |
| 1047 | cmark_node_free(cur); |
| 1048 | |
| 1049 | // fixup the iterator |
| 1050 | cmark_iter_reset(iter, block, CMARK_EVENT_EXIT); |
| 1051 | |
| 1052 | } else { |
| 1053 | // no end found, but lets try sibling nodes |
| 1054 | for (auto next = cmark_node_next(cur); next != nullptr; |
| 1055 | next = cmark_node_next(next)) { |
| 1056 | // only text nodes again |
| 1057 | if (cmark_node_get_type(next) != CMARK_NODE_TEXT) |
| 1058 | continue; |
| 1059 | |
| 1060 | std::string_view next_content = cmark_node_get_literal(next); |
| 1061 | if (auto posEndNext = next_content.find("~~"); |
| 1062 | posEndNext != std::string_view::npos) { |
| 1063 | // We found the end of the strikethrough |
| 1064 | std::string before_strike = std::string(content.substr(0, posStart)); |
| 1065 | std::string after_strike = std::string(next_content.substr(posEndNext + 2)); |
| 1066 | |
| 1067 | std::string inside_strike_start = std::string(content.substr(posStart + 2)); |
| 1068 | std::string inside_strike_end = |
| 1069 | std::string(next_content.substr(0, posEndNext)); |
| 1070 | |
| 1071 | // save all the nodes inside the strikethrough for later |
| 1072 | std::vector<cmark_node *> child_nodes; |
| 1073 | for (auto kid = cmark_node_next(cur); kid != nullptr && kid != next; |
| 1074 | kid = cmark_node_next(kid)) { |
| 1075 | child_nodes.push_back(kid); |
| 1076 | } |
| 1077 | |
| 1078 | // create the new nodes |
| 1079 | auto before_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1080 | cmark_node_set_literal(before_node, before_strike.c_str()); |
| 1081 | auto after_node = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1082 | cmark_node_set_literal(after_node, after_strike.c_str()); |
| 1083 | |
| 1084 | auto block = cmark_node_new(cmark_node_type::CMARK_NODE_CUSTOM_INLINE); |
| 1085 | cmark_node_set_on_enter(block, "<del>"); |
| 1086 | cmark_node_set_on_exit(block, "</del>"); |
| 1087 | |
| 1088 | // create the content inside the strikethrough by adding the old text at the |
| 1089 | // start and the end as well as all the existing children |
| 1090 | auto child_node_start = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1091 | cmark_node_set_literal(child_node_start, inside_strike_start.c_str()); |
| 1092 | cmark_node_append_child(block, child_node_start); |
| 1093 | for (auto &child : child_nodes) |
| 1094 | cmark_node_append_child(block, child); |
| 1095 | auto child_node_end = cmark_node_new(cmark_node_type::CMARK_NODE_TEXT); |
| 1096 | cmark_node_set_literal(child_node_end, inside_strike_end.c_str()); |
| 1097 | cmark_node_append_child(block, child_node_end); |
| 1098 | |
| 1099 | // insert the new nodes into the tree |
| 1100 | cmark_node_replace(cur, block); |
| 1101 | cmark_node_insert_before(block, before_node); |
| 1102 | cmark_node_insert_after(block, after_node); |
| 1103 | |
| 1104 | // cleanup removed nodes |
| 1105 | cmark_node_free(cur); |
| 1106 | cmark_node_free(next); |
| 1107 | |
| 1108 | // fixup the iterator |
| 1109 | cmark_iter_reset(iter, block, CMARK_EVENT_EXIT); |
| 1110 | |
| 1111 | break; |
| 1112 | } |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | cmark_iter_free(iter); |
| 1119 | } |
| 1120 | QString |
| 1121 | utils::markdownToHtml(const QString &text, bool rainbowify_, bool noExtensions) |
| 1122 | { |
| 1123 | const auto str = text.toUtf8(); |
| 1124 | cmark_node *const node = cmark_parse_document(str.constData(), str.size(), CMARK_OPT_UNSAFE); |
| 1125 | |
| 1126 | if (!noExtensions) { |
| 1127 | process_strikethrough(node); |
| 1128 | process_spoilers(node); |
| 1129 | |
| 1130 | if (rainbowify_) { |
| 1131 | rainbowify(node); |
| 1132 | } |
| 1133 | } |
| 1134 | |
| 1135 | const char *tmp_buf = cmark_render_html( |
| 1136 | node, |
| 1137 | // by default make single linebreaks <br> tags |
| 1138 | noExtensions ? CMARK_OPT_UNSAFE : (CMARK_OPT_UNSAFE | CMARK_OPT_HARDBREAKS)); |
| 1139 | // Copy the null terminated output buffer. |
| 1140 | std::string html(tmp_buf); |
| 1141 | |
| 1142 | // The buffer is no longer needed. |
| 1143 | free((char *)tmp_buf); |
| 1144 | cmark_node_free(node); |
| 1145 | |
| 1146 | auto result = escapeBlacklistedHtml(QString::fromStdString(html)).trimmed(); |
| 1147 | |
| 1148 | if (!noExtensions) { |
| 1149 | result = linkifyMessage(std::move(result)).trimmed(); |
| 1150 | } |
| 1151 | |
| 1152 | if (result.count(QStringLiteral("<p>")) == 1 && result.startsWith(QLatin1String("<p>")) && |
| 1153 | result.endsWith(QLatin1String("</p>"))) { |
| 1154 | result = result.mid(3, result.size() - 3 - 4); |
| 1155 | } |
| 1156 | |
| 1157 | return result; |
| 1158 | } |
| 1159 | |
| 1160 | QString |
| 1161 | getQuoteBody(const RelatedInfo &related) |
| 1162 | { |
| 1163 | using MsgType = mtx::events::MessageType; |
| 1164 | |
| 1165 | switch (related.type) { |
| 1166 | case MsgType::File: { |
| 1167 | return QStringLiteral("sent a file."); |
| 1168 | } |
| 1169 | case MsgType::Image: { |
| 1170 | return QStringLiteral("sent an image."); |
| 1171 | } |
| 1172 | case MsgType::Audio: { |
| 1173 | return QStringLiteral("sent an audio file."); |
| 1174 | } |
| 1175 | case MsgType::Video: { |
| 1176 | return QStringLiteral("sent a video"); |
| 1177 | } |
| 1178 | default: { |
| 1179 | return related.quoted_body; |
| 1180 | } |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | QString |
| 1185 | utils::linkColor() |
| 1186 | { |
| 1187 | const auto theme = UserSettings::instance()->theme(); |
| 1188 | |
| 1189 | if (theme == QLatin1String("light")) { |
| 1190 | return QStringLiteral("#0077b5"); |
| 1191 | } else if (theme == QLatin1String("dark")) { |
| 1192 | return QStringLiteral("#38A3D8"); |
| 1193 | } else { |
| 1194 | return QPalette().color(QPalette::Link).name(); |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | uint32_t |
| 1199 | utils::hashQString(const QString &input) |
| 1200 | { |
| 1201 | auto h = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha1); |
| 1202 | |
| 1203 | return (static_cast<uint32_t>(h[0]) << 24) ^ (static_cast<uint32_t>(h[1]) << 16) ^ |
| 1204 | (static_cast<uint32_t>(h[2]) << 8) ^ static_cast<uint32_t>(h[3]); |
| 1205 | } |
| 1206 | |
| 1207 | QColor |
| 1208 | utils::generateContrastingHexColor(const QString &input, const QColor &backgroundCol) |
| 1209 | { |
| 1210 | const qreal backgroundLum = luminance(backgroundCol); |
| 1211 | |
| 1212 | // Create a color for the input |
| 1213 | auto hash = hashQString(input); |
| 1214 | // create a hue value based on the hash of the input. |
| 1215 | // Adapted to make Nico blue |
| 1216 | auto userHue = static_cast<double>(hash - static_cast<uint32_t>(0x60'00'00'00)) / |
| 1217 | std::numeric_limits<uint32_t>::max() * 360.; |
| 1218 | // start with moderate saturation and lightness values. |
| 1219 | auto sat = 230.; |
| 1220 | auto lightness = 125.; |
| 1221 | |
| 1222 | // converting to a QColor makes the luminance calc easier. |
| 1223 | QColor inputColor = QColor::fromHsl( |
| 1224 | static_cast<int>(userHue), static_cast<int>(sat), static_cast<int>(lightness)); |
| 1225 | |
| 1226 | // calculate the initial luminance and contrast of the |
| 1227 | // generated color. It's possible that no additional |
| 1228 | // work will be necessary. |
| 1229 | auto lum = luminance(inputColor); |
| 1230 | auto contrast = computeContrast(lum, backgroundLum); |
| 1231 | |
| 1232 | // If the contrast doesn't meet our criteria, |
| 1233 | // try again and again until they do by modifying first |
| 1234 | // the lightness and then the saturation of the color. |
| 1235 | int iterationCount = 9; |
| 1236 | while (contrast < 4.5) { |
| 1237 | // if our lightness is at it's bounds, try changing |
| 1238 | // saturation instead. |
| 1239 | if (lightness >= 242 || lightness <= 13) { |
| 1240 | qreal newSat = qBound(26.0, sat * 1.25, 242.0); |
| 1241 | |
| 1242 | inputColor.setHsl(static_cast<int>(userHue), |
| 1243 | static_cast<int>(qFloor(newSat)), |
| 1244 | static_cast<int>(lightness)); |
| 1245 | auto tmpLum = luminance(inputColor); |
| 1246 | auto higherContrast = computeContrast(tmpLum, backgroundLum); |
| 1247 | if (higherContrast > contrast) { |
| 1248 | contrast = higherContrast; |
| 1249 | sat = newSat; |
| 1250 | } else { |
| 1251 | newSat = qBound(26.0, sat / 1.25, 242.0); |
| 1252 | inputColor.setHsl(static_cast<int>(userHue), |
| 1253 | static_cast<int>(qFloor(newSat)), |
| 1254 | static_cast<int>(lightness)); |
| 1255 | tmpLum = luminance(inputColor); |
| 1256 | auto lowerContrast = computeContrast(tmpLum, backgroundLum); |
| 1257 | if (lowerContrast > contrast) { |
| 1258 | contrast = lowerContrast; |
| 1259 | sat = newSat; |
| 1260 | } |
| 1261 | } |
| 1262 | } else { |
| 1263 | qreal newLightness = qBound(13.0, lightness * 1.25, 242.0); |
| 1264 | |
| 1265 | inputColor.setHsl(static_cast<int>(userHue), |
| 1266 | static_cast<int>(sat), |
| 1267 | static_cast<int>(qFloor(newLightness))); |
| 1268 | |
| 1269 | auto tmpLum = luminance(inputColor); |
| 1270 | auto higherContrast = computeContrast(tmpLum, backgroundLum); |
| 1271 | |
| 1272 | // Check to make sure we have actually improved contrast |
| 1273 | if (higherContrast > contrast) { |
| 1274 | contrast = higherContrast; |
| 1275 | lightness = newLightness; |
| 1276 | // otherwise, try going the other way instead. |
| 1277 | } else { |
| 1278 | newLightness = qBound(13.0, lightness / 1.25, 242.0); |
| 1279 | inputColor.setHsl(static_cast<int>(userHue), |
| 1280 | static_cast<int>(sat), |
| 1281 | static_cast<int>(qFloor(newLightness))); |
| 1282 | tmpLum = luminance(inputColor); |
| 1283 | auto lowerContrast = computeContrast(tmpLum, backgroundLum); |
| 1284 | if (lowerContrast > contrast) { |
| 1285 | contrast = lowerContrast; |
| 1286 | lightness = newLightness; |
| 1287 | } |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | // don't loop forever, just give up at some point! |
| 1292 | // Someone smart may find a better solution |
| 1293 | if (--iterationCount < 0) |
| 1294 | break; |
| 1295 | } |
| 1296 | |
| 1297 | // get the hex value of the generated color. |
| 1298 | auto colorHex = inputColor.name(); |
| 1299 | |
| 1300 | return colorHex; |
| 1301 | } |
| 1302 | |
| 1303 | qreal |
| 1304 | utils::computeContrast(const qreal &one, const qreal &two) |
| 1305 | { |
| 1306 | auto ratio = (one + 0.05) / (two + 0.05); |
| 1307 | |
| 1308 | if (two > one) { |
| 1309 | ratio = 1 / ratio; |
| 1310 | } |
| 1311 | |
| 1312 | return ratio; |
| 1313 | } |
| 1314 | |
| 1315 | qreal |
| 1316 | utils::luminance(const QColor &col) |
| 1317 | { |
| 1318 | int colRgb[3] = {col.red(), col.green(), col.blue()}; |
| 1319 | qreal lumRgb[3]; |
| 1320 | |
| 1321 | for (int i = 0; i < 3; i++) { |
| 1322 | qreal v = colRgb[i] / 255.0; |
| 1323 | lumRgb[i] = v <= 0.03928 ? v / 12.92 : qPow((v + 0.055) / 1.055, 2.4); |
| 1324 | } |
| 1325 | |
| 1326 | auto lum = lumRgb[0] * 0.2126 + lumRgb[1] * 0.7152 + lumRgb[2] * 0.0722; |
| 1327 | |
| 1328 | return lum; |
| 1329 | } |
| 1330 | |
| 1331 | void |
| 1332 | utils::centerWidget(QWidget *widget, QWindow *parent) |
| 1333 | { |
| 1334 | if (parent) { |
| 1335 | widget->window()->windowHandle()->setTransientParent(parent); |
| 1336 | return; |
| 1337 | } |
| 1338 | |
| 1339 | auto findCenter = [childRect = widget->rect()](QRect hostRect) -> QPoint { |
| 1340 | return QPoint(static_cast<int>(hostRect.center().x() - (childRect.width() * 0.5)), |
| 1341 | static_cast<int>(hostRect.center().y() - (childRect.height() * 0.5))); |
| 1342 | }; |
| 1343 | widget->move(findCenter(QGuiApplication::primaryScreen()->geometry())); |
| 1344 | } |
| 1345 | |
| 1346 | void |
| 1347 | utils::restoreCombobox(QComboBox *combo, const QString &value) |
| 1348 | { |
| 1349 | for (auto i = 0; i < combo->count(); ++i) { |
| 1350 | if (value == combo->itemText(i)) { |
| 1351 | combo->setCurrentIndex(i); |
| 1352 | break; |
| 1353 | } |
| 1354 | } |
| 1355 | } |
| 1356 | |
| 1357 | QImage |
| 1358 | utils::readImageFromFile(const QString &filename) |
| 1359 | { |
| 1360 | QImageReader reader(filename); |
| 1361 | reader.setAutoTransform(true); |
| 1362 | return reader.read(); |
| 1363 | } |
| 1364 | QImage |
| 1365 | utils::readImage(const QByteArray &data) |
| 1366 | { |
| 1367 | QBuffer buf; |
| 1368 | buf.setData(data); |
| 1369 | QImageReader reader(&buf); |
| 1370 | reader.setAutoTransform(true); |
| 1371 | return reader.read(); |
| 1372 | } |
| 1373 | |
| 1374 | bool |
| 1375 | utils::isReply(const mtx::events::collections::TimelineEvents &e) |
| 1376 | { |
| 1377 | return mtx::accessors::relations(e).reply_to().has_value(); |
| 1378 | } |
| 1379 | |
| 1380 | void |
| 1381 | utils::removeDirectFromRoom(QString roomid) |
| 1382 | { |
| 1383 | http::client()->get_account_data<mtx::events::account_data::Direct>( |
| 1384 | [roomid](mtx::events::account_data::Direct ev, mtx::http::RequestErr e) { |
| 1385 | if (e && e->status_code == 404) |
| 1386 | ev = {}; |
| 1387 | else if (e) { |
| 1388 | nhlog::net()->error("Failed to retrieve m.direct: {}", *e); |
| 1389 | return; |
| 1390 | } |
| 1391 | |
| 1392 | auto r = roomid.toStdString(); |
| 1393 | |
| 1394 | for (auto it = ev.user_to_rooms.begin(); it != ev.user_to_rooms.end();) { |
| 1395 | for (auto rit = it->second.begin(); rit != it->second.end();) { |
| 1396 | if (r == *rit) |
| 1397 | rit = it->second.erase(rit); |
| 1398 | else |
| 1399 | ++rit; |
| 1400 | } |
| 1401 | |
| 1402 | if (it->second.empty()) |
| 1403 | it = ev.user_to_rooms.erase(it); |
| 1404 | else |
| 1405 | ++it; |
| 1406 | } |
| 1407 | |
| 1408 | http::client()->put_account_data(ev, [r](mtx::http::RequestErr e) { |
| 1409 | if (e) |
| 1410 | nhlog::net()->error("Failed to update m.direct: {}", *e); |
| 1411 | }); |
| 1412 | }); |
| 1413 | } |
| 1414 | void |
| 1415 | utils::markRoomAsDirect(QString roomid, std::vector<RoomMember> members) |
| 1416 | { |
| 1417 | http::client()->get_account_data<mtx::events::account_data::Direct>( |
| 1418 | [roomid, members](mtx::events::account_data::Direct ev, mtx::http::RequestErr e) { |
| 1419 | if (e && e->status_code == 404) |
| 1420 | ev = {}; |
| 1421 | else if (e) { |
| 1422 | nhlog::net()->error("Failed to retrieve m.direct: {}", *e); |
| 1423 | return; |
| 1424 | } |
| 1425 | |
| 1426 | auto local = utils::localUser(); |
| 1427 | auto r = roomid.toStdString(); |
| 1428 | |
| 1429 | for (const auto &m : members) { |
| 1430 | if (m.user_id != local) { |
| 1431 | ev.user_to_rooms[m.user_id.toStdString()].push_back(r); |
| 1432 | } |
| 1433 | } |
| 1434 | |
| 1435 | http::client()->put_account_data(ev, [r](mtx::http::RequestErr e) { |
| 1436 | if (e) |
| 1437 | nhlog::net()->error("Failed to update m.direct: {}", *e); |
| 1438 | }); |
| 1439 | }); |
| 1440 | } |
| 1441 | |
| 1442 | std::vector<std::string> |
| 1443 | utils::roomVias(const std::string &roomid) |
| 1444 | { |
| 1445 | std::vector<std::string> vias; |
| 1446 | |
| 1447 | // for joined rooms |
| 1448 | { |
| 1449 | // see https://spec.matrix.org/v1.6/appendices/#routing for the algorithm |
| 1450 | |
| 1451 | auto members = cache::roomMembers(roomid); |
| 1452 | if (!members.empty()) { |
| 1453 | auto powerlevels = |
| 1454 | cache::client()->getStateEvent<mtx::events::state::PowerLevels>(roomid).value_or( |
| 1455 | mtx::events::StateEvent<mtx::events::state::PowerLevels>{}); |
| 1456 | auto acls = cache::client()->getStateEvent<mtx::events::state::ServerAcl>(roomid); |
| 1457 | |
| 1458 | std::vector<QRegularExpression> allowedServers; |
| 1459 | std::vector<QRegularExpression> deniedServers; |
| 1460 | |
| 1461 | if (acls) { |
| 1462 | auto globToRegexp = [](const std::string &globExp) { |
| 1463 | auto rawReg = QRegularExpression::escape(QString::fromStdString(globExp)) |
| 1464 | .replace("\\*", ".*") |
| 1465 | .replace("\\?", "."); |
| 1466 | return QRegularExpression(QRegularExpression::anchoredPattern(rawReg), |
| 1467 | QRegularExpression::DotMatchesEverythingOption | |
| 1468 | QRegularExpression::DontCaptureOption); |
| 1469 | }; |
| 1470 | |
| 1471 | allowedServers.reserve(acls->content.allow.size()); |
| 1472 | for (const auto &s : acls->content.allow) |
| 1473 | allowedServers.push_back(globToRegexp(s)); |
| 1474 | deniedServers.reserve(acls->content.deny.size()); |
| 1475 | for (const auto &s : acls->content.deny) |
| 1476 | allowedServers.push_back(globToRegexp(s)); |
| 1477 | } |
| 1478 | |
| 1479 | auto isHostAllowed = [&acls, &allowedServers, &deniedServers](const std::string &host) { |
| 1480 | if (!acls) |
| 1481 | return true; |
| 1482 | |
| 1483 | auto url = QUrl::fromEncoded( |
| 1484 | "https://" + QByteArray::fromRawData(host.data(), host.size()), QUrl::StrictMode); |
| 1485 | if (url.hasQuery() || url.hasFragment()) |
| 1486 | return false; |
| 1487 | |
| 1488 | auto hostname = url.host(); |
| 1489 | |
| 1490 | for (const auto &d : deniedServers) |
| 1491 | if (d.match(hostname).hasMatch()) |
| 1492 | return false; |
| 1493 | for (const auto &a : allowedServers) |
| 1494 | if (a.match(hostname).hasMatch()) |
| 1495 | return true; |
| 1496 | |
| 1497 | return false; |
| 1498 | }; |
| 1499 | |
| 1500 | std::unordered_set<std::string> users_with_high_pl; |
| 1501 | std::set<std::string> users_with_high_pl_in_room; |
| 1502 | // we should pick PL > 50, but imo that is broken, so we just pick users who have admins |
| 1503 | // perm |
| 1504 | for (const auto &user : powerlevels.content.users) { |
| 1505 | if (user.second >= powerlevels.content.events_default && |
| 1506 | user.second >= powerlevels.content.state_default) { |
| 1507 | auto host = |
| 1508 | mtx::identifiers::parse<mtx::identifiers::User>(user.first).hostname(); |
| 1509 | if (isHostAllowed(host)) |
| 1510 | users_with_high_pl.insert(user.first); |
| 1511 | } |
| 1512 | } |
| 1513 | |
| 1514 | std::unordered_map<std::string, std::size_t> usercount_by_server; |
| 1515 | for (const auto &m : members) { |
| 1516 | auto user_id = mtx::identifiers::parse<mtx::identifiers::User>(m); |
| 1517 | usercount_by_server[user_id.hostname()] += 1; |
| 1518 | |
| 1519 | if (users_with_high_pl.count(m)) |
| 1520 | users_with_high_pl_in_room.insert(m); |
| 1521 | } |
| 1522 | |
| 1523 | std::erase_if(usercount_by_server, [&isHostAllowed](const auto &item) { |
| 1524 | return !isHostAllowed(item.first); |
| 1525 | }); |
| 1526 | |
| 1527 | // add the highest powerlevel user |
| 1528 | auto max_pl_user = std::max_element( |
| 1529 | users_with_high_pl_in_room.begin(), |
| 1530 | users_with_high_pl_in_room.end(), |
| 1531 | [&pl_content = powerlevels.content](const std::string &a, const std::string &b) { |
| 1532 | return pl_content.user_level(a) < pl_content.user_level(b); |
| 1533 | }); |
| 1534 | if (max_pl_user != users_with_high_pl_in_room.end()) { |
| 1535 | auto host = |
| 1536 | mtx::identifiers::parse<mtx::identifiers::User>(*max_pl_user).hostname(); |
| 1537 | vias.push_back(host); |
| 1538 | usercount_by_server.erase(host); |
| 1539 | } |
| 1540 | |
| 1541 | // add up to 3 users, by usercount size from that server |
| 1542 | std::vector<std::pair<std::size_t, std::string>> servers_sorted_by_usercount; |
| 1543 | servers_sorted_by_usercount.reserve(usercount_by_server.size()); |
| 1544 | for (const auto &[server, count] : usercount_by_server) |
| 1545 | servers_sorted_by_usercount.emplace_back(count, server); |
| 1546 | |
| 1547 | std::sort(servers_sorted_by_usercount.begin(), |
| 1548 | servers_sorted_by_usercount.end(), |
| 1549 | [](const auto &a, const auto &b) { |
| 1550 | if (a.first == b.first) |
| 1551 | // same pl, sort lex smaller server first |
| 1552 | return a.second < b.second; |
| 1553 | |
| 1554 | // sort high user count first |
| 1555 | return a.first > b.first; |
| 1556 | }); |
| 1557 | |
| 1558 | for (const auto &server : servers_sorted_by_usercount) { |
| 1559 | if (vias.size() >= 3) |
| 1560 | break; |
| 1561 | |
| 1562 | vias.push_back(server.second); |
| 1563 | } |
| 1564 | |
| 1565 | return vias; |
| 1566 | } |
| 1567 | } |
| 1568 | |
| 1569 | // for invites |
| 1570 | { |
| 1571 | auto members = cache::getMembersFromInvite(roomid, 0, 100); |
| 1572 | if (!members.empty()) { |
| 1573 | vias.push_back(http::client()->user_id().hostname()); |
| 1574 | for (const auto &m : members) { |
| 1575 | if (vias.size() >= 3) |
| 1576 | break; |
| 1577 | |
| 1578 | auto user_id = |
| 1579 | mtx::identifiers::parse<mtx::identifiers::User>(m.user_id.toStdString()); |
| 1580 | |
| 1581 | auto server = user_id.hostname(); |
| 1582 | if (std::find(begin(vias), end(vias), server) == vias.end()) |
| 1583 | vias.push_back(server); |
| 1584 | } |
| 1585 | |
| 1586 | return vias; |
| 1587 | } |
| 1588 | } |
| 1589 | |
| 1590 | // for space previews |
| 1591 | auto parents = cache::client()->getParentRoomIds(roomid); |
| 1592 | for (const auto &p : parents) { |
| 1593 | auto child = cache::client()->getStateEvent<mtx::events::state::space::Child>(p, roomid); |
| 1594 | if (child && child->content.via) |
| 1595 | vias.insert(vias.end(), child->content.via->begin(), child->content.via->end()); |
| 1596 | } |
| 1597 | |
| 1598 | std::sort(begin(vias), end(vias)); |
| 1599 | auto last = std::unique(begin(vias), end(vias)); |
| 1600 | vias.erase(last, end(vias)); |
| 1601 | |
| 1602 | return vias; |
| 1603 | } |
| 1604 | |
| 1605 | void |
| 1606 | utils::updateSpaceVias() |
| 1607 | { |
| 1608 | if (!UserSettings::instance()->updateSpaceVias()) |
| 1609 | return; |
| 1610 | |
| 1611 | nhlog::net()->info("update space vias called"); |
| 1612 | |
| 1613 | auto rooms = cache::roomInfo(false); |
| 1614 | |
| 1615 | auto us = http::client()->user_id().to_string(); |
| 1616 | |
| 1617 | auto weekAgo = (uint64_t)QDateTime::currentDateTime().addDays(-7).toMSecsSinceEpoch(); |
| 1618 | |
| 1619 | struct ApplySpaceUpdatesState |
| 1620 | { |
| 1621 | std::vector<mtx::events::StateEvent<mtx::events::state::space::Child>> childrenToUpdate; |
| 1622 | std::vector<mtx::events::StateEvent<mtx::events::state::space::Parent>> parentsToUpdate; |
| 1623 | |
| 1624 | static void next(std::shared_ptr<ApplySpaceUpdatesState> state) |
| 1625 | { |
| 1626 | if (!state->childrenToUpdate.empty()) { |
| 1627 | const auto &child = state->childrenToUpdate.back(); |
| 1628 | |
| 1629 | http::client()->send_state_event( |
| 1630 | child.room_id, |
| 1631 | child.state_key, |
| 1632 | child.content, |
| 1633 | [state = std::move(state)](const mtx::responses::EventId &, |
| 1634 | mtx::http::RequestErr e) mutable { |
| 1635 | const auto &child_ = state->childrenToUpdate.back(); |
| 1636 | if (e) { |
| 1637 | if (e->status_code == 429 && e->matrix_error.retry_after.count() != 0) { |
| 1638 | ChatPage::instance()->callFunctionOnGuiThread( |
| 1639 | [state = std::move(state), |
| 1640 | interval = e->matrix_error.retry_after]() { |
| 1641 | QTimer::singleShot(interval * 3, |
| 1642 | ChatPage::instance(), |
| 1643 | [self = std::move(state)]() mutable { |
| 1644 | next(std::move(self)); |
| 1645 | }); |
| 1646 | }); |
| 1647 | return; |
| 1648 | } |
| 1649 | |
| 1650 | nhlog::net()->error("Failed to update space child {} -> {}: {}", |
| 1651 | child_.room_id, |
| 1652 | child_.state_key, |
| 1653 | *e); |
| 1654 | } |
| 1655 | nhlog::net()->info( |
| 1656 | "Updated space child {} -> {}", child_.room_id, child_.state_key); |
| 1657 | state->childrenToUpdate.pop_back(); |
| 1658 | next(std::move(state)); |
| 1659 | }); |
| 1660 | return; |
| 1661 | } else if (!state->parentsToUpdate.empty()) { |
| 1662 | const auto &parent = state->parentsToUpdate.back(); |
| 1663 | |
| 1664 | http::client()->send_state_event( |
| 1665 | parent.room_id, |
| 1666 | parent.state_key, |
| 1667 | parent.content, |
| 1668 | [state = std::move(state)](const mtx::responses::EventId &, |
| 1669 | mtx::http::RequestErr e) mutable { |
| 1670 | const auto &parent_ = state->parentsToUpdate.back(); |
| 1671 | if (e) { |
| 1672 | if (e->status_code == 429 && e->matrix_error.retry_after.count() != 0) { |
| 1673 | ChatPage::instance()->callFunctionOnGuiThread( |
| 1674 | [state = std::move(state), |
| 1675 | interval = e->matrix_error.retry_after]() { |
| 1676 | QTimer::singleShot(interval * 3, |
| 1677 | ChatPage::instance(), |
| 1678 | [self = std::move(state)]() mutable { |
| 1679 | next(std::move(self)); |
| 1680 | }); |
| 1681 | }); |
| 1682 | return; |
| 1683 | } |
| 1684 | |
| 1685 | nhlog::net()->error("Failed to update space parent {} -> {}: {}", |
| 1686 | parent_.room_id, |
| 1687 | parent_.state_key, |
| 1688 | *e); |
| 1689 | } |
| 1690 | nhlog::net()->info( |
| 1691 | "Updated space parent {} -> {}", parent_.room_id, parent_.state_key); |
| 1692 | state->parentsToUpdate.pop_back(); |
| 1693 | next(std::move(state)); |
| 1694 | }); |
| 1695 | return; |
| 1696 | } |
| 1697 | } |
| 1698 | }; |
| 1699 | |
| 1700 | auto asus = std::make_shared<ApplySpaceUpdatesState>(); |
| 1701 | |
| 1702 | for (const auto &[roomid, info] : rooms.toStdMap()) { |
| 1703 | if (!info.is_space) |
| 1704 | continue; |
| 1705 | |
| 1706 | auto spaceid = roomid.toStdString(); |
| 1707 | |
| 1708 | if (auto pl = cache::client() |
| 1709 | ->getStateEvent<mtx::events::state::PowerLevels>(spaceid) |
| 1710 | .value_or(mtx::events::StateEvent<mtx::events::state::PowerLevels>{}) |
| 1711 | .content; |
| 1712 | pl.user_level(us) < pl.state_level(to_string(mtx::events::EventType::SpaceChild))) |
| 1713 | continue; |
| 1714 | |
| 1715 | auto children = cache::client()->getChildRoomIds(spaceid); |
| 1716 | |
| 1717 | for (const auto &childid : children) { |
| 1718 | // only update children we are joined to |
| 1719 | if (!rooms.contains(QString::fromStdString(childid))) |
| 1720 | continue; |
| 1721 | |
| 1722 | auto child = |
| 1723 | cache::client()->getStateEvent<mtx::events::state::space::Child>(spaceid, childid); |
| 1724 | if (child && |
| 1725 | // don't update too often |
| 1726 | child->origin_server_ts < weekAgo && |
| 1727 | // ignore unset spaces |
| 1728 | (child->content.via && !child->content.via->empty())) { |
| 1729 | auto newVias = utils::roomVias(childid); |
| 1730 | |
| 1731 | if (!newVias.empty() && newVias != child->content.via) { |
| 1732 | nhlog::net()->info("Will update {} -> {} child relation from {} to {}", |
| 1733 | spaceid, |
| 1734 | childid, |
| 1735 | fmt::join(*child->content.via, ","), |
| 1736 | fmt::join(newVias, ",")); |
| 1737 | |
| 1738 | child->content.via = std::move(newVias); |
| 1739 | child->room_id = spaceid; |
| 1740 | asus->childrenToUpdate.push_back(*std::move(child)); |
| 1741 | } |
| 1742 | } |
| 1743 | |
| 1744 | auto parent = |
| 1745 | cache::client()->getStateEvent<mtx::events::state::space::Parent>(childid, spaceid); |
| 1746 | if (parent && |
| 1747 | // don't update too often |
| 1748 | parent->origin_server_ts < weekAgo && |
| 1749 | // ignore unset spaces |
| 1750 | (parent->content.via && !parent->content.via->empty())) { |
| 1751 | if (auto pl = |
| 1752 | cache::client() |
| 1753 | ->getStateEvent<mtx::events::state::PowerLevels>(childid) |
| 1754 | .value_or(mtx::events::StateEvent<mtx::events::state::PowerLevels>{}) |
| 1755 | .content; |
| 1756 | pl.user_level(us) < |
| 1757 | pl.state_level(to_string(mtx::events::EventType::SpaceParent))) |
| 1758 | continue; |
| 1759 | |
| 1760 | auto newVias = utils::roomVias(spaceid); |
| 1761 | |
| 1762 | if (!newVias.empty() && newVias != parent->content.via) { |
| 1763 | nhlog::net()->info("Will update {} -> {} parent relation from {} to {}", |
| 1764 | childid, |
| 1765 | spaceid, |
| 1766 | fmt::join(*parent->content.via, ","), |
| 1767 | fmt::join(newVias, ",")); |
| 1768 | |
| 1769 | parent->content.via = std::move(newVias); |
| 1770 | parent->room_id = childid; |
| 1771 | asus->parentsToUpdate.push_back(*std::move(parent)); |
| 1772 | } |
| 1773 | } |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | ApplySpaceUpdatesState::next(std::move(asus)); |
| 1778 | } |
| 1779 | |
| 1780 | std::atomic<bool> event_expiration_running = false; |
| 1781 | void |
| 1782 | utils::removeExpiredEvents() |
| 1783 | { |
| 1784 | if (!UserSettings::instance()->expireEvents()) |
| 1785 | return; |
| 1786 | |
| 1787 | if (event_expiration_running.exchange(true)) { |
| 1788 | nhlog::net()->info("Event expiration still running, not starting second job."); |
| 1789 | return; |
| 1790 | } |
| 1791 | |
| 1792 | nhlog::net()->info("Remove expired events starting."); |
| 1793 | |
| 1794 | auto rooms = cache::roomInfo(false); |
| 1795 | |
| 1796 | auto us = http::client()->user_id().to_string(); |
| 1797 | |
| 1798 | using ExpType = |
| 1799 | mtx::events::AccountDataEvent<mtx::events::account_data::nheko_extensions::EventExpiry>; |
| 1800 | static auto getExpEv = [](const std::string &room = "") -> std::optional<ExpType> { |
| 1801 | if (auto accountEvent = |
| 1802 | cache::client()->getAccountData(mtx::events::EventType::NhekoEventExpiry, room)) |
| 1803 | if (auto ev = std::get_if<ExpType>(&*accountEvent); |
| 1804 | ev && (ev->content.expire_after_ms || ev->content.keep_only_latest)) |
| 1805 | return std::optional{*ev}; |
| 1806 | return std::nullopt; |
| 1807 | }; |
| 1808 | |
| 1809 | struct ApplyEventExpiration |
| 1810 | { |
| 1811 | std::optional<ExpType> globalExpiry; |
| 1812 | std::vector<std::string> roomsToUpdate; |
| 1813 | std::string filter; |
| 1814 | |
| 1815 | std::string currentRoom; |
| 1816 | bool firstMessagesCall = true; |
| 1817 | std::uint64_t currentRoomCount = 0; |
| 1818 | |
| 1819 | // batch token for pagination |
| 1820 | std::string currentRoomPrevToken; |
| 1821 | // event id of an event redacted in a previous run |
| 1822 | std::string currentRoomStopAt; |
| 1823 | // event id of first event redacted in the current run, hoping that the order stays the |
| 1824 | // same. |
| 1825 | std::string currentRoomFirstRedactedEvent; |
| 1826 | // (evtype,state_key) tuple to keep the latest state event of each. |
| 1827 | std::set<std::pair<std::string, std::string>> currentRoomStateEvents; |
| 1828 | // event ids pending redaction |
| 1829 | std::vector<std::string> currentRoomRedactionQueue; |
| 1830 | |
| 1831 | mtx::events::account_data::nheko_extensions::EventExpiry currentExpiry; |
| 1832 | |
| 1833 | static void next(std::shared_ptr<ApplyEventExpiration> state) |
| 1834 | { |
| 1835 | if (!state->currentRoomRedactionQueue.empty()) { |
| 1836 | auto evid = state->currentRoomRedactionQueue.back(); |
| 1837 | auto room = state->currentRoom; |
| 1838 | http::client()->redact_event( |
| 1839 | room, |
| 1840 | evid, |
| 1841 | [state = std::move(state), evid](const mtx::responses::EventId &, |
| 1842 | mtx::http::RequestErr e) mutable { |
| 1843 | if (e) { |
| 1844 | if (e->status_code == 429 && e->matrix_error.retry_after.count() != 0) { |
| 1845 | ChatPage::instance()->callFunctionOnGuiThread( |
| 1846 | [state = std::move(state), |
| 1847 | interval = e->matrix_error.retry_after]() { |
| 1848 | // triple interval to allow other traffic as well |
| 1849 | QTimer::singleShot(interval * 3, |
| 1850 | ChatPage::instance(), |
| 1851 | [self = std::move(state)]() mutable { |
| 1852 | next(std::move(self)); |
| 1853 | }); |
| 1854 | }); |
| 1855 | return; |
| 1856 | } else { |
| 1857 | nhlog::net()->error("Failed to redact event {} in {}: {}", |
| 1858 | evid, |
| 1859 | state->currentRoom, |
| 1860 | *e); |
| 1861 | state->currentRoomRedactionQueue.pop_back(); |
| 1862 | next(std::move(state)); |
| 1863 | } |
| 1864 | } else { |
| 1865 | nhlog::net()->info("Redacted event {} in {}", evid, state->currentRoom); |
| 1866 | |
| 1867 | if (state->currentRoomFirstRedactedEvent.empty()) |
| 1868 | state->currentRoomFirstRedactedEvent = evid; |
| 1869 | |
| 1870 | state->currentRoomRedactionQueue.pop_back(); |
| 1871 | next(std::move(state)); |
| 1872 | } |
| 1873 | }); |
| 1874 | } else if (!state->currentRoom.empty()) { |
| 1875 | if (state->currentRoomPrevToken.empty() && !state->firstMessagesCall) { |
| 1876 | nhlog::net()->info("Finished room {}", state->currentRoom); |
| 1877 | |
| 1878 | if (!state->currentRoomFirstRedactedEvent.empty()) |
| 1879 | cache::client()->storeEventExpirationProgress( |
| 1880 | state->currentRoom, |
| 1881 | nlohmann::json(state->currentExpiry).dump(), |
| 1882 | state->currentRoomFirstRedactedEvent); |
| 1883 | |
| 1884 | state->currentRoom.clear(); |
| 1885 | next(std::move(state)); |
| 1886 | return; |
| 1887 | } |
| 1888 | |
| 1889 | mtx::http::MessagesOpts opts{}; |
| 1890 | opts.dir = mtx::http::PaginationDirection::Backwards; |
| 1891 | opts.from = state->currentRoomPrevToken; |
| 1892 | opts.limit = 1000; |
| 1893 | opts.filter = state->filter; |
| 1894 | opts.room_id = state->currentRoom; |
| 1895 | |
| 1896 | state->firstMessagesCall = false; |
| 1897 | |
| 1898 | http::client()->messages( |
| 1899 | opts, |
| 1900 | [state = std::move(state)](const mtx::responses::Messages &msgs, |
| 1901 | mtx::http::RequestErr error) mutable { |
| 1902 | if (error) { |
| 1903 | // skip success handler |
| 1904 | nhlog::net()->warn( |
| 1905 | "Finished room {} with error {}", state->currentRoom, *error); |
| 1906 | state->currentRoom.clear(); |
| 1907 | } else if (msgs.chunk.empty()) { |
| 1908 | state->currentRoomPrevToken.clear(); |
| 1909 | } else { |
| 1910 | state->currentRoomPrevToken = msgs.end; |
| 1911 | |
| 1912 | auto now = (uint64_t)QDateTime::currentMSecsSinceEpoch(); |
| 1913 | auto us = http::client()->user_id().to_string(); |
| 1914 | |
| 1915 | for (const auto &e : msgs.chunk) { |
| 1916 | if (std::holds_alternative< |
| 1917 | mtx::events::RedactionEvent<mtx::events::msg::Redaction>>(e)) |
| 1918 | continue; |
| 1919 | |
| 1920 | if (std::holds_alternative< |
| 1921 | mtx::events::RoomEvent<mtx::events::msg::Redacted>>(e) || |
| 1922 | std::holds_alternative< |
| 1923 | mtx::events::StateEvent<mtx::events::msg::Redacted>>(e)) { |
| 1924 | if (!state->currentRoomStopAt.empty() && |
| 1925 | mtx::accessors::event_id(e) == state->currentRoomStopAt) { |
| 1926 | // There is no filter to remove redacted events from |
| 1927 | // pagination, so we try to stop early by caching what event |
| 1928 | // we redacted last if we reached the end of a room. |
| 1929 | nhlog::net()->info( |
| 1930 | "Found previous redaction marker, stopping early: {}", |
| 1931 | state->currentRoom); |
| 1932 | state->currentRoomPrevToken.clear(); |
| 1933 | break; |
| 1934 | } |
| 1935 | continue; |
| 1936 | } |
| 1937 | |
| 1938 | if (std::holds_alternative< |
| 1939 | mtx::events::StateEvent<mtx::events::msg::Redacted>>(e)) |
| 1940 | continue; |
| 1941 | |
| 1942 | // synapse protects these 2 against redaction |
| 1943 | if (std::holds_alternative< |
| 1944 | mtx::events::StateEvent<mtx::events::state::Create>>(e)) |
| 1945 | continue; |
| 1946 | |
| 1947 | if (std::holds_alternative< |
| 1948 | mtx::events::StateEvent<mtx::events::state::ServerAcl>>(e)) |
| 1949 | continue; |
| 1950 | |
| 1951 | // skip events we don't know to protect us from mistakes. |
| 1952 | if (std::holds_alternative< |
| 1953 | mtx::events::RoomEvent<mtx::events::Unknown>>(e)) |
| 1954 | continue; |
| 1955 | |
| 1956 | if (mtx::accessors::sender(e) != us) |
| 1957 | continue; |
| 1958 | |
| 1959 | state->currentRoomCount++; |
| 1960 | if (state->currentRoomCount <= state->currentExpiry.protect_latest) { |
| 1961 | continue; |
| 1962 | } |
| 1963 | |
| 1964 | if (state->currentExpiry.exclude_state_events && |
| 1965 | mtx::accessors::is_state_event(e)) |
| 1966 | continue; |
| 1967 | |
| 1968 | if (mtx::accessors::is_state_event(e)) { |
| 1969 | // skip the first state event of a type |
| 1970 | if (std::visit( |
| 1971 | [&state](const auto &se) { |
| 1972 | if constexpr (requires { se.state_key; }) |
| 1973 | return state->currentRoomStateEvents |
| 1974 | .emplace(to_string(se.type), se.state_key) |
| 1975 | .second; |
| 1976 | else |
| 1977 | return true; |
| 1978 | }, |
| 1979 | e)) |
| 1980 | continue; |
| 1981 | } |
| 1982 | |
| 1983 | if (state->currentExpiry.keep_only_latest && |
| 1984 | state->currentRoomCount > state->currentExpiry.keep_only_latest) { |
| 1985 | state->currentRoomRedactionQueue.push_back( |
| 1986 | mtx::accessors::event_id(e)); |
| 1987 | } else if (state->currentExpiry.expire_after_ms && |
| 1988 | (state->currentExpiry.expire_after_ms + |
| 1989 | mtx::accessors::origin_server_ts(e).toMSecsSinceEpoch()) < |
| 1990 | now) { |
| 1991 | state->currentRoomRedactionQueue.push_back( |
| 1992 | mtx::accessors::event_id(e)); |
| 1993 | } |
| 1994 | } |
| 1995 | } |
| 1996 | |
| 1997 | next(std::move(state)); |
| 1998 | }); |
| 1999 | } else if (!state->roomsToUpdate.empty()) { |
| 2000 | const auto &room = state->roomsToUpdate.back(); |
| 2001 | |
| 2002 | auto localExp = getExpEv(room); |
| 2003 | if (localExp) { |
| 2004 | state->currentRoom = room; |
| 2005 | state->currentExpiry = localExp->content; |
| 2006 | } else if (state->globalExpiry) { |
| 2007 | state->currentRoom = room; |
| 2008 | state->currentExpiry = state->globalExpiry->content; |
| 2009 | } |
| 2010 | state->firstMessagesCall = true; |
| 2011 | state->currentRoomCount = 0; |
| 2012 | state->currentRoomPrevToken = ""; |
| 2013 | state->currentRoomRedactionQueue.clear(); |
| 2014 | state->currentRoomStateEvents.clear(); |
| 2015 | |
| 2016 | state->currentRoomStopAt = cache::client()->loadEventExpirationProgress( |
| 2017 | state->currentRoom, nlohmann::json(state->currentExpiry).dump()); |
| 2018 | |
| 2019 | state->roomsToUpdate.pop_back(); |
| 2020 | next(std::move(state)); |
| 2021 | } else { |
| 2022 | nhlog::net()->info("Finished event expiry"); |
| 2023 | event_expiration_running = false; |
| 2024 | } |
| 2025 | } |
| 2026 | }; |
| 2027 | |
| 2028 | auto asus = std::make_shared<ApplyEventExpiration>(); |
| 2029 | |
| 2030 | nlohmann::json filter; |
| 2031 | filter["timeline"]["senders"] = nlohmann::json::array({us}); |
| 2032 | filter["timeline"]["not_types"] = nlohmann::json::array({"m.room.redaction"}); |
| 2033 | |
| 2034 | asus->filter = filter.dump(); |
| 2035 | |
| 2036 | asus->globalExpiry = getExpEv(); |
| 2037 | |
| 2038 | for (const auto &[roomid_, info] : rooms.toStdMap()) { |
| 2039 | auto roomid = roomid_.toStdString(); |
| 2040 | |
| 2041 | if (!asus->globalExpiry && !getExpEv(roomid)) |
| 2042 | continue; |
| 2043 | |
| 2044 | if (auto pl = cache::client() |
| 2045 | ->getStateEvent<mtx::events::state::PowerLevels>(roomid) |
| 2046 | .value_or(mtx::events::StateEvent<mtx::events::state::PowerLevels>{}) |
| 2047 | .content; |
| 2048 | pl.user_level(us) < pl.event_level(to_string(mtx::events::EventType::RoomRedaction))) { |
| 2049 | nhlog::net()->warn("Can't react events in {}, not running expiration.", roomid); |
| 2050 | continue; |
| 2051 | } |
| 2052 | |
| 2053 | asus->roomsToUpdate.push_back(roomid); |
| 2054 | } |
| 2055 | |
| 2056 | nhlog::db()->info("Running expiration in {} rooms", asus->roomsToUpdate.size()); |
| 2057 | |
| 2058 | ApplyEventExpiration::next(std::move(asus)); |
| 2059 | } |
| 2060 | |
| 2061 | namespace { |
| 2062 | static const QList<QChar> diacritics = []() { |
| 2063 | QList<QChar> ret; |
| 2064 | for (wchar_t c = u'\u0300'; c <= u'\u036f'; ++c) |
| 2065 | ret.append(QChar(c)); |
| 2066 | return ret; |
| 2067 | }(); |
| 2068 | } |
| 2069 | |
| 2070 | QString |
| 2071 | utils::glitchText(const QString &text) |
| 2072 | { |
| 2073 | QString result; |
| 2074 | for (int i = 0; i < text.size(); ++i) { |
| 2075 | result.append(text.at(i)); |
| 2076 | if (QRandomGenerator64::global()->bounded(0, 100) >= 25) |
| 2077 | result.append( |
| 2078 | diacritics.at(QRandomGenerator64::global()->bounded(0, diacritics.size()))); |
| 2079 | } |
| 2080 | return result; |
| 2081 | } |
| 2082 | |
| 2083 | QString |
| 2084 | utils::graduallyGlitchText(const QString &text) |
| 2085 | { |
| 2086 | QString result; |
| 2087 | |
| 2088 | const int noGlitch = text.size() * 0.5; |
| 2089 | const int someGlitch = text.size() * 0.8; |
| 2090 | const int lotsOfGlitch = text.size() * 0.95; |
| 2091 | |
| 2092 | for (int i = 0; i < text.size(); ++i) { |
| 2093 | result.append(text.at(i)); |
| 2094 | |
| 2095 | if (i < noGlitch) // first 40% of text is normal |
| 2096 | continue; |
| 2097 | else if (i < someGlitch) // next 25% is progressively glitchier |
| 2098 | { |
| 2099 | if (QRandomGenerator64::global()->bounded(noGlitch, someGlitch) < |
| 2100 | noGlitch + (i - noGlitch) * 0.05) |
| 2101 | result.append( |
| 2102 | diacritics.at(QRandomGenerator64::global()->bounded(0, diacritics.size()))); |
| 2103 | } else if (i < lotsOfGlitch) { // oh no, it's spreading! |
| 2104 | if (QRandomGenerator64::global()->bounded(someGlitch, lotsOfGlitch) < i) |
| 2105 | result.append( |
| 2106 | diacritics.at(QRandomGenerator64::global()->bounded(0, diacritics.size()))); |
| 2107 | } else { // just give up, your computer is cursed now |
| 2108 | do { |
| 2109 | if (QRandomGenerator64::global()->bounded(text.size() / 5, text.size()) < i) |
| 2110 | result.append( |
| 2111 | diacritics.at(QRandomGenerator64::global()->bounded(0, diacritics.size()))); |
| 2112 | } while (QRandomGenerator64::global()->bounded(0, 100) < 35); |
| 2113 | } |
| 2114 | } |
| 2115 | |
| 2116 | return result; |
| 2117 | } |
| 2118 | |
| 2119 | static QString |
| 2120 | mxidFromSegments(QStringView sigil, QStringView mxid) |
| 2121 | { |
| 2122 | if (mxid.isEmpty()) |
| 2123 | return QString(); |
| 2124 | |
| 2125 | auto mxid_ = QUrl::fromPercentEncoding(mxid.toUtf8()); |
| 2126 | |
| 2127 | if (sigil == u"u") { |
| 2128 | return "@" + mxid_; |
| 2129 | } else if (sigil == u"roomid") { |
| 2130 | return "!" + mxid_; |
| 2131 | } else if (sigil == u"r") { |
| 2132 | return "#" + mxid_; |
| 2133 | //} else if (sigil == "group") { |
| 2134 | // return "+" + mxid_; |
| 2135 | } else { |
| 2136 | return QString(); |
| 2137 | } |
| 2138 | } |
| 2139 | |
| 2140 | std::optional<utils::MatrixUriParseResult> |
| 2141 | utils::parseMatrixUri(QString uri) |
| 2142 | { |
| 2143 | QUrl uri_{uri}; |
| 2144 | |
| 2145 | // Convert matrix.to URIs to proper format |
| 2146 | if (uri_.scheme() == QLatin1String("https") && uri_.host() == QLatin1String("matrix.to")) { |
| 2147 | QString p = uri_.fragment(QUrl::FullyEncoded); |
| 2148 | if (p.startsWith(QLatin1String("/"))) |
| 2149 | p.remove(0, 1); |
| 2150 | |
| 2151 | auto temp = p.split(QStringLiteral("?")); |
| 2152 | QString query; |
| 2153 | if (temp.size() >= 2) |
| 2154 | query = QUrl::fromPercentEncoding(temp.takeAt(1).toUtf8()); |
| 2155 | |
| 2156 | temp = temp.first().split(QStringLiteral("/")); |
| 2157 | auto identifier = QUrl::fromPercentEncoding(temp.takeFirst().toUtf8()); |
| 2158 | QString eventId = QUrl::fromPercentEncoding(temp.join('/').toUtf8()); |
| 2159 | if (!identifier.isEmpty()) { |
| 2160 | if (identifier.startsWith(QLatin1String("@"))) { |
| 2161 | QByteArray newUri = "matrix:u/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); |
| 2162 | if (!query.isEmpty()) |
| 2163 | newUri.append("?" + query.toUtf8()); |
| 2164 | uri_ = QUrl::fromEncoded(newUri); |
| 2165 | } else if (identifier.startsWith(QLatin1String("#"))) { |
| 2166 | QByteArray newUri = "matrix:r/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); |
| 2167 | if (!eventId.isEmpty()) |
| 2168 | newUri.append("/e/" + QUrl::toPercentEncoding(eventId.remove(0, 1))); |
| 2169 | if (!query.isEmpty()) |
| 2170 | newUri.append("?" + query.toUtf8()); |
| 2171 | uri_ = QUrl::fromEncoded(newUri); |
| 2172 | } else if (identifier.startsWith(QLatin1String("!"))) { |
| 2173 | QByteArray newUri = |
| 2174 | "matrix:roomid/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); |
| 2175 | if (!eventId.isEmpty()) |
| 2176 | newUri.append("/e/" + QUrl::toPercentEncoding(eventId.remove(0, 1))); |
| 2177 | if (!query.isEmpty()) |
| 2178 | newUri.append("?" + query.toUtf8()); |
| 2179 | uri_ = QUrl::fromEncoded(newUri); |
| 2180 | } |
| 2181 | } |
| 2182 | } |
| 2183 | |
| 2184 | // non-matrix URIs are not handled by us, return false |
| 2185 | if (uri_.scheme() != QLatin1String("matrix")) |
| 2186 | return {}; |
| 2187 | |
| 2188 | auto tempPath = uri_.path(QUrl::ComponentFormattingOption::FullyEncoded); |
| 2189 | if (tempPath.startsWith('/')) |
| 2190 | tempPath.remove(0, 1); |
| 2191 | auto segments = QStringView(tempPath).split('/'); |
| 2192 | |
| 2193 | if (segments.size() != 2 && segments.size() != 4) |
| 2194 | return {}; |
| 2195 | |
| 2196 | auto sigil1 = segments[0]; |
| 2197 | auto mxid1 = mxidFromSegments(sigil1, segments[1]); |
| 2198 | if (mxid1.isEmpty()) |
| 2199 | return {}; |
| 2200 | |
| 2201 | QString mxid2; |
| 2202 | QString sigil2; |
| 2203 | if (segments.size() == 4 && segments[2] == QStringView(u"e")) { |
| 2204 | if (segments[3].isEmpty()) |
| 2205 | return {}; |
| 2206 | else |
| 2207 | mxid2 = "$" + QUrl::fromPercentEncoding(segments[3].toUtf8()); |
| 2208 | sigil2 = "$"; |
| 2209 | } |
| 2210 | |
| 2211 | std::vector<std::string> vias; |
| 2212 | QString action; |
| 2213 | |
| 2214 | auto items = |
| 2215 | uri_.query(QUrl::ComponentFormattingOption::FullyEncoded).split('&', Qt::SkipEmptyParts); |
| 2216 | for (QString item : std::as_const(items)) { |
| 2217 | if (item.startsWith(QLatin1String("action="))) { |
| 2218 | action = item.remove(QStringLiteral("action=")); |
| 2219 | } else if (item.startsWith(QLatin1String("via="))) { |
| 2220 | vias.push_back(QUrl::fromPercentEncoding(item.remove(QStringLiteral("via=")).toUtf8()) |
| 2221 | .toStdString()); |
| 2222 | } |
| 2223 | } |
| 2224 | |
| 2225 | return MatrixUriParseResult{ |
| 2226 | .sigil1 = sigil1.toString(), |
| 2227 | .mxid1 = std::move(mxid1), |
| 2228 | .sigil2 = std::move(sigil2), |
| 2229 | .mxid2 = std::move(mxid2), |
| 2230 | .action = std::move(action), |
| 2231 | .vias = std::move(vias), |
| 2232 | }; |
| 2233 | } |
| 2234 | |
| 2235 | void |
| 2236 | utils::markFileAsFromWeb(const QString &path [[maybe_unused]]) |
| 2237 | { |
| 2238 | #ifdef Q_OS_WINDOWS |
| 2239 | QFile file(path + ":Zone.Identifier"); |
| 2240 | if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly)) { |
| 2241 | nhlog::net()->error("Failed to open alternate stream for {}", path.toStdString()); |
| 2242 | return; |
| 2243 | } |
| 2244 | |
| 2245 | file.write("[ZoneTransfer]\nZoneId=3"); |
| 2246 | file.close(); |
| 2247 | #endif |
| 2248 | } |