messagewebview.cpp 16.2 KB
Newer Older
1
/***************************************************************************
2
 * Copyright (C) 2017-2019 by Savoir-faire Linux                           *
3 4
 * Author: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>          *
 * Author: Alexandre Viau <alexandre.viau@savoirfairelinux.com>            *
5
 * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>            *
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Author: Hugo Lefeuvre <hugo.lefeuvre@savoirfairelinux.com>              *
 *                                                                         *
 * This program is free software; you can redistribute it and/or modify    *
 * it under the terms of the GNU General Public License as published by    *
 * the Free Software Foundation; either version 3 of the License, or       *
 * (at your option) any later version.                                     *
 *                                                                         *
 * This program is distributed in the hope that it will be useful,         *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 * GNU General Public License for more details.                            *
 *                                                                         *
 * You should have received a copy of the GNU General Public License       *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.   *
 **************************************************************************/

#include "messagewebview.h"

#include <QDebug>
#include <QDesktopServices>
#include <QFileDialog>
27 28 29 30 31
#include <QMenu>
#include <QMouseEvent>
#include <QScrollBar>
#include <QTimer>
#include <QWebChannel>
32
#include <QWebEnginePage>
33
#include <QWebEngineProfile>
34 35 36 37 38 39 40
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
#include <QWebEngineSettings>

#include <ciso646>
#include <fstream>

41 42
#include "lrcinstance.h"
#include "messagewebpage.h"
43 44 45 46 47 48
#include "utils.h"
#include "webchathelpers.h"

MessageWebView::MessageWebView(QWidget *parent)
    : QWebEngineView(parent)
{
49 50 51 52 53 54 55 56 57 58 59
    QWebEngineProfile* profile = QWebEngineProfile::defaultProfile();
    QDir dataDir(QStandardPaths::writableLocation(
        QStandardPaths::AppLocalDataLocation));
    dataDir.cdUp();
    auto cachePath = dataDir.absolutePath() + "/jami";
    profile->setCachePath(cachePath);
    profile->setPersistentStoragePath(cachePath);
    profile->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies);
    profile->setHttpCacheType(QWebEngineProfile::NoCache);

    setPage(new MessageWebPage(profile, this));
60 61 62 63 64 65 66 67 68 69

    settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
    settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
    settings()->setAttribute(QWebEngineSettings::ScrollAnimatorEnabled, false);
    settings()->setAttribute(QWebEngineSettings::ErrorPageEnabled, false);
    settings()->setAttribute(QWebEngineSettings::PluginsEnabled, false);
    settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, false);
    settings()->setAttribute(QWebEngineSettings::ScreenCaptureEnabled, false);
    settings()->setAttribute(QWebEngineSettings::LinksIncludedInFocusChain, false);
    settings()->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
70 71 72 73 74 75
    settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
    settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
    settings()->setAttribute(QWebEngineSettings::XSSAuditingEnabled, false);
    settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);

    settings()->setFontSize(QWebEngineSettings::MinimumFontSize, 2);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

    setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu);

    jsBridge_ = new PrivateBridging(this);
    webChannel_ = new QWebChannel(page());
    webChannel_->registerObject(QStringLiteral("jsbridge"), jsBridge_);
    page()->setWebChannel(webChannel_);

    connect(this, &QWebEngineView::renderProcessTerminated,
        [this](QWebEnginePage::RenderProcessTerminationStatus termStatus, int statusCode) {
            Q_UNUSED(statusCode);
            QString status;
            switch (termStatus) {
            case QWebEnginePage::NormalTerminationStatus:
                qDebug() << "MessageWebView - Render process normal exit";
                break;
            case QWebEnginePage::AbnormalTerminationStatus:
                qDebug() << "MessageWebView - Render process abnormal exit";
                break;
            case QWebEnginePage::CrashedTerminationStatus:
                qDebug() << "MessageWebView - Render process crashed";
                break;
            case QWebEnginePage::KilledTerminationStatus:
                qDebug() << "MessageWebView - Render process killed";
                break;
            }
        });
}

MessageWebView::~MessageWebView()
{
}

109 110 111 112 113 114 115 116 117 118 119 120
void MessageWebView::setMessagesContent(QString text)
{
    page()->runJavaScript(QStringLiteral("document.getElementById('message').value = '%1'").arg(text));
}

void MessageWebView::copySelectedText(QClipboard* clipboard)
{
    page()->runJavaScript(QStringLiteral("copy_text_selected();"), [clipboard, this](const QVariant& v) {
        clipboard->setText(v.toString());
    });
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
void MessageWebView::buildView()
{
    auto html = Utils::QByteArrayFromFile(":/web/chatview.html");
    page()->setHtml(html, QUrl(":/web/chatview.html"));
    connect(this, &QWebEngineView::loadFinished, this, &MessageWebView::slotLoadFinished);
}

void
MessageWebView::slotLoadFinished()
{
    insertStyleSheet("chatcss", Utils::QByteArrayFromFile(":/web/chatview.css"));
    page()->runJavaScript(Utils::QByteArrayFromFile(":/web/linkify.js"), QWebEngineScript::MainWorld);
    page()->runJavaScript(Utils::QByteArrayFromFile(":/web/linkify-html.js"), QWebEngineScript::MainWorld);
    page()->runJavaScript(Utils::QByteArrayFromFile(":/web/linkify-string.js"), QWebEngineScript::MainWorld);
    page()->runJavaScript(Utils::QByteArrayFromFile(":/web/qwebchannel.js"), QWebEngineScript::MainWorld);
    page()->runJavaScript(Utils::QByteArrayFromFile(":/web/chatview.js"), QWebEngineScript::MainWorld);
}

void
MessageWebView::insertStyleSheet(const QString &name, const QString &source)
{
    QWebEngineScript script;
    auto simplifiedCSS = source.simplified().replace("'", "\"");
    QString s = QString::fromLatin1("(function() {"\
                                    "    var node = document.createElement('style');"\
                                    "    node.id = '%1';"\
                                    "    node.innerHTML = '%2';"\
                                    "    document.head.appendChild(node);"\
                                    "})()").arg(name).arg(simplifiedCSS);
    page()->runJavaScript(s);

    script.setName(name);
    script.setSourceCode(s);
    script.setInjectionPoint(QWebEngineScript::DocumentReady);
    script.setRunsOnSubFrames(true);
    script.setWorldId(QWebEngineScript::MainWorld);
    page()->scripts().insert(script);
}

void
MessageWebView::removeStyleSheet(const QString &name)
{
    QString s = QString::fromLatin1("(function() {"\
                                    "    var element = document.getElementById('%1');"\
                                    "    element.outerHTML = '';"\
                                    "    delete element;"\
                                    "})()").arg(name);

    page()->runJavaScript(s);

    QWebEngineScript script = page()->scripts().findScript(name);
    page()->scripts().remove(script);
}

void MessageWebView::clear()
{
    QString s = QString::fromLatin1("clearMessages();");
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::setDisplayLinks(bool display)
{
    QString s = QString::fromLatin1("setDisplayLinks('%1');")
        .arg(display ? "true" : "false");
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::printNewInteraction(lrc::api::ConversationModel& conversationModel,
                                    uint64_t msgId,
                                    const lrc::api::interaction::Info& interaction)
{
    auto interactionObject = interactionToJsonInteractionObject(conversationModel, msgId, interaction).toUtf8();
    QString s = QString::fromLatin1("addMessage(%1);")
        .arg(interactionObject.constData());
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::updateInteraction(lrc::api::ConversationModel& conversationModel,
                                  uint64_t msgId,
                                  const lrc::api::interaction::Info& interaction)
{
    auto interactionObject = interactionToJsonInteractionObject(conversationModel, msgId, interaction).toUtf8();
    QString s = QString::fromLatin1("updateMessage(%1);")
        .arg(interactionObject.constData());
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::removeInteraction(uint64_t interactionId)
{
    QString s = QString::fromLatin1("removeInteraction(%1);")
        .arg(QString::number(interactionId));
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::printHistory(lrc::api::ConversationModel& conversationModel,
                             const std::map<uint64_t,
Andreas Traczyk's avatar
Andreas Traczyk committed
222
                             lrc::api::interaction::Info> interactions)
223 224
{
    auto interactionsStr = interactionsToJsonArrayObject(conversationModel, interactions).toUtf8();
Andreas Traczyk's avatar
Andreas Traczyk committed
225 226
    QString s = QString::fromLatin1("printHistory(%1);")
        .arg(interactionsStr.constData());
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
MessageWebView::setSenderImage(const std::string& sender,
                               const std::string& senderImage)
{
    QJsonObject setSenderImageObject = QJsonObject();
    setSenderImageObject.insert("sender_contact_method", QJsonValue(QString(sender.c_str())));
    setSenderImageObject.insert("sender_image", QJsonValue(QString(senderImage.c_str())));

    auto setSenderImageObjectString = QString(QJsonDocument(setSenderImageObject).toJson(QJsonDocument::Compact));
    QString s = QString::fromLatin1("setSenderImage(%1);")
        .arg(setSenderImageObjectString.toUtf8().constData());
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
245
MessageWebView::setInvitation(bool show, const std::string& contactUri, const std::string& contactId)
246
{
247 248 249 250
    QString s = show ? QString::fromLatin1("showInvitation(\"%1\", \"%2\")")
        .arg(QString(contactUri.c_str()))
        .arg(QString(contactId.c_str())) : QString::fromLatin1("showInvitation()");

251 252 253 254
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

void
255
MessageWebView::setMessagesVisibility(bool visible)
256
{
257
    QString s = QString::fromLatin1(visible ? "showMessagesDiv();" : "hideMessagesDiv();");
258 259 260 261
    page()->runJavaScript(s, QWebEngineScript::MainWorld);
}

// JS bridging incoming
262 263 264 265 266 267 268
Q_INVOKABLE int
PrivateBridging::log(const QString& arg)
{
    qDebug() << "JS log: " << arg;
    return 0;
}

269
Q_INVOKABLE int
Andreas Traczyk's avatar
Andreas Traczyk committed
270
PrivateBridging::emitMessagesCleared()
271 272 273 274 275 276 277
{
    if (auto messageView = qobject_cast<MessageWebView*>(this->parent())) {
        emit messageView->messagesCleared();
    }
    return 0;
}

Andreas Traczyk's avatar
Andreas Traczyk committed
278 279 280 281 282 283 284 285 286
Q_INVOKABLE int
PrivateBridging::emitMessagesLoaded()
{
    if (auto messageView = qobject_cast<MessageWebView*>(this->parent())) {
        emit messageView->messagesLoaded();
    }
    return 0;
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
Q_INVOKABLE int
PrivateBridging::deleteInteraction(const QString& arg)
{
    bool ok;
    uint64_t interactionUid = arg.toULongLong(&ok);
    if (ok) {
        LRCInstance::getCurrentConversationModel()->clearInteractionFromConversation(
            LRCInstance::getSelectedConvUid(),
            interactionUid
        );
    } else {
        qDebug() << "deleteInteraction - invalid arg" << arg;
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::retryInteraction(const QString& arg)
{
    bool ok;
    uint64_t interactionUid = arg.toULongLong(&ok);
    if (ok) {
        LRCInstance::getCurrentConversationModel()->retryInteraction(
            LRCInstance::getSelectedConvUid(),
            interactionUid
        );
    } else {
        qDebug() << "retryInteraction - invalid arg" << arg;
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::openFile(const QString& arg)
{
    QDesktopServices::openUrl(arg);
    return 0;
}

Q_INVOKABLE int
PrivateBridging::acceptFile(const QString& arg)
{
    try {
        auto interactionUid = std::stoull(arg.toStdString());

        lrc::api::datatransfer::Info info = {};
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->getTransferInfo(interactionUid, info);

        // get full path
337
        std::string filename = LRCInstance::dataTransferModel().downloadDirectory.c_str();
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        if (!filename.empty() && filename.back() != '/')
            filename += "/";
        auto wantedFilename = filename + info.displayName;
        auto duplicate = 0;
        while (std::ifstream(wantedFilename).good()) {
            ++duplicate;
            auto extensionIdx = info.displayName.find_last_of(".");
            if (extensionIdx == std::string::npos)
                wantedFilename = filename + info.displayName + " (" + std::to_string(duplicate) + ")";
            else
                wantedFilename = filename + info.displayName.substr(0, extensionIdx) + " (" + std::to_string(duplicate) + ")" + info.displayName.substr(extensionIdx);
        }
        LRCInstance::getCurrentConversationModel()->acceptTransfer(convUid, interactionUid, wantedFilename);
    } catch (...) {
        qDebug() << "JS bridging - exception during acceptFile: " << arg;
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::refuseFile(const QString& arg)
{
    try {
        auto interactionUid = std::stoull(arg.toStdString());
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->cancelTransfer(convUid, interactionUid);
    } catch (...) {
        qDebug() << "JS bridging - exception during refuseFile:" << arg;
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::sendMessage(const QString& arg)
{
    try {
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->sendMessage(convUid, arg.toStdString());
    } catch (...) {
        qDebug() << "JS bridging - exception during sendMessage:" << arg;
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::sendFile()
{
    qDebug() << "JS bridging - MessageWebView::sendFile";
    QString filePath = QFileDialog::getOpenFileName((QWidget*)this->parent(), tr("Choose File"), "", tr("Files (*)"));
    QFileInfo fi(filePath);
    QString fileName = fi.fileName();
    try {
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->sendFile(convUid, filePath.toStdString(), fileName.toStdString());
    } catch (...) {
        qDebug() << "JS bridging - exception during sendFile";
    }
    return 0;
}

Q_INVOKABLE int
399
PrivateBridging::acceptInvitation()
400
{
401 402 403
    try {
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->makePermanent(convUid);
404
        qobject_cast<MessageWebView*>(this->parent())->setInvitation(false);
405 406 407 408 409 410 411 412 413 414 415 416
    } catch (...) {
        qDebug() << "JS bridging - exception during acceptInvitation";
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::refuseInvitation()
{
    try {
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->removeConversation(convUid, false);
417 418 419 420
        if (auto messageView = qobject_cast<MessageWebView*>(this->parent())) {
            messageView->setInvitation(false);
            emit messageView->conversationRemoved();
        }
421 422 423 424 425 426 427 428 429 430 431 432
    } catch (...) {
        qDebug() << "JS bridging - exception during refuseInvitation";
    }
    return 0;
}

Q_INVOKABLE int
PrivateBridging::blockConversation()
{
    try {
        auto convUid = LRCInstance::getSelectedConvUid();
        LRCInstance::getCurrentConversationModel()->removeConversation(convUid, true);
433 434 435 436
        if (auto messageView = qobject_cast<MessageWebView*>(this->parent())) {
            messageView->setInvitation(false);
            emit messageView->conversationRemoved();
        }
437 438 439
    } catch (...) {
        qDebug() << "JS bridging - exception during blockConversation";
    }
440
    return 0;
441
}