File indexing completed on 2024-10-06 12:54:05

0001 // SPDX-FileCopyrightText: 2022 Bharadwaj Raju <bharadwaj.raju777@protonmail.com>
0002 // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-or-later OR LicenseRef-KDE-Accepted-GPL
0003 
0004 #include "linkpreviewer.h"
0005 
0006 #include "controller.h"
0007 
0008 #include <Quotient/connection.h>
0009 #include <Quotient/csapi/content-repo.h>
0010 
0011 #include "neochatroom.h"
0012 
0013 using namespace Quotient;
0014 
0015 LinkPreviewer::LinkPreviewer(QObject *parent, NeoChatRoom *room, const QUrl &url)
0016     : QObject(parent)
0017     , m_currentRoom(room)
0018     , m_loaded(false)
0019     , m_url(url)
0020 {
0021     loadUrlPreview();
0022 }
0023 
0024 bool LinkPreviewer::loaded() const
0025 {
0026     return m_loaded;
0027 }
0028 
0029 QString LinkPreviewer::title() const
0030 {
0031     return m_title;
0032 }
0033 
0034 QString LinkPreviewer::description() const
0035 {
0036     return m_description;
0037 }
0038 
0039 QUrl LinkPreviewer::imageSource() const
0040 {
0041     return m_imageSource;
0042 }
0043 
0044 QUrl LinkPreviewer::url() const
0045 {
0046     return m_url;
0047 }
0048 
0049 void LinkPreviewer::setUrl(QUrl url)
0050 {
0051     if (url != m_url) {
0052         m_url = url;
0053         urlChanged();
0054         loadUrlPreview();
0055     }
0056 }
0057 
0058 void LinkPreviewer::loadUrlPreview()
0059 {
0060     if (m_url.scheme() == QStringLiteral("https")) {
0061         m_loaded = false;
0062         Q_EMIT loadedChanged();
0063 
0064         auto conn = m_currentRoom->connection();
0065         GetUrlPreviewJob *job = conn->callApi<GetUrlPreviewJob>(m_url.toString());
0066 
0067         connect(job, &BaseJob::success, this, [this, job, conn]() {
0068             const auto json = job->jsonData();
0069             m_title = json["og:title"].toString().trimmed();
0070             m_description = json["og:description"].toString().trimmed().replace("\n", " ");
0071 
0072             auto imageUrl = QUrl(json["og:image"].toString());
0073             if (imageUrl.isValid() && imageUrl.scheme() == QStringLiteral("mxc")) {
0074                 m_imageSource = conn->makeMediaUrl(imageUrl);
0075             } else {
0076                 m_imageSource = QUrl();
0077             }
0078 
0079             m_loaded = true;
0080             Q_EMIT titleChanged();
0081             Q_EMIT descriptionChanged();
0082             Q_EMIT imageSourceChanged();
0083             Q_EMIT loadedChanged();
0084         });
0085     }
0086 }
0087 
0088 #include "moc_linkpreviewer.cpp"