Debian Codegraph @

src/timeline/InputBar.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "InputBar.h"
6
7 #include <QBuffer>
8 #include <QClipboard>
9 #include <QDropEvent>
10 #include <QFileDialog>
11 #include <QGuiApplication>
12 #include <QInputMethod>
13 #include <QMediaMetaData>
14 #include <QMediaPlayer>
15 #include <QMimeData>
16 #include <QMimeDatabase>
17 #include <QRegularExpression>
18 #include <QStandardPaths>
19 #include <QTextBoundaryFinder>
20 #include <QVideoFrame>
21 #include <QVideoSink>
22
23 #include <fmt/format.h>
24
25 #include <nlohmann/json.hpp>
26
27 #include <mtx/responses/common.hpp>
28 #include <mtx/responses/media.hpp>
29
30 #include "Cache.h"
31 #include "Cache_p.h"
32 #include "ChatPage.h"
33 #include "EventAccessors.h"
34 #include "Logging.h"
35 #include "MainWindow.h"
36 #include "MatrixClient.h"
37 #include "TimelineModel.h"
38 #include "TimelineViewManager.h"
39 #include "UserSettingsPage.h"
40 #include "Utils.h"
41 #include "ui/UserProfile.h"
42
43 #include "blurhash.hpp"
44
45 static constexpr size_t INPUT_HISTORY_SIZE = 10;
46
47 std::string
48 threadFallbackEventId(const std::string &room_id, const std::string &thread_id)
49 {
50 auto event_ids = cache::client()->relatedEvents(room_id, thread_id);
51
52 std::map<uint64_t, std::string_view, std::greater<>> orderedEvents;
53
54 for (const auto &e : event_ids) {
55 if (auto index = cache::client()->getTimelineIndex(room_id, e))
56 orderedEvents.emplace(*index, e);
57 }
58
59 for (const auto &[index, event_id] : orderedEvents) {
60 (void)index;
61 if (auto event = cache::client()->getEvent(room_id, event_id)) {
62 if (mtx::accessors::relations(event.value()).thread() == thread_id)
63 return std::string(event_id);
64 }
65 }
66 return thread_id;
67 }
68
69 QUrl
70 MediaUpload::thumbnailDataUrl() const
71 {
72 if (thumbnail_.isNull())
73 return {};
74
75 QByteArray byteArray;
76 QBuffer buffer(&byteArray);
77 buffer.open(QIODevice::WriteOnly);
78 thumbnail_.save(&buffer, "PNG");
79 QString base64 = QString::fromUtf8(byteArray.toBase64());
80 return QStringLiteral("data:image/png;base64,") + base64;
81 }
82
83 bool
84 InputBar::tryPasteAttachment(bool fromMouse)
85 {
86 const QMimeData *md = nullptr;
87
88 if (fromMouse && QGuiApplication::clipboard()->supportsSelection()) {
89 md = QGuiApplication::clipboard()->mimeData(QClipboard::Selection);
90 } else {
91 md = QGuiApplication::clipboard()->mimeData(QClipboard::Clipboard);
92 }
93
94 if (md)
95 return insertMimeData(md);
96
97 return false;
98 }
99
100 bool
101 InputBar::insertMimeData(const QMimeData *md)
102 {
103 if (!md)
104 return false;
105
106 nhlog::ui()->debug("Got mime formats: {}",
107 md->formats().join(QStringLiteral(", ")).toStdString());
108 nhlog::ui()->debug("Has image: {}", md->hasImage());
109 const auto formats = md->formats().filter(QStringLiteral("/"));
110 const auto image = formats.filter(QStringLiteral("image/"), Qt::CaseInsensitive);
111 const auto audio = formats.filter(QStringLiteral("audio/"), Qt::CaseInsensitive);
112 const auto video = formats.filter(QStringLiteral("video/"), Qt::CaseInsensitive);
113
114 if (md->hasImage()) {
115 if (formats.contains(QStringLiteral("image/svg+xml"), Qt::CaseInsensitive)) {
116 startUploadFromMimeData(*md, QStringLiteral("image/svg+xml"));
117 } else if (formats.contains(QStringLiteral("image/png"), Qt::CaseInsensitive)) {
118 startUploadFromMimeData(*md, QStringLiteral("image/png"));
119 } else if (image.empty()) {
120 QByteArray ba;
121 QBuffer buffer(&ba);
122 buffer.open(QIODevice::WriteOnly);
123 qvariant_cast<QImage>(md->imageData()).save(&buffer, "PNG");
124 QMimeData d;
125 d.setData(QStringLiteral("image/png"), ba);
126 startUploadFromMimeData(d, QStringLiteral("image/png"));
127 } else {
128 startUploadFromMimeData(*md, image.first());
129 }
130 } else if (!audio.empty()) {
131 startUploadFromMimeData(*md, audio.first());
132 } else if (!video.empty()) {
133 startUploadFromMimeData(*md, video.first());
134 } else if (md->hasUrls() &&
135 // NOTE(Nico): Safari, when copying the url, sends a url list. Since we only paste
136 // local files, skip remote ones.
137 [&md] {
138 for (auto &&u : md->urls()) {
139 if (u.isLocalFile())
140 return true;
141 }
142 return false;
143 }()) {
144 // Generic file path for any platform.
145 for (auto &&u : md->urls()) {
146 if (u.isLocalFile()) {
147 startUploadFromPath(u.toLocalFile());
148 }
149 }
150 } else if (md->hasFormat(QStringLiteral("x-special/gnome-copied-files"))) {
151 // Special case for X11 users. See "Notes for X11 Users" in md.
152 // Source: http://doc.qt.io/qt-5/qclipboard.html
153
154 // This MIME type returns a string with multiple lines separated by '\n'. The first
155 // line is the command to perform with the clipboard (not useful to us). The
156 // following lines are the file URIs.
157 //
158 // Source: the nautilus source code in file 'src/nautilus-clipboard.c' in function
159 // nautilus_clipboard_get_uri_list_from_selection_data()
160 // https://github.com/GNOME/nautilus/blob/master/src/nautilus-clipboard.c
161
162 auto data = md->data(QStringLiteral("x-special/gnome-copied-files")).split('\n');
163 if (data.size() < 2) {
164 nhlog::ui()->warn("MIME format is malformed, cannot perform paste.");
165 return false;
166 }
167
168 for (int i = 1; i < data.size(); ++i) {
169 QUrl url{data[i]};
170 if (url.isLocalFile()) {
171 startUploadFromPath(url.toLocalFile());
172 }
173 }
174 } else if (md->hasText()) {
175 return false;
176 } else {
177 nhlog::ui()->debug("formats: {}", md->formats().join(QStringLiteral(", ")).toStdString());
178 return false;
179 }
180
181 return true;
182 }
183
184 void
185 InputBar::addMention(QString mention, QString text)
186 {
187 if (!mentions_.contains(mention)) {
188 mentions_.push_back(mention);
189 mentionTexts_.push_back(text);
190
191 emit mentionsChanged();
192 }
193 }
194
195 void
196 InputBar::removeMention(QString mention)
197 {
198 if (auto idx = mentions_.indexOf(mention); idx != -1) {
199 mentions_.removeAt(idx);
200 mentionTexts_.removeAt(idx);
201 emit mentionsChanged();
202 }
203 }
204
205 void
206 InputBar::updateTextContentProperties(const QString &t, bool charDeleted)
207 {
208 auto containsRoomMention = [](QStringView text) {
209 // check for @room
210 bool roomMention = false;
211 if (text.size() > 4) {
212 QTextBoundaryFinder finder(QTextBoundaryFinder::BoundaryType::Word, text);
213
214 finder.toStart();
215 do {
216 auto start = finder.position();
217 finder.toNextBoundary();
218 auto end = finder.position();
219 if (start > 0 && end - start >= 4 &&
220 text.mid(start, end - start) == QStringView(u"room") &&
221 text.at(start - 1) == QChar('@')) {
222 roomMention = true;
223 break;
224 }
225 } while (finder.position() < text.size());
226 }
227 return roomMention;
228 };
229
230 if (charDeleted) {
231 for (qsizetype idx = 0; idx < mentions_.size();) {
232 if (!t.contains(mentionTexts_.at(idx))) {
233 removeMention(mentions_.at(idx));
234 } else {
235 idx++;
236 }
237 }
238 }
239
240 auto roomMention = containsRoomMention(t) && this->room->permissions()->canPingRoom();
241
242 if (roomMention != this->containsAtRoom_) {
243 this->containsAtRoom_ = roomMention;
244 if (roomMention)
245 addMention(QStringLiteral(u"@room"), QStringLiteral(u"@room"));
246 else
247 removeMention(QStringLiteral(u"@room"));
248 }
249
250 // check for invalid commands
251 auto commandName = getCommandAndArgs(t).first;
252 static const QSet<QString> validCommands{QStringLiteral("me"),
253 QStringLiteral("react"),
254 QStringLiteral("join"),
255 QStringLiteral("knock"),
256 QStringLiteral("part"),
257 QStringLiteral("leave"),
258 QStringLiteral("invite"),
259 QStringLiteral("kick"),
260 QStringLiteral("ban"),
261 QStringLiteral("unban"),
262 QStringLiteral("redact"),
263 QStringLiteral("roomnick"),
264 QStringLiteral("shrug"),
265 QStringLiteral("fliptable"),
266 QStringLiteral("unfliptable"),
267 QStringLiteral("sovietflip"),
268 QStringLiteral("clear-timeline"),
269 QStringLiteral("reset-state"),
270 QStringLiteral("rotate-megolm-session"),
271 QStringLiteral("md"),
272 QStringLiteral("cmark"),
273 QStringLiteral("plain"),
274 QStringLiteral("rainbow"),
275 QStringLiteral("rainbowme"),
276 QStringLiteral("notice"),
277 QStringLiteral("rainbownotice"),
278 QStringLiteral("confetti"),
279 QStringLiteral("rainbowconfetti"),
280 QStringLiteral("rainfall"),
281 QStringLiteral("msgtype"),
282 QStringLiteral("glitch"),
283 QStringLiteral("gradualglitch"),
284 QStringLiteral("goto"),
285 QStringLiteral("converttodm"),
286 QStringLiteral("converttoroom"),
287 QStringLiteral("ignore"),
288 QStringLiteral("unignore"),
289 QStringLiteral("blockinvites"),
290 QStringLiteral("allowinvites")};
291 bool hasInvalidCommand = !commandName.isNull() && !validCommands.contains(commandName);
292 bool hasIncompleteCommand = hasInvalidCommand && '/' + commandName == t;
293
294 bool signalsChanged{false};
295 if (containsInvalidCommand_ != hasInvalidCommand) {
296 containsInvalidCommand_ = hasInvalidCommand;
297 signalsChanged = true;
298 }
299 if (containsIncompleteCommand_ != hasIncompleteCommand) {
300 containsIncompleteCommand_ = hasIncompleteCommand;
301 signalsChanged = true;
302 }
303 if (currentCommand_ != commandName) {
304 currentCommand_ = commandName;
305 signalsChanged = true;
306 }
307 if (signalsChanged) {
308 emit currentCommandChanged();
309 emit containsInvalidCommandChanged();
310 emit containsIncompleteCommandChanged();
311 }
312 }
313
314 void
315 InputBar::setText(const QString &newText)
316 {
317 if (history_.empty())
318 history_.push_front(newText);
319 else
320 history_.front() = newText;
321 history_index_ = 0;
322
323 if (history_.size() == INPUT_HISTORY_SIZE)
324 history_.pop_back();
325
326 updateTextContentProperties(newText, true);
327 emit textChanged(newText);
328 }
329 void
330 InputBar::updateState(int selectionStart_,
331 int selectionEnd_,
332 int cursorPosition_,
333 const QString &text_)
334 {
335 if (text_.isEmpty())
336 stopTyping();
337 else
338 startTyping();
339
340 auto oldText = text();
341 if (text_ != oldText) {
342 if (history_.empty())
343 history_.push_front(text_);
344 else
345 history_.front() = text_;
346 history_index_ = 0;
347
348 updateTextContentProperties(text_, text_.size() < oldText.size());
349 // disabled, as it moves the cursor to the end
350 // emit textChanged(text_);
351 }
352
353 selectionStart = selectionStart_;
354 selectionEnd = selectionEnd_;
355 cursorPosition = cursorPosition_;
356 }
357
358 QString
359 InputBar::text() const
360 {
361 if (history_index_ < history_.size())
362 return history_.at(history_index_);
363
364 return QString();
365 }
366
367 QString
368 InputBar::previousText()
369 {
370 history_index_++;
371 if (history_index_ >= INPUT_HISTORY_SIZE)
372 history_index_ = INPUT_HISTORY_SIZE;
373 else if (text().isEmpty())
374 history_index_--;
375
376 updateTextContentProperties(text());
377 return text();
378 }
379
380 QString
381 InputBar::nextText()
382 {
383 history_index_--;
384 if (history_index_ >= INPUT_HISTORY_SIZE)
385 history_index_ = 0;
386
387 updateTextContentProperties(text());
388 return text();
389 }
390
391 void
392 InputBar::send()
393 {
394 QInputMethod *im = QGuiApplication::inputMethod();
395 im->commit();
396 if (text().trimmed().isEmpty()) {
397 acceptUploads();
398 return;
399 }
400
401 nhlog::ui()->debug("Send: {}", text().toStdString());
402
403 auto wasEdit = !room->edit().isEmpty();
404
405 auto [commandName, args] = getCommandAndArgs();
406 updateTextContentProperties(text());
407 if (containsIncompleteCommand_)
408 return;
409 if (commandName.isEmpty() || !command(commandName, args))
410 message(text());
411
412 if (!wasEdit) {
413 history_.push_front(QLatin1String(""));
414 setText(QLatin1String(""));
415 }
416 }
417
418 void
419 InputBar::openFileSelection()
420 {
421 const QString homeFolder = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
422 const QStringList fileNames =
423 QFileDialog::getOpenFileNames(nullptr, tr("Select file(s)"), homeFolder, tr("All Files (*)"));
424
425 if (fileNames.isEmpty())
426 return;
427
428 ChatPage::instance()->timelineManager()->focusMessageInput();
429 for (const auto &fileName : fileNames)
430 startUploadFromPath(fileName);
431 }
432
433 QString
434 replaceMatrixToMarkdownLink(QString input)
435 {
436 bool replaced = false;
437 do {
438 replaced = false;
439
440 int endOfName = input.indexOf("](https://matrix.to/#/");
441 int startOfName;
442 int nestingCount = 0;
443 for (startOfName = endOfName - 1; startOfName > 0; startOfName--) {
444 // skip escaped chars
445 if (startOfName > 0 && input[startOfName - 1] == '\\')
446 continue;
447
448 if (input[startOfName] == '[') {
449 if (nestingCount <= 0)
450 break;
451 else
452 nestingCount--;
453 }
454 if (input[startOfName] == ']')
455 nestingCount++;
456 }
457 if (startOfName < 0 || nestingCount > 0)
458 break;
459
460 int endOfLink = input.indexOf(')', endOfName);
461 int newline = input.indexOf('\n', endOfName);
462 if (endOfLink > endOfName && (newline == -1 || endOfLink < newline)) {
463 auto name = input.mid(startOfName + 1, endOfName - startOfName - 1);
464 name.remove(QChar(u'\\'), Qt::CaseSensitive);
465 input.replace(startOfName, endOfLink - startOfName + 1, name);
466 replaced = true;
467 }
468 } while (replaced);
469
470 return input;
471 }
472
473 mtx::common::Relations
474 InputBar::generateRelations() const
475 {
476 mtx::common::Relations relations;
477 if (!room->thread().isEmpty()) {
478 relations.relations.push_back(
479 {mtx::common::RelationType::Thread, room->thread().toStdString()});
480 if (room->reply().isEmpty())
481 relations.relations.push_back(
482 {mtx::common::RelationType::InReplyTo,
483 threadFallbackEventId(room->roomId().toStdString(), room->thread().toStdString()),
484 std::nullopt,
485 true});
486 }
487 if (!room->reply().isEmpty()) {
488 relations.relations.push_back(
489 {mtx::common::RelationType::InReplyTo, room->reply().toStdString()});
490 }
491 if (!room->edit().isEmpty()) {
492 relations.relations.push_back(
493 {mtx::common::RelationType::Replace, room->edit().toStdString()});
494 }
495 return relations;
496 }
497
498 mtx::common::Mentions
499 InputBar::generateMentions() const
500 {
501 std::vector<std::string> userMentions;
502 bool atRoom = false;
503 for (const auto &m : std::as_const(mentions_))
504 if (m == u"@room")
505 atRoom = true;
506 else
507 userMentions.push_back(m.toStdString());
508
509 if (!room->reply().isEmpty()) {
510 auto replyToSender =
511 room->dataById(room->reply(), TimelineModel::Roles::UserId, "").toString().toStdString();
512 if (!replyToSender.empty() &&
513 std::ranges::find(userMentions, replyToSender) == userMentions.end()) {
514 userMentions.push_back(replyToSender);
515 }
516 }
517
518 auto mention = mtx::common::Mentions{
519 .user_ids = userMentions,
520 // We use the atRoom from the mentions list to allow suppressing a room mention
521 .room = atRoom,
522 };
523
524 // this->containsAtRoom_ = false;
525 // this->mentions_.clear();
526 // this->mentionTexts_.clear();
527
528 return mention;
529 }
530
531 void
532 InputBar::message(const QString &msg, MarkdownOverride useMarkdown, bool rainbowify)
533 {
534 mtx::events::msg::Text text = {};
535 text.body = msg.trimmed().toStdString();
536
537 if ((ChatPage::instance()->userSettings()->markdown() &&
538 useMarkdown == MarkdownOverride::NOT_SPECIFIED) ||
539 useMarkdown == MarkdownOverride::ON) {
540 text.formatted_body = utils::markdownToHtml(msg, rainbowify).toStdString();
541 // Remove markdown links by completer
542 text.body = replaceMatrixToMarkdownLink(msg.trimmed()).toStdString();
543
544 // Don't send formatted_body, when we don't need to
545 // Specifically, if it includes no html tag and no newlines or
546 // backslashes (which behave differently in formatted bodies). Probably
547 // we forgot something, so this might need to expand at some point.
548 if (text.formatted_body.find('<') == std::string::npos &&
549 text.body.find('\n') == std::string::npos && text.body.find('\\') == std::string::npos)
550 text.formatted_body = "";
551 else
552 text.format = "org.matrix.custom.html";
553 } else if (useMarkdown == MarkdownOverride::CMARK) {
554 // disable all markdown extensions
555 text.formatted_body = utils::markdownToHtml(msg, rainbowify, true).toStdString();
556 // keep everything as it was
557 text.body = msg.trimmed().toStdString();
558
559 // always send formatted
560 text.format = "org.matrix.custom.html";
561 }
562
563 text.mentions = generateMentions();
564 text.relations = generateRelations();
565
566 room->sendMessageEvent(text, mtx::events::EventType::RoomMessage);
567 }
568
569 void
570 InputBar::emote(const QString &msg, bool rainbowify)
571 {
572 auto html = utils::markdownToHtml(msg, rainbowify);
573
574 mtx::events::msg::Emote emote;
575 emote.body = msg.trimmed().toStdString();
576
577 if (html != msg.trimmed().toHtmlEscaped() && ChatPage::instance()->userSettings()->markdown()) {
578 emote.formatted_body = html.toStdString();
579 emote.format = "org.matrix.custom.html";
580 // Remove markdown links by completer
581 emote.body = replaceMatrixToMarkdownLink(msg.trimmed()).toStdString();
582 }
583
584 emote.mentions = generateMentions();
585 emote.relations = generateRelations();
586
587 room->sendMessageEvent(emote, mtx::events::EventType::RoomMessage);
588 }
589
590 void
591 InputBar::notice(const QString &msg, bool rainbowify)
592 {
593 auto html = utils::markdownToHtml(msg, rainbowify);
594
595 mtx::events::msg::Notice notice;
596 notice.body = msg.trimmed().toStdString();
597
598 if (html != msg.trimmed().toHtmlEscaped() && ChatPage::instance()->userSettings()->markdown()) {
599 notice.formatted_body = html.toStdString();
600 notice.format = "org.matrix.custom.html";
601 // Remove markdown links by completer
602 notice.body = replaceMatrixToMarkdownLink(msg.trimmed()).toStdString();
603 }
604
605 notice.mentions = generateMentions();
606 notice.relations = generateRelations();
607
608 room->sendMessageEvent(notice, mtx::events::EventType::RoomMessage);
609 }
610
611 void
612 InputBar::confetti(const QString &body, bool rainbowify)
613 {
614 auto html = utils::markdownToHtml(body, rainbowify);
615
616 mtx::events::msg::ElementEffect confetti;
617 confetti.msgtype = "nic.custom.confetti";
618 confetti.body = body.trimmed().toStdString();
619
620 if (html != body.trimmed().toHtmlEscaped() &&
621 ChatPage::instance()->userSettings()->markdown()) {
622 confetti.formatted_body = html.toStdString();
623 confetti.format = "org.matrix.custom.html";
624 // Remove markdown links by completer
625 confetti.body = replaceMatrixToMarkdownLink(body.trimmed()).toStdString();
626 }
627
628 confetti.mentions = generateMentions();
629 confetti.relations = generateRelations();
630
631 room->sendMessageEvent(confetti, mtx::events::EventType::RoomMessage);
632 }
633
634 void
635 InputBar::rainfall(const QString &body)
636 {
637 auto html = utils::markdownToHtml(body);
638
639 mtx::events::msg::Unknown rain;
640 rain.msgtype = "io.element.effect.rainfall";
641 rain.body = body.trimmed().toStdString();
642
643 if (html != body.trimmed().toHtmlEscaped() &&
644 ChatPage::instance()->userSettings()->markdown()) {
645 nlohmann::json j;
646 j["formatted_body"] = html.toStdString();
647 j["format"] = "org.matrix.custom.html";
648 rain.content = j.dump();
649 // Remove markdown links by completer
650 rain.body = replaceMatrixToMarkdownLink(body.trimmed()).toStdString();
651 }
652
653 rain.mentions = generateMentions();
654 rain.relations = generateRelations();
655
656 room->sendMessageEvent(rain, mtx::events::EventType::RoomMessage);
657 }
658
659 void
660 InputBar::customMsgtype(const QString &msgtype, const QString &body)
661 {
662 auto html = utils::markdownToHtml(body);
663
664 mtx::events::msg::Unknown msg;
665 msg.msgtype = msgtype.toStdString();
666 msg.body = body.trimmed().toStdString();
667
668 if (html != body.trimmed().toHtmlEscaped() &&
669 ChatPage::instance()->userSettings()->markdown()) {
670 nlohmann::json j;
671 j["formatted_body"] = html.toStdString();
672 j["format"] = "org.matrix.custom.html";
673 msg.content = j.dump();
674 // Remove markdown links by completer
675 msg.body = replaceMatrixToMarkdownLink(body.trimmed()).toStdString();
676 }
677
678 msg.mentions = generateMentions();
679 msg.relations = generateRelations();
680
681 room->sendMessageEvent(msg, mtx::events::EventType::RoomMessage);
682 }
683
684 void
685 InputBar::image(const QString &filename,
686 const std::optional<mtx::crypto::EncryptedFile> &file,
687 const QString &url,
688 const QString &mime,
689 uint64_t dsize,
690 const QSize &dimensions,
691 const std::optional<mtx::crypto::EncryptedFile> &thumbnailEncryptedFile,
692 const QString &thumbnailUrl,
693 uint64_t thumbnailSize,
694 const QSize &thumbnailDimensions,
695 const QString &blurhash)
696 {
697 mtx::events::msg::Image image;
698 image.info.mimetype = mime.toStdString();
699 image.info.size = dsize;
700 image.info.blurhash = blurhash.toStdString();
701 image.body = filename.toStdString();
702 image.info.h = dimensions.height();
703 image.info.w = dimensions.width();
704
705 if (file)
706 image.file = file;
707 else
708 image.url = url.toStdString();
709
710 if (!thumbnailUrl.isEmpty()) {
711 if (thumbnailEncryptedFile)
712 image.info.thumbnail_file = thumbnailEncryptedFile;
713 else
714 image.info.thumbnail_url = thumbnailUrl.toStdString();
715
716 image.info.thumbnail_info.h = thumbnailDimensions.height();
717 image.info.thumbnail_info.w = thumbnailDimensions.width();
718 image.info.thumbnail_info.size = thumbnailSize;
719 image.info.thumbnail_info.mimetype = "image/png";
720 }
721
722 image.mentions = generateMentions();
723 image.relations = generateRelations();
724
725 room->sendMessageEvent(image, mtx::events::EventType::RoomMessage);
726 }
727
728 void
729 InputBar::file(const QString &filename,
730 const std::optional<mtx::crypto::EncryptedFile> &encryptedFile,
731 const QString &url,
732 const QString &mime,
733 uint64_t dsize)
734 {
735 mtx::events::msg::File file;
736 file.info.mimetype = mime.toStdString();
737 file.info.size = dsize;
738 file.body = filename.toStdString();
739
740 if (encryptedFile)
741 file.file = encryptedFile;
742 else
743 file.url = url.toStdString();
744
745 file.mentions = generateMentions();
746 file.relations = generateRelations();
747
748 room->sendMessageEvent(file, mtx::events::EventType::RoomMessage);
749 }
750
751 void
752 InputBar::audio(const QString &filename,
753 const std::optional<mtx::crypto::EncryptedFile> &file,
754 const QString &url,
755 const QString &mime,
756 uint64_t dsize,
757 uint64_t duration)
758 {
759 mtx::events::msg::Audio audio;
760 audio.info.mimetype = mime.toStdString();
761 audio.info.size = dsize;
762 audio.body = filename.toStdString();
763 audio.url = url.toStdString();
764
765 if (duration > 0)
766 audio.info.duration = duration;
767
768 if (file)
769 audio.file = file;
770 else
771 audio.url = url.toStdString();
772
773 audio.mentions = generateMentions();
774 audio.relations = generateRelations();
775
776 room->sendMessageEvent(audio, mtx::events::EventType::RoomMessage);
777 }
778
779 void
780 InputBar::video(const QString &filename,
781 const std::optional<mtx::crypto::EncryptedFile> &file,
782 const QString &url,
783 const QString &mime,
784 uint64_t dsize,
785 uint64_t duration,
786 const QSize &dimensions,
787 const std::optional<mtx::crypto::EncryptedFile> &thumbnailEncryptedFile,
788 const QString &thumbnailUrl,
789 uint64_t thumbnailSize,
790 const QSize &thumbnailDimensions,
791 const QString &blurhash)
792 {
793 mtx::events::msg::Video video;
794 video.info.mimetype = mime.toStdString();
795 video.info.size = dsize;
796 video.info.blurhash = blurhash.toStdString();
797 video.body = filename.toStdString();
798
799 if (duration > 0)
800 video.info.duration = duration;
801 if (dimensions.isValid()) {
802 video.info.h = dimensions.height();
803 video.info.w = dimensions.width();
804 }
805
806 if (file)
807 video.file = file;
808 else
809 video.url = url.toStdString();
810
811 if (!thumbnailUrl.isEmpty()) {
812 if (thumbnailEncryptedFile)
813 video.info.thumbnail_file = thumbnailEncryptedFile;
814 else
815 video.info.thumbnail_url = thumbnailUrl.toStdString();
816
817 video.info.thumbnail_info.h = thumbnailDimensions.height();
818 video.info.thumbnail_info.w = thumbnailDimensions.width();
819 video.info.thumbnail_info.size = thumbnailSize;
820 video.info.thumbnail_info.mimetype = "image/png";
821 }
822
823 video.mentions = generateMentions();
824 video.relations = generateRelations();
825
826 room->sendMessageEvent(video, mtx::events::EventType::RoomMessage);
827 }
828
829 QPair<QString, QString>
830 InputBar::getCommandAndArgs(const QString &currentText) const
831 {
832 if (!currentText.startsWith('/'))
833 return {{}, currentText};
834
835 static QRegularExpression spaceRegex(QStringLiteral("\\s"));
836
837 int command_end = currentText.indexOf(spaceRegex);
838 if (command_end == -1)
839 command_end = currentText.size();
840 auto name = currentText.mid(1, command_end - 1);
841 auto args = currentText.mid(command_end + 1);
842 if (name.isEmpty() || name == QLatin1String("/")) {
843 return {{}, currentText};
844 } else {
845 return {name, args};
846 }
847 }
848
849 void
850 InputBar::sticker(QStringList descriptor)
851 {
852 if (descriptor.size() != 3)
853 return;
854
855 auto originalPacks = cache::client()->getImagePacks(room->roomId().toStdString(), true);
856
857 auto source_room = descriptor[0].toStdString();
858 auto state_key = descriptor[1].toStdString();
859 auto short_code = descriptor[2].toStdString();
860
861 for (auto &pack : originalPacks) {
862 if (pack.source_room == source_room && pack.state_key == state_key &&
863 pack.pack.images.contains(short_code)) {
864 auto img = pack.pack.images.at(short_code);
865
866 mtx::events::msg::StickerImage sticker{};
867 sticker.info = img.info.value_or(mtx::common::ImageInfo{});
868 sticker.url = img.url;
869 sticker.body = img.body.empty() ? short_code : img.body;
870
871 // workaround for https://github.com/vector-im/element-ios/issues/2353
872 sticker.info.thumbnail_url = sticker.url;
873 sticker.info.thumbnail_info.mimetype = sticker.info.mimetype;
874 sticker.info.thumbnail_info.size = sticker.info.size;
875 sticker.info.thumbnail_info.h = sticker.info.h;
876 sticker.info.thumbnail_info.w = sticker.info.w;
877
878 sticker.mentions = generateMentions();
879 sticker.relations = generateRelations();
880
881 room->sendMessageEvent(sticker, mtx::events::EventType::Sticker);
882 break;
883 }
884 }
885 }
886
887 bool
888 InputBar::command(const QString &command, QString args)
889 {
890 if (command == QLatin1String("me")) {
891 emote(args, false);
892 } else if (command == QLatin1String("react")) {
893 auto eventId = room->reply();
894 if (!eventId.isEmpty())
895 reaction(eventId, args.trimmed());
896 } else if (command == QLatin1String("join")) {
897 ChatPage::instance()->joinRoom(args.section(' ', 0, 0), args.section(' ', 1, -1));
898 } else if (command == QLatin1String("knock")) {
899 ChatPage::instance()->knockRoom(args.section(' ', 0, 0), args.section(' ', 1, -1));
900 } else if (command == QLatin1String("part") || command == QLatin1String("leave")) {
901 ChatPage::instance()->timelineManager()->openLeaveRoomDialog(room->roomId(), args);
902 } else if (command == QLatin1String("invite")) {
903 ChatPage::instance()->inviteUser(
904 room->roomId(), args.section(' ', 0, 0), args.section(' ', 1, -1));
905 } else if (command == QLatin1String("kick")) {
906 if (args.startsWith('@')) {
907 ChatPage::instance()->kickUser(
908 room->roomId(), args.section(' ', 0, 0), args.section(' ', 1, -1));
909 } else if (auto reply = room->reply(); !reply.isEmpty()) {
910 auto replySender =
911 room->dataById(room->reply(), TimelineModel::Roles::UserId, "").toString();
912 if (!replySender.isEmpty()) {
913 ChatPage::instance()->kickUser(room->roomId(), replySender, args);
914 }
915 }
916 } else if (command == QLatin1String("ban")) {
917 if (args.startsWith('@')) {
918 ChatPage::instance()->banUser(
919 room->roomId(), args.section(' ', 0, 0), args.section(' ', 1, -1));
920 } else if (auto reply = room->reply(); !reply.isEmpty()) {
921 auto replySender =
922 room->dataById(room->reply(), TimelineModel::Roles::UserId, "").toString();
923 if (!replySender.isEmpty()) {
924 ChatPage::instance()->banUser(room->roomId(), replySender, args);
925 }
926 }
927 } else if (command == QLatin1String("unban")) {
928 if (args.startsWith('@')) {
929 ChatPage::instance()->unbanUser(
930 room->roomId(), args.section(' ', 0, 0), args.section(' ', 1, -1));
931 } else if (auto reply = room->reply(); !reply.isEmpty()) {
932 auto replySender =
933 room->dataById(room->reply(), TimelineModel::Roles::UserId, "").toString();
934 if (!replySender.isEmpty()) {
935 ChatPage::instance()->unbanUser(room->roomId(), replySender, args);
936 }
937 }
938 } else if (command == QLatin1String("redact")) {
939 if (args.startsWith('@')) {
940 room->redactAllFromUser(args.section(' ', 0, 0), args.section(' ', 1, -1));
941 } else if (args.startsWith('$')) {
942 room->redactEvent(args.section(' ', 0, 0), args.section(' ', 1, -1));
943 } else if (auto reply = room->reply(); !reply.isEmpty()) {
944 room->redactEvent(reply, args);
945 }
946 } else if (command == QLatin1String("roomnick")) {
947 mtx::events::state::Member member;
948 member.display_name = args.toStdString();
949 member.avatar_url =
950 cache::avatarUrl(room->roomId(),
951 QString::fromStdString(http::client()->user_id().to_string()))
952 .toStdString();
953 member.membership = mtx::events::state::Membership::Join;
954
955 http::client()->send_state_event(
956 room->roomId().toStdString(),
957 http::client()->user_id().to_string(),
958 member,
959 [](const mtx::responses::EventId &, mtx::http::RequestErr err) {
960 if (err)
961 nhlog::net()->error("Failed to set room displayname: {}",
962 err->matrix_error.error);
963 });
964 } else if (command == QLatin1String("shrug")) {
965 message("¯\\\\\\_(ツ)\\_/¯" + (args.isEmpty() ? QLatin1String("") : " " + args));
966 } else if (command == QLatin1String("fliptable")) {
967 message(QStringLiteral("(╯°□°)╯︵ ┻━┻"));
968 } else if (command == QLatin1String("unfliptable")) {
969 message(QStringLiteral(" ┯━┯╭( º _ º╭)"));
970 } else if (command == QLatin1String("sovietflip")) {
971 message(QStringLiteral("ノ┬─┬ノ ︵ ( \\o°o)\\"));
972 } else if (command == QLatin1String("clear-timeline")) {
973 room->clearTimeline();
974 } else if (command == QLatin1String("reset-state")) {
975 room->resetState();
976 } else if (command == QLatin1String("rotate-megolm-session")) {
977 cache::dropOutboundMegolmSession(room->roomId().toStdString());
978 } else if (command == QLatin1String("md")) {
979 message(args, MarkdownOverride::ON);
980 } else if (command == QLatin1String("cmark")) {
981 message(args, MarkdownOverride::CMARK);
982 } else if (command == QLatin1String("plain")) {
983 message(args, MarkdownOverride::OFF);
984 } else if (command == QLatin1String("rainbow")) {
985 message(args, MarkdownOverride::ON, true);
986 } else if (command == QLatin1String("rainbowme")) {
987 emote(args, true);
988 } else if (command == QLatin1String("notice")) {
989 notice(args, false);
990 } else if (command == QLatin1String("rainbownotice")) {
991 notice(args, true);
992 } else if (command == QLatin1String("confetti")) {
993 confetti(args, false);
994 } else if (command == QLatin1String("rainbowconfetti")) {
995 confetti(args, true);
996 } else if (command == QLatin1String("rainfall")) {
997 rainfall(args);
998 } else if (command == QLatin1String("msgtype")) {
999 customMsgtype(args.section(' ', 0, 0), args.section(' ', 1, -1));
1000 } else if (command == QLatin1String("glitch")) {
1001 message(utils::glitchText(args));
1002 } else if (command == QLatin1String("gradualglitch")) {
1003 message(utils::graduallyGlitchText(args));
1004 } else if (command == QLatin1String("goto")) {
1005 // Goto has three different modes:
1006 // 1 - Going directly to a given event ID
1007 if (args[0] == '$') {
1008 room->showEvent(args);
1009 return true;
1010 }
1011 // 2 - Going directly to a given message index
1012 if (args[0] >= '0' && args[0] <= '9') {
1013 room->showEvent(args);
1014 return true;
1015 }
1016 // 3 - Matrix URI handler, as if you clicked the URI
1017 if (ChatPage::instance()->handleMatrixUri(args)) {
1018 return true;
1019 }
1020 nhlog::net()->error("Could not resolve goto: {}", args.toStdString());
1021 } else if (command == QLatin1String("converttodm")) {
1022 utils::markRoomAsDirect(this->room->roomId(),
1023 cache::getMembers(this->room->roomId().toStdString(), 0, -1));
1024 } else if (command == QLatin1String("converttoroom")) {
1025 utils::removeDirectFromRoom(this->room->roomId());
1026 } else if (command == QLatin1String("ignore")) {
1027 this->toggleIgnore(args.trimmed(), true);
1028 } else if (command == QLatin1String("unignore")) {
1029 this->toggleIgnore(args.trimmed(), false);
1030 } else if (command == QLatin1String("blockinvites")) {
1031 this->toggleInvitePermission(args.trimmed(), true);
1032 } else if (command == QLatin1String("allowinvites")) {
1033 this->toggleInvitePermission(args.trimmed(), false);
1034 } else {
1035 return false;
1036 }
1037
1038 return true;
1039 }
1040
1041 void
1042 InputBar::toggleIgnore(const QString &user, const bool ignored)
1043 {
1044 if (!user.startsWith(u"@")) {
1045 MainWindow::instance()->showNotification(
1046 tr("You need to pass a valid mxid when ignoring a user. '%1' is not a valid userid.")
1047 .arg(user));
1048 return;
1049 }
1050
1051 UserProfile *profile = new UserProfile(QString(), user, TimelineViewManager::instance());
1052 connect(profile, &UserProfile::failedToFetchProfile, [user, profile] {
1053 MainWindow::instance()->showNotification(tr("Failed to fetch user %1").arg(user));
1054 profile->deleteLater();
1055 });
1056
1057 connect(
1058 profile, &UserProfile::globalUsernameRetrieved, [profile, ignored](const QString &user_id) {
1059 Q_UNUSED(user_id)
1060 profile->setIgnored(ignored);
1061 profile->deleteLater();
1062 });
1063 }
1064
1065 void
1066 InputBar::toggleInvitePermission(const QString &id, bool block)
1067 {
1068 mtx::events::account_data::nheko_extensions::InvitePermissions permissions;
1069 if (auto ev = cache::client()->getAccountData(mtx::events::EventType::NhekoInvitePermissions)) {
1070 permissions = std::get<mtx::events::AccountDataEvent<
1071 mtx::events::account_data::nheko_extensions::InvitePermissions>>(*ev)
1072 .content;
1073 }
1074
1075 auto idstr = id.toStdString();
1076
1077 if (id.startsWith("matrix:") || id.startsWith("https://matrix.to")) {
1078 auto m = utils::parseMatrixUri(id);
1079 if (m) {
1080 idstr = m->mxid1.toStdString();
1081 } else {
1082 return;
1083 }
1084 }
1085
1086 if (idstr.starts_with("@")) {
1087 if (block) {
1088 permissions.user_allow.erase(idstr);
1089 permissions.user_deny.emplace(idstr, "{}");
1090 } else {
1091 permissions.user_deny.erase(idstr);
1092 permissions.user_allow.emplace(idstr, "{}");
1093 }
1094 } else if (idstr.starts_with("!")) {
1095 if (block) {
1096 permissions.room_allow.erase(idstr);
1097 permissions.room_deny.emplace(idstr, "{}");
1098 } else {
1099 permissions.room_deny.erase(idstr);
1100 permissions.room_allow.emplace(idstr, "{}");
1101 }
1102 } else if (idstr == "all" || idstr == "default") {
1103 if (block)
1104 permissions.default_ = "deny";
1105 else
1106 permissions.default_ = "allow";
1107 } else if (!idstr.starts_with("#")) {
1108 if (block) {
1109 permissions.server_allow.erase(idstr);
1110 permissions.server_deny.emplace(idstr, "{}");
1111 } else {
1112 permissions.server_deny.erase(idstr);
1113 permissions.server_allow.emplace(idstr, "{}");
1114 }
1115 }
1116
1117 http::client()->put_account_data(permissions, [](mtx::http::RequestErr err) {
1118 if (err) {
1119 nhlog::ui()->error("Failed to update invite permissions: {}", *err);
1120 }
1121 });
1122
1123 auto invites = cache::client()->invites();
1124
1125 for (const auto &[roomid, info] : invites.asKeyValueRange()) {
1126 auto roomid_ = roomid.toStdString();
1127 auto self =
1128 cache::client()->getInviteMember(roomid_, http::client()->user_id().to_string());
1129 if (!self->inviter.empty()) {
1130 if (!permissions.invite_allowed(roomid_, self->inviter)) {
1131 ChatPage::instance()->leaveRoom(roomid, "");
1132 }
1133 }
1134 }
1135 }
1136
1137 MediaUpload::MediaUpload(std::unique_ptr<QIODevice> source_,
1138 const QString &mimetype,
1139 const QString &originalFilename,
1140 bool encrypt,
1141 QObject *parent)
1142 : QObject(parent)
1143 , source(std::move(source_))
1144 , mimetype_(std::move(mimetype))
1145 , originalFilename_(QFileInfo(originalFilename).fileName())
1146 , encrypt_(encrypt)
1147 {
1148 mimeClass_ = mimetype_.left(mimetype_.indexOf(u'/'));
1149
1150 if (!source->isOpen())
1151 source->open(QIODevice::ReadOnly);
1152
1153 data = source->readAll();
1154 source->reset();
1155
1156 if (!data.size()) {
1157 nhlog::ui()->warn("Attempted to upload zero-byte file?! Mimetype {}, filename {}",
1158 mimetype_.toStdString(),
1159 originalFilename_.toStdString());
1160 emit uploadFailed(this);
1161 return;
1162 }
1163
1164 nhlog::ui()->debug("Mime: {}", mimetype_.toStdString());
1165 if (mimeClass_ == u"image") {
1166 QImage img = utils::readImage(data);
1167 setThumbnail(img.scaled(
1168 std::min(800, img.width()), std::min(800, img.height()), Qt::KeepAspectRatioByExpanding));
1169
1170 dimensions_ = img.size();
1171 if (img.height() > 200 && img.width() > 360)
1172 img = img.scaled(360, 200, Qt::KeepAspectRatioByExpanding);
1173 std::vector<unsigned char> data_;
1174 for (int y = 0; y < img.height(); y++) {
1175 for (int x = 0; x < img.width(); x++) {
1176 auto p = img.pixel(x, y);
1177 data_.push_back(static_cast<unsigned char>(qRed(p)));
1178 data_.push_back(static_cast<unsigned char>(qGreen(p)));
1179 data_.push_back(static_cast<unsigned char>(qBlue(p)));
1180 }
1181 }
1182 blurhash_ =
1183 QString::fromStdString(blurhash::encode(data_.data(), img.width(), img.height(), 4, 3));
1184 } else if (mimeClass_ == u"video" || mimeClass_ == u"audio") {
1185 auto mediaPlayer = new QMediaPlayer(this);
1186 mediaPlayer->setAudioOutput(nullptr);
1187
1188 if (mimeClass_ == u"video") {
1189 auto newSurface = new QVideoSink(this);
1190 connect(newSurface,
1191 &QVideoSink::videoFrameChanged,
1192 this,
1193 [this, mediaPlayer](const QVideoFrame &frame) {
1194 QImage img = frame.toImage();
1195 if (img.size().isEmpty())
1196 return;
1197
1198 mediaPlayer->stop();
1199
1200 auto orientation =
1201 mediaPlayer->metaData().value(QMediaMetaData::Orientation).toInt();
1202 if (orientation == 90 || orientation == 270 || orientation == 180) {
1203 img = img.transformed(QTransform().rotate(orientation),
1204 Qt::SmoothTransformation);
1205 }
1206
1207 nhlog::ui()->debug("Got image {}x{}", img.width(), img.height());
1208
1209 this->setThumbnail(img);
1210
1211 if (!dimensions_.isValid())
1212 this->dimensions_ = img.size();
1213
1214 if (img.height() > 200 && img.width() > 360)
1215 img = img.scaled(360, 200, Qt::KeepAspectRatioByExpanding);
1216 std::vector<unsigned char> data_;
1217 for (int y = 0; y < img.height(); y++) {
1218 for (int x = 0; x < img.width(); x++) {
1219 auto p = img.pixel(x, y);
1220 data_.push_back(static_cast<unsigned char>(qRed(p)));
1221 data_.push_back(static_cast<unsigned char>(qGreen(p)));
1222 data_.push_back(static_cast<unsigned char>(qBlue(p)));
1223 }
1224 }
1225 blurhash_ = QString::fromStdString(
1226 blurhash::encode(data_.data(), img.width(), img.height(), 4, 3));
1227 });
1228 mediaPlayer->setVideoOutput(newSurface);
1229 }
1230
1231 connect(mediaPlayer,
1232 &QMediaPlayer::errorOccurred,
1233 this,
1234 [](QMediaPlayer::Error error, QString errorString) {
1235 nhlog::ui()->debug("Media player error {} and errorStr {}",
1236 static_cast<int>(error),
1237 errorString.toStdString());
1238 });
1239 connect(mediaPlayer,
1240 &QMediaPlayer::mediaStatusChanged,
1241 [mediaPlayer](QMediaPlayer::MediaStatus status) {
1242 nhlog::ui()->debug("Media player status {} and error {}",
1243 static_cast<int>(status),
1244 static_cast<int>(mediaPlayer->error()));
1245 });
1246 connect(mediaPlayer, &QMediaPlayer::metaDataChanged, this, [this, mediaPlayer]() {
1247 nhlog::ui()->debug("Got metadata {}");
1248
1249 if (mediaPlayer->duration() > 0)
1250 this->duration_ = mediaPlayer->duration();
1251
1252 auto dimensions = mediaPlayer->metaData().value(QMediaMetaData::Resolution).toSize();
1253 if (!dimensions.isEmpty()) {
1254 dimensions_ = dimensions;
1255 auto orientation =
1256 mediaPlayer->metaData().value(QMediaMetaData::Orientation).toInt();
1257 if (orientation == 90 || orientation == 270) {
1258 dimensions_.transpose();
1259 }
1260 }
1261 });
1262 connect(
1263 mediaPlayer, &QMediaPlayer::durationChanged, this, [this, mediaPlayer](qint64 duration) {
1264 if (duration > 0) {
1265 this->duration_ = mediaPlayer->duration();
1266 if (mimeClass_ == u"audio")
1267 mediaPlayer->stop();
1268 }
1269 nhlog::ui()->debug("Duration changed {}", duration);
1270 });
1271
1272 auto originalFile = qobject_cast<QFile *>(source.get());
1273
1274 mediaPlayer->setSourceDevice(
1275 source.get(), QUrl(originalFile ? originalFile->fileName() : originalFilename_));
1276
1277 mediaPlayer->play();
1278 }
1279 }
1280
1281 void
1282 MediaUpload::startUpload()
1283 {
1284 if (!thumbnail_.isNull() && thumbnailUrl_.isEmpty()) {
1285 QByteArray ba;
1286 QBuffer buffer(&ba);
1287 buffer.open(QIODevice::WriteOnly);
1288 thumbnail_.save(&buffer, "PNG", 0);
1289 if (type() == MediaType::Image && ba.size() >= (data.size() - data.size() / 10)) {
1290 nhlog::ui()->info(
1291 "Thumbnail is not a lot smaller than original image, not uploading it");
1292 nhlog::ui()->debug(
1293 "\n Image size: {:9d}\nThumbnail size: {:9d}", data.size(), ba.size());
1294 } else {
1295 auto payload = std::string(ba.data(), ba.size());
1296 if (encrypt_) {
1297 mtx::crypto::BinaryBuf buf;
1298 std::tie(buf, thumbnailEncryptedFile) =
1299 mtx::crypto::encrypt_file(std::move(payload));
1300 payload = mtx::crypto::to_string(buf);
1301 }
1302 thumbnailSize_ = payload.size();
1303
1304 http::client()->upload(
1305 payload,
1306 encryptedFile ? "application/octet-stream" : "image/png",
1307 "",
1308 [this](const mtx::responses::ContentURI &res, mtx::http::RequestErr err) mutable {
1309 if (err) {
1310 emit ChatPage::instance()->showNotification(
1311 tr("Failed to upload media. Please try again."));
1312 nhlog::net()->warn("failed to upload media: {} {} ({})",
1313 err->matrix_error.error,
1314 to_string(err->matrix_error.errcode),
1315 static_cast<int>(err->status_code));
1316 thumbnail_ = QImage();
1317 startUpload();
1318 return;
1319 }
1320
1321 thumbnailUrl_ = QString::fromStdString(res.content_uri);
1322 if (thumbnailEncryptedFile)
1323 thumbnailEncryptedFile->url = res.content_uri;
1324
1325 startUpload();
1326 });
1327 return;
1328 }
1329 }
1330
1331 auto payload = std::string(data.data(), data.size());
1332 if (encrypt_) {
1333 mtx::crypto::BinaryBuf buf;
1334 std::tie(buf, encryptedFile) = mtx::crypto::encrypt_file(std::move(payload));
1335 payload = mtx::crypto::to_string(buf);
1336 }
1337 size_ = payload.size();
1338
1339 http::client()->upload(
1340 payload,
1341 encryptedFile ? "application/octet-stream" : mimetype_.toStdString(),
1342 encrypt_ ? "" : originalFilename_.toStdString(),
1343 [this](const mtx::responses::ContentURI &res, mtx::http::RequestErr err) mutable {
1344 if (err) {
1345 emit ChatPage::instance()->showNotification(
1346 tr("Failed to upload media. Please try again."));
1347 nhlog::net()->warn("failed to upload media: {} {} ({})",
1348 err->matrix_error.error,
1349 to_string(err->matrix_error.errcode),
1350 static_cast<int>(err->status_code));
1351 emit uploadFailed(this);
1352 return;
1353 }
1354
1355 auto url = QString::fromStdString(res.content_uri);
1356 if (encryptedFile)
1357 encryptedFile->url = res.content_uri;
1358
1359 emit uploadComplete(this, std::move(url));
1360 });
1361 }
1362
1363 void
1364 InputBar::finalizeUpload(MediaUpload *upload, const QString &url)
1365 {
1366 auto mime = upload->mimetype();
1367 auto filename = upload->filename();
1368 auto mimeClass = upload->mimeClass();
1369 auto size = upload->size();
1370 auto encryptedFile = upload->encryptedFile_();
1371 if (mimeClass == u"image")
1372 image(filename,
1373 encryptedFile,
1374 url,
1375 mime,
1376 size,
1377 upload->dimensions(),
1378 upload->thumbnailEncryptedFile_(),
1379 upload->thumbnailUrl(),
1380 upload->thumbnailSize(),
1381 upload->thumbnailImg().size(),
1382 upload->blurhash());
1383 else if (mimeClass == u"audio")
1384 audio(filename, encryptedFile, url, mime, size, upload->duration());
1385 else if (mimeClass == u"video")
1386 video(filename,
1387 encryptedFile,
1388 url,
1389 mime,
1390 size,
1391 upload->duration(),
1392 upload->dimensions(),
1393 upload->thumbnailEncryptedFile_(),
1394 upload->thumbnailUrl(),
1395 upload->thumbnailSize(),
1396 upload->thumbnailImg().size(),
1397 upload->blurhash());
1398 else
1399 file(filename, encryptedFile, url, mime, size);
1400
1401 removeRunUpload(upload);
1402 }
1403
1404 void
1405 InputBar::removeRunUpload(MediaUpload *upload)
1406 {
1407 auto it = std::find_if(runningUploads.begin(),
1408 runningUploads.end(),
1409 [upload](const UploadHandle &h) { return h.get() == upload; });
1410 if (it != runningUploads.end())
1411 runningUploads.erase(it);
1412
1413 if (runningUploads.empty())
1414 setUploading(false);
1415 else
1416 runningUploads.front()->startUpload();
1417 }
1418
1419 void
1420 InputBar::startUploadFromPath(const QString &path)
1421 {
1422 if (path.isEmpty())
1423 return;
1424
1425 auto file = std::make_unique<QFile>(path);
1426
1427 if (!file->open(QIODevice::ReadOnly)) {
1428 nhlog::ui()->warn(
1429 "Failed to open file ({}): {}", path.toStdString(), file->errorString().toStdString());
1430 return;
1431 }
1432
1433 QMimeDatabase db;
1434 auto mime = db.mimeTypeForFileNameAndData(path, file.get());
1435
1436 startUpload(std::move(file), path, mime.name());
1437 }
1438
1439 void
1440 InputBar::startUploadFromMimeData(const QMimeData &source, const QString &format)
1441 {
1442 auto file = std::make_unique<QBuffer>();
1443 file->setData(source.data(format));
1444
1445 if (!file->open(QIODevice::ReadOnly)) {
1446 nhlog::ui()->warn("Failed to open buffer: {}", file->errorString().toStdString());
1447 return;
1448 }
1449
1450 QMimeDatabase db;
1451 auto mime = db.mimeTypeForName(format);
1452 auto suffix = mime.preferredSuffix();
1453 QString filename = QStringLiteral("clipboard");
1454
1455 startUpload(std::move(file), suffix.isEmpty() ? filename : (filename + "." + suffix), format);
1456 }
1457 void
1458 InputBar::startUpload(std::unique_ptr<QIODevice> dev, const QString &orgPath, const QString &format)
1459 {
1460 auto upload =
1461 UploadHandle(new MediaUpload(std::move(dev), format, orgPath, room->isEncrypted(), this));
1462 connect(upload.get(), &MediaUpload::uploadComplete, this, &InputBar::finalizeUpload);
1463 // TODO(Nico): Show a retry option
1464 connect(upload.get(), &MediaUpload::uploadFailed, this, [this](MediaUpload *up) {
1465 ChatPage::instance()->showNotification(tr("Upload of '%1' failed").arg(up->filename()));
1466 removeRunUpload(up);
1467 });
1468
1469 unconfirmedUploads.push_back(std::move(upload));
1470
1471 nhlog::ui()->debug("Uploads {}", unconfirmedUploads.size());
1472 emit uploadsChanged();
1473 }
1474
1475 void
1476 InputBar::acceptUploads()
1477 {
1478 if (unconfirmedUploads.empty())
1479 return;
1480
1481 bool wasntRunning = runningUploads.empty();
1482 runningUploads.insert(runningUploads.end(),
1483 std::make_move_iterator(unconfirmedUploads.begin()),
1484 std::make_move_iterator(unconfirmedUploads.end()));
1485 unconfirmedUploads.clear();
1486 emit uploadsChanged();
1487
1488 if (wasntRunning) {
1489 setUploading(true);
1490 runningUploads.front()->startUpload();
1491 }
1492 }
1493
1494 void
1495 InputBar::declineUploads()
1496 {
1497 unconfirmedUploads.clear();
1498 emit uploadsChanged();
1499 }
1500
1501 QVariantList
1502 InputBar::uploads() const
1503 {
1504 QVariantList l;
1505 l.reserve((int)unconfirmedUploads.size());
1506
1507 for (auto &e : unconfirmedUploads)
1508 l.push_back(QVariant::fromValue(e.get()));
1509 return l;
1510 }
1511
1512 void
1513 InputBar::startTyping()
1514 {
1515 if (!typingRefresh_.isActive()) {
1516 typingRefresh_.start();
1517
1518 if (ChatPage::instance()->userSettings()->typingNotifications()) {
1519 http::client()->start_typing(
1520 room->roomId().toStdString(), 10'000, [](mtx::http::RequestErr err) {
1521 if (err) {
1522 nhlog::net()->warn("failed to send typing notification: {}",
1523 err->matrix_error.error);
1524 }
1525 });
1526 }
1527 }
1528 typingTimeout_.start();
1529 }
1530 void
1531 InputBar::stopTyping()
1532 {
1533 typingRefresh_.stop();
1534 typingTimeout_.stop();
1535
1536 if (!ChatPage::instance()->userSettings()->typingNotifications())
1537 return;
1538
1539 http::client()->stop_typing(room->roomId().toStdString(), [](mtx::http::RequestErr err) {
1540 if (err) {
1541 nhlog::net()->warn("failed to stop typing notifications: {}", err->matrix_error.error);
1542 }
1543 });
1544 }
1545
1546 void
1547 InputBar::reaction(const QString &reactedEvent, const QString &reactionKey)
1548 {
1549 auto reactions = room->reactions(reactedEvent.toStdString());
1550
1551 QString selfReactedEvent;
1552 for (const auto &reaction : reactions) {
1553 if (reactionKey == reaction.key_) {
1554 selfReactedEvent = reaction.selfReactedEvent_;
1555 break;
1556 }
1557 }
1558
1559 if (selfReactedEvent.startsWith(QLatin1String("m")))
1560 return;
1561
1562 // If selfReactedEvent is empty, that means we haven't previously reacted
1563 if (selfReactedEvent.isEmpty()) {
1564 mtx::events::msg::Reaction reaction;
1565 mtx::common::Relation rel;
1566 rel.rel_type = mtx::common::RelationType::Annotation;
1567 rel.event_id = reactedEvent.toStdString();
1568 rel.key = reactionKey.toStdString();
1569 reaction.relations.relations.push_back(rel);
1570
1571 room->sendMessageEvent(reaction, mtx::events::EventType::Reaction);
1572
1573 auto recents = UserSettings::instance()->recentReactions();
1574 if (recents.contains(reactionKey))
1575 recents.removeOne(reactionKey);
1576 else if (recents.size() >= 6)
1577 recents.removeLast();
1578 recents.push_front(reactionKey);
1579 UserSettings::instance()->setRecentReactions(recents);
1580 // Otherwise, we have previously reacted and the reaction should be redacted
1581 } else {
1582 room->redactEvent(selfReactedEvent);
1583 }
1584 }
1585
1586 #include "moc_InputBar.cpp"