Newer
Older
saori / saoriview.cpp
/***

The MIT License

Copyright (c) 2018 Teppei Tamra (TAM)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

***/

#include "saoriview.h"
#include "ui_saoriview.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrlQuery>
#include <QLabel>
#include <QScrollBar>
#include <QDebug>
#include <QDateTime>
#include <QBoxLayout>
#include <saoriapplication.h>

QList<SaoriView *> SaoriView::m_viewList;

SaoriView::SaoriView(const QString view, const QString account, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SaoriView)
{
    ui->setupUi(this);
    m_viewname = view;
    m_account = account;
    m_viewList.append(this);
    m_maxid = 0;

    if (m_viewname == "instance") {
        m_entries.append(new SaoriViewEntry(0,ui->scrollAreaWidgetContents));
        m_entries.at(0)->setContent(instanceInfoParser(account));
        ui->scrollAreaWidgetContents->layout()->addWidget(m_entries.at(0));
        return;
    }

    auto saoriaccount = SaoriApplication::saori()->findAccount(m_account);
    if (saoriaccount) {
        connect(saoriaccount,&SaoriAccount::apiData,this,&SaoriView::recived);
        saoriaccount->getTimelineData(view,QUrlQuery());
        connect(ui->scrollArea->verticalScrollBar(),&QScrollBar::valueChanged,this,[=](int p){
            if (ui->scrollArea->verticalScrollBar()->maximum() == p) {
                if (m_entries.count()) {
                    QUrlQuery q;
                    q.addQueryItem("max_id",QString::number(m_entries.last()->id()));
                    saoriaccount->getTimelineData(view,q);
                }
            }
        });
    }
}

SaoriView::~SaoriView()
{
    delete ui;
    m_viewList.removeOne(this);
}

SaoriView *SaoriView::findView(const QString view, const QString account)
{
    for(auto v:m_viewList) {
        if ((v->m_viewname == view) && (v->m_account == account)) return v;
    }
    return nullptr;
}

void SaoriView::reload()
{
    qDebug() << "reload.";
    auto saoriaccount = SaoriApplication::saori()->findAccount(m_account);
    if (saoriaccount == nullptr) return;
    if (m_entries.count() == 0) m_maxid = 0;
    else {
        m_maxid = m_entries.first()->id();
    }
    QUrlQuery query;
    query.addQueryItem("since_id",QString::number(m_maxid));
    saoriaccount->getTimelineData(m_viewname,query);
}

const QString SaoriView::instanceInfoParser(const QString instance)
{
    auto i = SaoriApplication::findInstance(QUrl(instance));
    if (!i) return QString();
    QString result;
    result = (tr("<div>%1</div>"
                 "<div>%2</div>"
                 "<div>%3</div>"
                 "<div>email : %4</div>"
                 "<div>%5</div>"
                 "<div>version : %6</div>"
                 ).arg(i->instanceInfo("title").toString(),
                       i->instanceInfo("uri").toString(),
                       i->instanceInfo("description").toString(),
                       i->instanceInfo("email").toString(),
                       accountParser(i->instanceInfo("contact_account").toObject()),
                       i->instanceInfo("version").toString()));
    return result;
}

const QString SaoriView::statusParser(const QJsonObject json)
{
    QString result;
    if (json.isEmpty()) return QString();
    bool rebloged = false;
    if (!json["reblog"].isNull()) rebloged = true;
    if (rebloged) {
        result += statusParser(json["reblog"].toObject());
        result += "<div class=\"reblogger\">";
    } else {
        result += "<div class=\"status\">";
    }
    if (rebloged) {
        result += "<br /><img(mavatar:";
        result += json["account"].toObject()["avatar"].toString();
        result += ") />";
        result += tr("boosted by: %1").arg(json["account"].toObject()["display_name"].toString());
    } else {
        result += accountParser(json["account"].toObject());
        result += "<div class=\"created_at\">";
        result += tr("created at :");
        QDateTime dt = QDateTime::fromString(json["created_at"].toString(),"yyyy-MM-ddTHH:mm:ss.zzzZ");
        dt.setTimeSpec(Qt::UTC);
        result += dt.toLocalTime().toString();
        result += "</div>";
    }
    if (!rebloged) {
        result += "<div class=\"content\">";
        result += contentParser(json["content"].toString());
        result += "<div class=\"media\">";
        for (auto j:json["media_attachments"].toArray()) {
            result += mediaParser(j.toObject());
        }
        result += "</div>";
        result += "</div>";
    }
    result += "</div>";
    return result;
}

const QString SaoriView::accountParser(const QJsonObject json)
{
    QString result;
    if (json.isEmpty()) return QString();
    result += "<div class=\"account\">";
    result += "<span class=\"avatar\"><hr />";
    result += "<img(avatar:";
    result += json["avatar"].toString();
    result += ") style=\"float:left;\" /></span>";
    result += "<span class=\"display_name\">";
    result += json["display_name"].toString();
    result += "</span> <span class=\"acct\">@";
    result += json["acct"].toString();
    result += "</span>";
    result += "<div class=\"user_info\">";
    result += tr(" following: ");
    result += QString::number(json["following_count"].toInt());
    result += tr(" followers: ");
    result += QString::number(json["followers_count"].toInt());
    result += "</div>";
    result += "</div>";
    return result;
}

const QString SaoriView::mediaParser(const QJsonObject json)
{
    QString result;
    result += "<span class=\"media_preview\">";
    if (json["type"].toString() == "image") {
        result += "<a href=\"media:";
        result += json["url"].toString();
        result += "\">";
    }
    result += "<img(media:";
    result += json["preview_url"].toString();
    result += ") width=200>";
    if (json["type"].toString() == "image") {
        result += "</a>";
    }
    result += "</span>";
    return result;
}

const QString SaoriView::contentParser(const QString content)
{
    QString result;
    auto l = content.split("<br />");
    for (auto s:l) {
        result += "<br />";
        int i = 0;
        for (auto c:s) {
            if (c != ' ') break;
            result += "&nbsp;";
        }
        result += s.right(s.count() - i);
    }
    result = result.right(result.count() - 6);

    l = result.split("<p>");
    result = "";
    for (auto s:l) {
        result += "<p>";
        int i = 0;
        for (auto c:s) {
            if (c != ' ') break;
            result += "&nbsp;";
        }
        result += s.right(s.count() - i);
    }
    result = result.right(result.count() - 3);

    return result;
}

void SaoriView::recived(const QString timeline,const QByteArray data)
{
    if (timeline != m_viewname) return;
    QJsonArray json = QJsonDocument::fromJson(data).array();
    for (auto j:json) {
        qDebug() << j.toObject()["content"].toString();
        int i = 0;
        SaoriViewEntry *entry = nullptr;
        for(;m_entries.count() > i;i ++) {
            if (m_entries.at(i)->id() == j.toObject()["id"].toString().toLongLong()) {
                entry = m_entries.at(i);
                qDebug() << "update";
                break;
            }
            if (m_entries.at(i)->id() < j.toObject()["id"].toString().toLongLong()) break;
        }
        if (entry == nullptr) {
            qDebug() << j.toObject()["id"].toString().toLong();
            entry = new SaoriViewEntry(j.toObject()["id"].toString().toLongLong(),ui->scrollAreaWidgetContents);
            connect(entry,&SaoriViewEntry::anchorClicked,this,&SaoriView::linkClicked);
            m_entries.insert(i,entry);
            qobject_cast<QBoxLayout*>(ui->scrollAreaWidgetContents->layout())->insertWidget(i,entry);
            entry->setContent(statusParser(j.toObject()));
        }
    }
    if (m_entries.count()) {
        if (m_entries.first()->id() > m_maxid) reload();
    }
}

void SaoriView::linkClicked(const QUrl &url)
{
    qDebug() << "clicked:" << url.toString();
    if (url.toString().left(6) == "media:") {
        QUrl u(url.toString().mid(6));
        emit openMediaView(u);
    }
}

void SaoriView::on_pushButton_newest_clicked()
{
    ui->scrollArea->verticalScrollBar()->setValue(0);
}

void SaoriView::on_pushButton_reload_clicked()
{
    reload();
}