| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include "MxcMediaProxy.h" |
| 6 | |
| 7 | #include <QDir> |
| 8 | #include <QFile> |
| 9 | #include <QFileInfo> |
| 10 | #include <QMediaMetaData> |
| 11 | #include <QMediaPlayer> |
| 12 | #include <QMimeDatabase> |
| 13 | #include <QStandardPaths> |
| 14 | #include <QUrl> |
| 15 | |
| 16 | #include "ChatPage.h" |
| 17 | #include "EventAccessors.h" |
| 18 | #include "Logging.h" |
| 19 | #include "MatrixClient.h" |
| 20 | #include "timeline/RoomlistModel.h" |
| 21 | #include "timeline/TimelineModel.h" |
| 22 | #include "timeline/TimelineViewManager.h" |
| 23 | |
| 24 | MxcMediaProxy::MxcMediaProxy(QObject *parent) |
| 25 | : QMediaPlayer(parent) |
| 26 | { |
| 27 | connect( |
| 28 | this, &QMediaPlayer::errorOccurred, this, [](QMediaPlayer::Error error, QString errorString) { |
| 29 | nhlog::ui()->debug("Media player error {} and errorStr {}", |
| 30 | static_cast<int>(error), |
| 31 | errorString.toStdString()); |
| 32 | }); |
| 33 | connect( |
| 34 | this, &MxcMediaProxy::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status) { |
| 35 | nhlog::ui()->info("Media player status {} and error {}", |
| 36 | static_cast<int>(status), |
| 37 | static_cast<int>(this->error())); |
| 38 | }); |
| 39 | connect( |
| 40 | this, &MxcMediaProxy::playbackStateChanged, this, [this](QMediaPlayer::PlaybackState status) { |
| 41 | // We only set the output when starting the playback because otherwise the audio device |
| 42 | // lookup takes about 500ms, which causes a lot of stutter... |
| 43 | if (status == QMediaPlayer::PlayingState && !audioOutput()) { |
| 44 | nhlog::ui()->debug("Set audio output"); |
| 45 | auto newOut = new QAudioOutput(this); |
| 46 | newOut->setMuted(muted_); |
| 47 | newOut->setVolume(QAudio::convertVolume( |
| 48 | volume_, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale)); |
| 49 | setAudioOutput(newOut); |
| 50 | } |
| 51 | }); |
| 52 | connect(this, &MxcMediaProxy::metaDataChanged, [this]() { emit orientationChanged(); }); |
| 53 | |
| 54 | connect(ChatPage::instance()->timelineManager()->rooms(), |
| 55 | &RoomlistModel::currentRoomChanged, |
| 56 | this, |
| 57 | &MxcMediaProxy::pause); |
| 58 | } |
| 59 | |
| 60 | int |
| 61 | MxcMediaProxy::orientation() const |
| 62 | { |
| 63 | // nhlog::ui()->debug("metadata: {}", |
| 64 | // availableMetaData().join(QStringLiteral(",")).toStdString()); |
| 65 | auto orientation = metaData().value(QMediaMetaData::Orientation).toInt(); |
| 66 | nhlog::ui()->debug("Video orientation: {}", orientation); |
| 67 | return orientation; |
| 68 | } |
| 69 | |
| 70 | void |
| 71 | MxcMediaProxy::startDownload(bool onlyCached) |
| 72 | { |
| 73 | if (!room_) |
| 74 | return; |
| 75 | if (eventId_.isEmpty()) |
| 76 | return; |
| 77 | |
| 78 | auto event = room_->eventById(eventId_); |
| 79 | if (!event) { |
| 80 | nhlog::ui()->error("Failed to load media for event {}, event not found.", |
| 81 | eventId_.toStdString()); |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | QString mxcUrl = QString::fromStdString(mtx::accessors::url(*event)); |
| 86 | QString mimeType = QString::fromStdString(mtx::accessors::mimetype(*event)); |
| 87 | |
| 88 | auto encryptionInfo = mtx::accessors::file(*event); |
| 89 | |
| 90 | // If the message is a link to a non mxcUrl, don't download it |
| 91 | if (!mxcUrl.startsWith(QLatin1String("mxc://"))) { |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix(); |
| 96 | |
| 97 | const auto url = mxcUrl.toStdString(); |
| 98 | const auto name = QString(mxcUrl).remove(QStringLiteral("mxc://")); |
| 99 | QFileInfo filename(QStringLiteral("%1/media_cache/media/%2.%3") |
| 100 | .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), |
| 101 | QString::fromUtf8(name.toUtf8().toBase64( |
| 102 | QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)), |
| 103 | suffix)); |
| 104 | if (QDir::cleanPath(filename.filePath()) != filename.filePath()) { |
| 105 | nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url); |
| 106 | return; |
| 107 | } |
| 108 | |
| 109 | QDir().mkpath(filename.path()); |
| 110 | |
| 111 | QPointer<MxcMediaProxy> self = this; |
| 112 | |
| 113 | auto processBuffer = [this, encryptionInfo, filename, self, suffix](QIODevice &device) { |
| 114 | if (!self) |
| 115 | return; |
| 116 | |
| 117 | if (encryptionInfo) { |
| 118 | QByteArray ba = device.readAll(); |
| 119 | std::string temp(ba.constData(), ba.size()); |
| 120 | temp = mtx::crypto::to_string(mtx::crypto::decrypt_file(temp, encryptionInfo.value())); |
| 121 | buffer.setData(temp.data(), static_cast<int>(temp.size())); |
| 122 | } else { |
| 123 | buffer.setData(device.readAll()); |
| 124 | } |
| 125 | buffer.open(QIODevice::ReadOnly); |
| 126 | buffer.reset(); |
| 127 | |
| 128 | QTimer::singleShot(0, this, [this, filename] { |
| 129 | nhlog::ui()->info( |
| 130 | "Playing buffer with size: {}, {}", buffer.bytesAvailable(), buffer.isOpen()); |
| 131 | this->setSourceDevice(&buffer, QUrl(filename.fileName())); |
| 132 | emit loadedChanged(); |
| 133 | }); |
| 134 | }; |
| 135 | |
| 136 | if (filename.isReadable()) { |
| 137 | QFile f(filename.filePath()); |
| 138 | if (f.open(QIODevice::ReadOnly)) { |
| 139 | processBuffer(f); |
| 140 | return; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | if (onlyCached) |
| 145 | return; |
| 146 | |
| 147 | http::client()->download(url, |
| 148 | [filename, url, processBuffer](const std::string &data, |
| 149 | const std::string &, |
| 150 | const std::string &, |
| 151 | mtx::http::RequestErr err) { |
| 152 | if (err) { |
| 153 | nhlog::net()->warn("failed to retrieve media {}: {} {}", |
| 154 | url, |
| 155 | err->matrix_error.error, |
| 156 | static_cast<int>(err->status_code)); |
| 157 | return; |
| 158 | } |
| 159 | |
| 160 | try { |
| 161 | QFile file(filename.filePath()); |
| 162 | |
| 163 | if (!file.open(QIODevice::WriteOnly)) |
| 164 | return; |
| 165 | |
| 166 | QByteArray ba(data.data(), (int)data.size()); |
| 167 | file.write(ba); |
| 168 | file.close(); |
| 169 | |
| 170 | QBuffer buf(&ba); |
| 171 | buf.open(QBuffer::ReadOnly); |
| 172 | processBuffer(buf); |
| 173 | } catch (const std::exception &e) { |
| 174 | nhlog::ui()->warn("Error while saving file to: {}", e.what()); |
| 175 | } |
| 176 | }); |
| 177 | } |
| 178 | |
| 179 | #include "moc_MxcMediaProxy.cpp" |