Commit 211b78cc authored by jan.koester's avatar jan.koester
Browse files

test

parent 00370d07
Loading
Loading
Loading
Loading
+3 −0
Changes for client/CMakeLists.txt: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -18,6 +18,8 @@ qt_add_executable(blogi-editor
    localapi.cpp
    localapi.h
    themeprovider.h
    authimageprovider.cpp
    authimageprovider.h
)

qt_add_qml_module(blogi-editor
@@ -32,6 +34,7 @@ qt_add_qml_module(blogi-editor
        qml/PreviewPane.qml
        qml/ConnectionPanel.qml
        qml/MediaBrowser.qml
        qml/PublishDialog.qml
)

target_link_libraries(blogi-editor PRIVATE
+143 −0
Changes for client/authimageprovider.cpp: 143 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include "authimageprovider.h"
#include "publishclient.h"

#include <QNetworkReply>
#include <QNetworkRequest>
#include <QQuickTextureFactory>
#include <QImage>
#include <QImageReader>
#include <QBuffer>
#include <QMetaObject>
#include <QDebug>

AuthImageResponse::AuthImageResponse(const QString &url, const QSize &requestedSize,
                                     PublishClient *pub)
{
    /*
     * requestImageResponse() is called from the QQuickPixmapReader thread,
     * but QNetworkAccessManager must be used from its owning (main) thread.
     * Dispatch the network request to the main thread via QueuedConnection.
     */
    QMetaObject::invokeMethod(pub, [this, url, requestedSize, pub]() {
        QNetworkAccessManager *nam = pub->networkManager();
        QUrl imageUrl = QUrl::fromEncoded(url.toUtf8());

        QNetworkRequest req(imageUrl);
        req.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);
        req.setRawHeader("Accept", "image/png, image/jpeg, image/gif, image/bmp, image/webp, */*");

        QString token = pub->authToken();
        if (!token.isEmpty())
            req.setRawHeader("Cookie", ("authid=" + token).toUtf8());

        QNetworkReply *reply = nam->get(req);

        if (pub->ignoreSsl()) {
            connect(reply, &QNetworkReply::sslErrors,
                    reply, qOverload<>(&QNetworkReply::ignoreSslErrors));
        }

        /*
         * Use DirectConnection: reply lives on main thread, the lambda
         * runs on main thread, which is fine.  QQuickImageResponse::finished()
         * is documented as safe to emit from any thread.
         */
        connect(reply, &QNetworkReply::finished, this, [this, reply, requestedSize]() {
            reply->deleteLater();

            if (reply->error() != QNetworkReply::NoError) {
                _error = reply->errorString();
                emit finished();
                return;
            }

            QByteArray data = reply->readAll();
            if (data.isEmpty()) {
                _error = "Empty response from server";
                emit finished();
                return;
            }

            /* Derive format hint from Content-Type header */
            QByteArray formatHint;
            QString ct = reply->header(QNetworkRequest::ContentTypeHeader).toString().toLower();
            if (ct.contains("png"))        formatHint = "png";
            else if (ct.contains("jpeg") || ct.contains("jpg")) formatHint = "jpeg";
            else if (ct.contains("gif"))   formatHint = "gif";
            else if (ct.contains("webp"))  formatHint = "webp";
            else if (ct.contains("bmp"))   formatHint = "bmp";
            else if (ct.contains("svg"))   formatHint = "svg";

            /* Try with format hint first, then without (auto-detect) */
            if (!formatHint.isEmpty())
                _image = QImage::fromData(data, formatHint.constData());
            if (_image.isNull())
                _image = QImage::fromData(data);

            if (_image.isNull()) {
                /* Try QImageReader with explicit format probing */
                QBuffer buf(&data);
                buf.open(QIODevice::ReadOnly);
                QImageReader reader(&buf);
                reader.setDecideFormatFromContent(true);
                _image = reader.read();
            }

            if (_image.isNull()) {
                _error = "Cannot decode image (Content-Type: " + ct
                       + ", " + QString::number(data.size()) + " bytes, "
                       + "supported: " + QImageReader::supportedImageFormats().join(", ") + ")";
                qWarning() << "AuthImageProvider:" << _error;
                emit finished();
                return;
            }

            if (requestedSize.isValid() && !requestedSize.isEmpty())
                _image = _image.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);

            emit finished();
        }, Qt::DirectConnection);
    }, Qt::QueuedConnection);
}

QQuickTextureFactory *AuthImageResponse::textureFactory() const {
    return _image.isNull() ? nullptr : QQuickTextureFactory::textureFactoryForImage(_image);
}

AuthImageProvider::AuthImageProvider(PublishClient *pub)
    : _pub(pub)
{
}

QQuickImageResponse *AuthImageProvider::requestImageResponse(
    const QString &id, const QSize &requestedSize)
{
    return new AuthImageResponse(id, requestedSize, _pub);
}
+58 −0
Changes for client/authimageprovider.h: 58 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#pragma once

#include <QQuickAsyncImageProvider>
#include <QNetworkAccessManager>

class PublishClient;

class AuthImageResponse : public QQuickImageResponse {
    Q_OBJECT
public:
    AuthImageResponse(const QString &url, const QSize &requestedSize,
                      PublishClient *pub);

    QQuickTextureFactory *textureFactory() const override;
    QString errorString() const override { return _error; }

private:
    QImage  _image;
    QString _error;
};

class AuthImageProvider : public QQuickAsyncImageProvider {
public:
    explicit AuthImageProvider(PublishClient *pub);

    QQuickImageResponse *requestImageResponse(
        const QString &id, const QSize &requestedSize) override;

private:
    PublishClient *_pub;
};
+218 −11
Changes for client/localapi.cpp: 218 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QSettings>

LocalApi::LocalApi(DocumentManager *doc, PublishClient *pub, QObject *parent)
    : QObject(parent), _doc(doc), _pub(pub) {}
@@ -116,6 +117,40 @@ QString LocalApi::renderPreview() {
    return _doc->renderToHtml();
}

void LocalApi::renderPreviewOnServer(bool mobile, const QString &target, const QString &paramsJson) {
    if (!_pub->isConfigured()) {
        emit statusMessage("Not connected — using local preview");
        emit serverPreviewReady(QString());
        return;
    }

    QString html = _doc->renderToHtml();
    if (html.isEmpty()) {
        emit serverPreviewReady(QString());
        return;
    }

    QMap<QString,QString> extra;
    if (!paramsJson.isEmpty()) {
        QJsonDocument pdoc = QJsonDocument::fromJson(paramsJson.toUtf8());
        if (pdoc.isObject()) {
            QJsonObject obj = pdoc.object();
            for (auto it = obj.begin(); it != obj.end(); ++it)
                extra.insert(it.key(), it.value().toString());
        }
    }

    _pub->renderOnServer(html, mobile, target, extra,
        [this](bool ok, const QString &rendered) {
            if (ok) {
                emit serverPreviewReady(rendered);
            } else {
                emit statusMessage("Server render failed: " + rendered);
                emit serverPreviewReady(QString());
            }
        });
}

void LocalApi::newDocument() {
    _doc->newDocument();
    _currentFile.clear();
@@ -290,7 +325,7 @@ void LocalApi::fetchMedia(const QString &albumId) {
void LocalApi::fetchPublishTargets() {
    QJsonArray cmds;
    QJsonObject cmd;
    cmd["command"] = "webedit_list_targets";
    cmd["command"] = "list_publish_targets";
    cmds.append(cmd);

    _pub->apiRequest(cmds, [this](bool ok, const QJsonArray &resp) {
@@ -315,22 +350,194 @@ void LocalApi::publishToTarget(const QString &target, const QString &paramsJson)
        return;
    }

    QString rendered = _doc->renderToHtml();
    if (rendered.isEmpty()) {
        emit publishCompleted(false, "Document is empty");
    emit statusMessage("Publishing to " + target + "...");

    QJsonArray cmds;
    QJsonObject cmd;
    cmd["command"] = "publish";
    cmd["target"] = target;

    if (!paramsJson.isEmpty()) {
        QJsonDocument pdoc = QJsonDocument::fromJson(paramsJson.toUtf8());
        if (pdoc.isObject())
            cmd["params"] = pdoc.object();
    }
    cmds.append(cmd);

    _pub->apiRequest(cmds, [this, target](bool ok, const QJsonArray &resp) {
        if (!ok) {
            emit publishCompleted(false, "Network error");
            emit statusMessage("Publish failed: network error");
            return;
        }
        for (int i = 0; i < resp.size(); ++i) {
            QJsonObject obj = resp.at(i).toObject();
            QString status = obj["status"].toString();
            if (status == "success") {
                QString url = obj["url"].toString();
                QString msg = url.isEmpty() ? "Published successfully" : url;
                emit publishCompleted(true, msg);
                emit statusMessage("Published to " + target);
                return;
            } else if (status == "duplicate") {
                emit publishCompleted(false, "duplicate:" + obj["existing_id"].toString()
                                             + ":" + obj["message"].toString("Duplicate entry"));
                emit statusMessage("Duplicate — overwrite?");
                return;
            } else if (status == "error") {
                emit publishCompleted(false, obj["message"].toString("Publish failed"));
                emit statusMessage("Publish failed: " + obj["message"].toString());
                return;
            }
        }
        emit publishCompleted(false, "Unexpected response");
    });
}

    emit statusMessage("Publishing to " + target + "...");
    _pub->renderOnServer(rendered, false, [this](bool ok, const QString &msg) {
        emit publishCompleted(ok, msg);
        if (ok)
            emit statusMessage("Published successfully");
        else
            emit statusMessage("Publish failed: " + msg);
void LocalApi::publishToTargetOverwrite(const QString &target, const QString &paramsJson, const QString &existingId) {
    if (!_pub->isConfigured()) {
        emit publishCompleted(false, "Not connected");
        return;
    }

    emit statusMessage("Overwriting " + target + "...");

    QJsonArray cmds;
    QJsonObject cmd;
    cmd["command"] = "publish";
    cmd["target"] = target;
    cmd["overwrite"] = true;
    cmd["existing_id"] = existingId;

    if (!paramsJson.isEmpty()) {
        QJsonDocument pdoc = QJsonDocument::fromJson(paramsJson.toUtf8());
        if (pdoc.isObject())
            cmd["params"] = pdoc.object();
    }
    cmds.append(cmd);

    _pub->apiRequest(cmds, [this, target](bool ok, const QJsonArray &resp) {
        if (!ok) {
            emit publishCompleted(false, "Network error");
            return;
        }
        for (int i = 0; i < resp.size(); ++i) {
            QJsonObject obj = resp.at(i).toObject();
            QString status = obj["status"].toString();
            if (status == "success") {
                QString url = obj["url"].toString();
                emit publishCompleted(true, url.isEmpty() ? "Overwritten successfully" : url);
                emit statusMessage("Published to " + target);
                return;
            } else if (status == "error") {
                emit publishCompleted(false, obj["message"].toString("Overwrite failed"));
                emit statusMessage("Overwrite failed: " + obj["message"].toString());
                return;
            }
        }
        emit publishCompleted(false, "Unexpected response");
    });
}

void LocalApi::refresh() {
    emit documentChanged();
}

/* ---------- Saved connections CRUD ---------- */

QString LocalApi::getSavedConnections() {
    QSettings settings;
    QJsonArray arr;
    int count = settings.beginReadArray("connections");
    for (int i = 0; i < count; ++i) {
        settings.setArrayIndex(i);
        QJsonObject obj;
        obj["name"]      = settings.value("name").toString();
        obj["url"]       = settings.value("url").toString();
        obj["user"]      = settings.value("user").toString();
        obj["password"]  = settings.value("password").toString();
        obj["ignoreSsl"] = settings.value("ignoreSsl").toBool();
        arr.append(obj);
    }
    settings.endArray();
    return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
}

void LocalApi::saveConnection(const QString &name, const QString &url, const QString &user, const QString &password, bool ignoreSsl) {
    QJsonArray arr = QJsonDocument::fromJson(getSavedConnections().toUtf8()).array();
    QJsonObject obj;
    obj["name"]      = name;
    obj["url"]       = url;
    obj["user"]      = user;
    obj["password"]  = password;
    obj["ignoreSsl"] = ignoreSsl;
    arr.append(obj);

    QSettings settings;
    settings.beginWriteArray("connections", arr.size());
    for (int i = 0; i < arr.size(); ++i) {
        settings.setArrayIndex(i);
        QJsonObject o = arr.at(i).toObject();
        settings.setValue("name",      o["name"].toString());
        settings.setValue("url",       o["url"].toString());
        settings.setValue("user",      o["user"].toString());
        settings.setValue("password",  o["password"].toString());
        settings.setValue("ignoreSsl", o["ignoreSsl"].toBool());
    }
    settings.endArray();
    emit savedConnectionsChanged();
}

void LocalApi::updateConnection(const QString &oldName, const QString &name, const QString &url, const QString &user, const QString &password, bool ignoreSsl) {
    QJsonArray arr = QJsonDocument::fromJson(getSavedConnections().toUtf8()).array();
    for (int i = 0; i < arr.size(); ++i) {
        QJsonObject o = arr.at(i).toObject();
        if (o["name"].toString() == oldName) {
            o["name"]      = name;
            o["url"]       = url;
            o["user"]      = user;
            o["password"]  = password;
            o["ignoreSsl"] = ignoreSsl;
            arr[i] = o;
            break;
        }
    }

    QSettings settings;
    settings.beginWriteArray("connections", arr.size());
    for (int i = 0; i < arr.size(); ++i) {
        settings.setArrayIndex(i);
        QJsonObject o = arr.at(i).toObject();
        settings.setValue("name",      o["name"].toString());
        settings.setValue("url",       o["url"].toString());
        settings.setValue("user",      o["user"].toString());
        settings.setValue("password",  o["password"].toString());
        settings.setValue("ignoreSsl", o["ignoreSsl"].toBool());
    }
    settings.endArray();
    emit savedConnectionsChanged();
}

void LocalApi::deleteConnection(const QString &name) {
    QJsonArray arr = QJsonDocument::fromJson(getSavedConnections().toUtf8()).array();
    QJsonArray filtered;
    for (int i = 0; i < arr.size(); ++i) {
        QJsonObject o = arr.at(i).toObject();
        if (o["name"].toString() != name)
            filtered.append(o);
    }

    QSettings settings;
    settings.beginWriteArray("connections", filtered.size());
    for (int i = 0; i < filtered.size(); ++i) {
        settings.setArrayIndex(i);
        QJsonObject o = filtered.at(i).toObject();
        settings.setValue("name",      o["name"].toString());
        settings.setValue("url",       o["url"].toString());
        settings.setValue("user",      o["user"].toString());
        settings.setValue("password",  o["password"].toString());
        settings.setValue("ignoreSsl", o["ignoreSsl"].toBool());
    }
    settings.endArray();
    emit savedConnectionsChanged();
}
+10 −0
Changes for client/localapi.h: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -65,6 +65,7 @@ public:
    Q_INVOKABLE QString exportXml();
    Q_INVOKABLE bool importXml(const QString &xml);
    Q_INVOKABLE QString renderPreview();
    Q_INVOKABLE void renderPreviewOnServer(bool mobile, const QString &target, const QString &paramsJson);

    /* Media browse (requires connection) */
    Q_INVOKABLE void fetchAlbums();
@@ -73,6 +74,7 @@ public:
    /* Publish (requires connection) */
    Q_INVOKABLE void fetchPublishTargets();
    Q_INVOKABLE void publishToTarget(const QString &target, const QString &paramsJson);
    Q_INVOKABLE void publishToTargetOverwrite(const QString &target, const QString &paramsJson, const QString &existingId);

    /* File operations (called from QML menus) */
    Q_INVOKABLE void newDocument();
@@ -88,6 +90,12 @@ public:
    Q_INVOKABLE void setIgnoreSslErrors(bool ignore);
    Q_INVOKABLE QString serverUrl() const;

    /* Saved connections CRUD */
    Q_INVOKABLE QString getSavedConnections();
    Q_INVOKABLE void    saveConnection(const QString &name, const QString &url, const QString &user, const QString &password, bool ignoreSsl);
    Q_INVOKABLE void    updateConnection(const QString &oldName, const QString &name, const QString &url, const QString &user, const QString &password, bool ignoreSsl);
    Q_INVOKABLE void    deleteConnection(const QString &name);

    /* Initial load */
    Q_INVOKABLE void refresh();

@@ -96,10 +104,12 @@ signals:
    void statusMessage(const QString &msg);
    void currentFileChanged(const QString &path);
    void connectionStatusChanged(bool ok, const QString &msg);
    void serverPreviewReady(const QString &html);
    void albumsLoaded(const QString &json);
    void mediaLoaded(const QString &json);
    void publishTargetsLoaded(const QString &json);
    void publishCompleted(bool ok, const QString &msg);
    void savedConnectionsChanged();

private:
    DocumentManager *_doc;
Loading