Newer
Older
saori / saoriview.cpp
@TAM (Teppei Tamra) TAM (Teppei Tamra) on 9 May 2018 14 KB ユーザ情報へのリンクを追加。
/***

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);
    ui->tootWidget->hide();

    m_viewname = view;
    m_account = account;
    m_viewList.append(this);
    m_maxid = 0;

    ui->header->hide();

    auto footter = new SaoriViewEntry(ui->scrollAreaWidgetContents);
    footter->setFrameStyle(QFrame::NoFrame);
    footter->setContent(htmlDiv("more",tr("more...")));
    ui->scrollAreaWidgetContents->layout()->addWidget(footter);

    if (m_viewname == "instance") {
        ui->frame_buttons->setVisible(false);
        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);
                }
            }
        });
        ui->tootWidget->setAccountLabel(QString("%1(@%2@%3)").arg(
                                            saoriaccount->accountInfo("display_name").toString(),
                                            saoriaccount->accountInfo("username").toString(),
                                            saoriaccount->instance()->instanceInfo("uri").toString()));
        connect(ui->tootWidget,&SaoriTootWidget::postNewStatus,this,[=](const QString data){
            ui->tootWidget->setEnabled(false);
            connect(saoriaccount,&SaoriAccount::posted,this,[=](const QString tl,int result){
                if (tl == m_viewname) {
                    ui->tootWidget->posted(result);
                    ui->tootWidget->setEnabled(true);
                    if (result == QNetworkReply::NoError) reload();
                }
            });
            saoriaccount->postNewStatus(m_viewname,data);
        });
    }
}

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()
{
    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::headerParser(const QJsonObject json)
{
    QString result;
    result += QString(htmlDiv("accounts_icon",
                              htmlImg("avatar",json["avatar"].toString())));
    result += QString(htmlDiv("accounts_display_name",
                              json["display_name"].toString()));
    result += QString(htmlDiv("accounts_acct",
                              "@" + json["acct"].toString()));
    result += QString(htmlDiv("accounts_note",
                              json["note"].toString()));
    return htmlDiv("accounts",result);
}

const QString SaoriView::instanceInfoParser(const QString instance)
{
    auto i = SaoriApplication::findInstance(QUrl(instance));
    if (!i) return QString();
    QString result;
    result = QString(htmlDiv("instance_title","%1") +
                     htmlDiv("instance_uri","%2") +
                     htmlHr() +
                     htmlDiv("instance_description","%3") +
                     htmlHr() +
                     htmlDiv("instance_email","email : %4") +
                     htmlDiv("instance_contact_account","%5") +
                     htmlDiv("instance_version","Version : %6")
                     ).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();

    QDateTime dt = QDateTime::fromString(json["created_at"].toString(),"yyyy-MM-ddTHH:mm:ss.zzzZ");
    dt.setTimeSpec(Qt::UTC);

    //FIXME デバッグ用。
    if (ui->header->isHidden() && (m_viewname.left(8) == "accounts")) {
        ui->header->setContent(headerParser(json["account"].toObject()));
        ui->header->show();
    }

    result = (!json["reblog"].isNull()) ?
        (statusParser(json["reblog"].toObject()) +
                htmlAnc("accounts:" + json["account"].toObject()["id"].toString(),
                        htmlDiv("reblogger",htmlHr() +
                                htmlImg("mavatar",json["account"].toObject()["avatar"].toString()) +
                                tr("boosted by: %1").arg(json["account"].toObject()["display_name"].toString())
                               )
                       )
        ) :
        (htmlDiv("status",accountParser(json["account"].toObject()) +
                htmlDiv("created_at",tr("created at :") +
                        dt.toLocalTime().toString()) +
                htmlDiv("content",contentParser(json["content"].toString()))
                )
        );
    if (json["reblog"].isNull()) {
        QString media;
        bool sensitive = json["sensitive"].toBool();
        for (auto j:json["media_attachments"].toArray()) {
            media += mediaParser(j.toObject(),sensitive);
        }
        result += htmlDiv("media",media);
    }
    return result;
}

const QString SaoriView::accountParser(const QJsonObject json)
{
    QString result;
    if (json.isEmpty()) return QString();
    result = htmlDiv("account",
                     htmlAnc("accounts:" + json["id"].toString(),
                             htmlSpan("avatar",
                                      htmlHr() +
                                      htmlImg("avatar",json["avatar"].toString())) +
                             htmlSpan("display_name",
                                      json["display_name"].toString()) +
                             " " +
                             htmlSpan("acct","@" + json["acct"].toString())
                            ) +
                     htmlDiv("user_info",
                             tr(" following: ") +
                             QString::number(json["following_count"].toInt()) +
                             tr(" followers: ") +
                             QString::number(json["followers_count"].toInt())
                            )
                    );
    return result;
}

const QString SaoriView::mediaParser(const QJsonObject json, bool sensitive)
{
    QString result,media;
    if (sensitive) media = "nsfwmedia";
    else media = "media";
    result = htmlSpan("media_preview",
                      json["type"].toString() == "image" ?
                        htmlAnc("media:" + json["url"].toString(),htmlImg(media,json["preview_url"].toString())) :
                        htmlImg(media,json["preview_url"].toString()));
    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;
}

const QString SaoriView::notificationParser(const QJsonObject json)
{
    QString result;
    if (json.isEmpty()) return QString();

    QDateTime dt = QDateTime::fromString(json["created_at"].toString(),"yyyy-MM-ddTHH:mm:ss.zzzZ");
    dt.setTimeSpec(Qt::UTC);

    QStringList type;
    type << "mention" << "reblog" << "favourite" << "follow";
    QString title;
    switch (type.indexOf(json["type"].toString())) {
    case 0:
        title += htmlImg("mavatar",":/icons/ionicons/chatbubbles.svg");
        title += tr("%1 mentioned your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 1:
        title += htmlImg("mavatar",":/icons/ionicons/share.svg");
        title += tr("%1 boosted your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 2:
        title += htmlImg("mavatar",":/icons/ionicons/heart.svg");
        title += tr("%1 favourited your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 3:
        title += htmlImg("mavatar",":/icons/ionicons/person-add.svg");
        title += tr("%1 followed you.").arg(json["account"].toObject()["display_name"].toString());
        break;
    default:
        break;
    }

    result = htmlDiv("notification",
                     htmlDiv("notification_type",title + htmlHr()) +
                     htmlDiv("created_at",tr("created at :") + dt.toLocalTime().toString()) +
                     statusParser(json["status"].toObject()) +
                     htmlAnc("accounts:" + json["account"].toObject()["id"].toString(),
                             htmlDiv("reblogger",htmlHr() +
                                     htmlImg("mavatar",json["account"].toObject()["avatar"].toString()) +
                                     tr("%1 (@%2)").arg(json["account"].toObject()["display_name"].toString(),
                                                        json["account"].toObject()["acct"].toString())
                                    )
                            )
                     );
    return result;
}

const QString SaoriView::htmlDiv(const QString divclass, const QString text)
{
    return QString("<div class=\"%1\">\n%2\n</div>\n").arg(divclass,text);
}

const QString SaoriView::htmlSpan(const QString spanclass, const QString text)
{
    return QString("<span class=\"%1\">%2</span>").arg(spanclass,text);
}

const QString SaoriView::htmlImg(const QString type, const QString url)
{
    return QString("<img(%1:%2) />").arg(type,url);
}

const QString SaoriView::htmlAnc(const QString link, const QString text)
{
    return QString("<a href=\"%1\">%2</a>").arg(link,text);
}

const QString SaoriView::htmlHr()
{
    return QString("<hr />");
}

void SaoriView::recived(const QString timeline,const QByteArray data)
{
    if (timeline != m_viewname) return;
    qDebug() << "resived " + timeline;
    QJsonArray json = QJsonDocument::fromJson(data).array();
    for (auto j:json) {
        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);
                break;
            }
            if (m_entries.at(i)->id() < j.toObject()["id"].toString().toLongLong()) break;
        }
        if (entry == nullptr) {
            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);
            if (m_viewname == "notifications") entry->setContent(notificationParser(j.toObject()));
            else entry->setContent(statusParser(j.toObject()));
        }
    }
    if (m_entries.count()) {
        if (m_entries.first()->id() > m_maxid) reload();
    }
}

void SaoriView::linkClicked(const QUrl &url)
{
    if (url.toString().left(6) == "media:") {
        QUrl u(url.toString().mid(6));
        emit openMediaView(u);
    }
    if (url.toString().left(9) == "accounts:") {
        QStringList v;
        v << m_account << url.toString().mid(9);
        emit openAccountView(v);
    }
}

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

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