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 "ui_saoriview.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrlQuery>
#include <QLabel>
#include <QScrollBar>
#include <QDebug>
#include <QDateTime>
#include <QTimer>
#include <QBoxLayout>
#include "saoriapplication.h"
#include "saoriview.h"
#include "saoridef.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_timecount = 0;
    m_viewname = view;
    m_account = account;
    m_viewList.append(this);
    m_maxid = 0;
    m_sinceid = 0;

    m_config = "/" + m_account + "/" + m_viewname;
    ui->actionPin->setChecked(
                SaoriApplication::saori()->setting()->value(SAORI_SETTING_VIEW + m_config + SAORI_SETTING_VIEW_PINED,false).toBool());

    connect(ui->header,&SaoriViewEntry::anchorClicked,this,&SaoriView::linkClicked);
    ui->header->setOpenLinks(false);
    ui->header->setOpenExternalLinks(false);
    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") {
        footter->hide();
        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);
        if (view.left(9) == "accounts:") {
            QStringList t = view.split(':');
            if (t.count() >= 2) {
                saoriaccount->getTimelineData(t[0] + ":" + t[1],QUrlQuery());
                connect(saoriaccount,&SaoriAccount::relationship,this,&SaoriView::relationship);
                saoriaccount->getRelationship(t[1].toLongLong());
            }
        }
        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_maxid));
                    saoriaccount->getTimelineData(view,q);
                }
            }
        });
        connect(saoriaccount,&SaoriAccount::accountInfomationChanged,this,[=](){
            ui->tootWidget->setAccountLabel(QString("%1(@%2@%3)").arg(
                                                saoriaccount->accountInfo("display_name").toString(),
                                                saoriaccount->accountInfo("username").toString(),
                                                saoriaccount->instance()->instanceInfo("uri").toString()));
        });
        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);
        });
    }
    QTimer::singleShot(60000,this,&SaoriView::timerUpdate);
}

SaoriView::~SaoriView()
{
    savePinnedGeometry();
    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;
}

QList<SaoriView *> SaoriView::findView(const QString account)
{
    QList<SaoriView *> result;
    for(auto v:m_viewList) {
        if (v->m_account == account) result.append(v);
    }
    return result;
}

void SaoriView::reload()
{
    auto saoriaccount = SaoriApplication::saori()->findAccount(m_account);
    if (saoriaccount == nullptr) return;
    QUrlQuery query;
    query.addQueryItem("since_id",QString::number(m_sinceid));
    saoriaccount->getTimelineData(m_viewname,query);
}

const QString SaoriView::headerParser(const QJsonObject json, bool followed, bool following, bool muting, bool blocking)
{
    qDebug() << m_header["id"].toString().toLongLong() << followed << following << muting << blocking;
    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()));
    result += htmlHr();
    result += htmlDiv("tools",
                      htmlAnc("accounts:" + json["id"].toString() + ":statuses",
                              tr(" statuses: ") +
                              QString::number(json["statuses_count"].toInt())) +
                      htmlAnc("accounts:" + json["id"].toString() + ":following",
                              tr(" following: ") +
                              QString::number(json["following_count"].toInt())) +
                      htmlAnc("accounts:" + json["id"].toString() + ":followers",
                              tr(" followers: ") +
                              QString::number(json["followers_count"].toInt()))
           );

    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);

    result = (!json["reblog"].isNull()) ?
        (statusParser(json["reblog"].toObject()) +
                htmlAnc("accounts:" + json["account"].toObject()["id"].toString() + ":statuses",
                        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()) +
                (json["spoiler_text"].toString().isEmpty() ? QString() :
                    htmlDiv("cw",json["spoiler_text"].toString()) +
                    htmlAnc("cw:",tr("[more]"))) +
                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);

        QString visibility;
        QStringList vl;
        vl << "public" << "unlisted" << "private" << "direct";
        switch (vl.indexOf(json["visibility"].toString())) {
        case 0:
            visibility = htmlImg("icon",SAORI_ICONS_GLOBAL);
            break;
        case 1:
            visibility = htmlImg("icon",SAORI_ICONS_UNLOCK);
            break;
        case 2:
            visibility = htmlImg("icon",SAORI_ICONS_LOCK);
            break;
        case 3:
            visibility = htmlImg("icon",SAORI_ICONS_PERSON);
            break;
        default:
            break;
        }
        result += htmlDiv("tools",
                          visibility + "  " +
                          htmlAnc("reply:" + json["id"].toString(),
                                  htmlImg("icon",SAORI_ICONS_RELPY)) + " " +
                          htmlAnc("boost:" + json["id"].toString(),
                                  htmlImg("icon",SAORI_ICONS_SHARE)) +
                          QString::number(json["reblogs_count"].toInt()) +
                          htmlAnc("fav:" + json["id"].toString(),
                                  htmlImg("icon",SAORI_ICONS_STAR)) +
                          QString::number(json["favourites_count"].toInt())
                          );
    }
    return result;
}

const QString SaoriView::accountParser(const QJsonObject json)
{
    QString result;
    if (json.isEmpty()) return QString();
    result = htmlDiv("account",
                     htmlAnc("accounts:" + json["id"].toString() + ":statuses",
                             htmlSpan("avatar",
                                      htmlHr() +
                                      htmlImg("avatar",json["avatar"].toString())) +
                             htmlSpan("display_name",
                                      json["display_name"].toString()) +
                             " " +
                             htmlSpan("acct","@" + json["acct"].toString())
                            ) +
                     htmlDiv("user_info",
                             htmlAnc("accounts:" + json["id"].toString() + ":following",
                                     tr(" following: ") +
                                     QString::number(json["following_count"].toInt())) +
                             htmlAnc("accounts:" + json["id"].toString() + ":followers",
                                     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",SAORI_ICONS_CHAT);
        title += tr("%1 mentioned your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 1:
        title += htmlImg("mavatar",SAORI_ICONS_SHARE);
        title += tr("%1 boosted your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 2:
        title += htmlImg("mavatar",SAORI_ICONS_STAR);
        title += tr("%1 favourited your status.").arg(json["account"].toObject()["display_name"].toString());
        break;
    case 3:
        title += htmlImg("mavatar",SAORI_ICONS_PERSONADD);
        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() + ":statuses",
                             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::followerParser(const QJsonObject json)
{
    return accountParser(json);
}

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::savePinnedGeometry()
{
    SaoriApplication::saori()->setting()->beginGroup(SAORI_SETTING_VIEW);
    if ((ui->actionPin->isChecked()) && (!(qobject_cast<QWidget *>(parent())->windowState() & Qt::WindowMaximized))) {
        SaoriApplication::saori()->setting()->setValue(m_config + SAORI_SETTING_VIEW_GEOMETRY,
                                                       qobject_cast<QWidget *>(parent())->geometry());
    }
    SaoriApplication::saori()->setting()->setValue(m_config + SAORI_SETTING_VIEW_PINED,ui->actionPin->isChecked());
    SaoriApplication::saori()->setting()->endGroup();
}

void SaoriView::closeEvent(QCloseEvent *event)
{
    if (ui->actionPin->isChecked()) event->ignore();
    else QWidget::closeEvent(event);
}

void SaoriView::getIdsFromHeader(const QByteArray header)
{
    QString l(header);
    int n1 = l.indexOf("&max_id=") + 8;
    int n2 = l.indexOf('>',n1);
    qlonglong maxid =  l.mid(n1,n2 - n1).toLongLong();
    n1 = l.indexOf("&since_id=") + 10;
    n2 = l.indexOf('>',n1);
    qlonglong sinceid =  l.mid(n1,n2 - n1).toLongLong();
    if (maxid) {
        if (m_maxid == 0) m_maxid = maxid;
        m_maxid = m_maxid > maxid ? maxid : m_maxid;
    }
    if (sinceid) {
        if (m_sinceid == 0) m_sinceid = sinceid;
        m_sinceid = m_sinceid < sinceid ? sinceid : m_sinceid;
    }
}

void SaoriView::recived(const QString timeline, const QByteArray data, const QByteArray link)
{
    if ((timeline.left(9) == "accounts:") && (m_viewname.left(9) == "accounts:")) {
        QStringList t = timeline.split(':');
        if (t.count() == 2) {
            if (t[1] == m_viewname.split(':')[1]) {
                m_header = QJsonDocument::fromJson(data).object();
                ui->header->setContent(headerParser(m_header,false,false,false,false));
                ui->header->show();
            }
        }
    }
    if (timeline != m_viewname) return;
    qlonglong s = m_sinceid;
    getIdsFromHeader(link);
    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);
        }

        // NOTE:ここから
        if (m_viewname == "notifications") entry->setContent(notificationParser(j.toObject()));
        else if ((m_viewname.split(':')[0] == "accounts") && (m_viewname.split(':')[2] == "followers")) {
            entry->setContent(followerParser(j.toObject()));
        } else if ((m_viewname.split(':')[0] == "accounts") && (m_viewname.split(':')[2] == "following")) {
            entry->setContent(followerParser(j.toObject()));
        } else {
            bool cw = !j.toObject()["spoiler_text"].toString().isEmpty();
            if (!j.toObject()["reblog"].isNull())
                cw = !j.toObject()["reblog"].toObject()["spoiler_text"].toString().isEmpty();
            entry->setContent(statusParser(j.toObject()),cw);
        }
        // NOTE:ここまでを上ifに含めると取得済みエントリを再描画しなくなる。
    }
    if (s != m_sinceid) reload();
    viewEntriesAdjustment();
}

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();
        emit openAccountView(v);
    }
}

void SaoriView::timerUpdate()
{
    m_timecount ++;
    if (ui->actionAutoreload->isChecked()) {
        if (m_timecount >= SaoriApplication::saori()->setting()->value(
                    SAORI_SETTING_RELOADINT,SAORI_SETTING_RELOADINT_DEFAULT).toInt()) {
            reload();
            m_timecount = 0;
        }
    }
    QTimer::singleShot(60000,this,&SaoriView::timerUpdate);
}

void SaoriView::viewEntriesAdjustment()
{
    int showentries = SaoriApplication::saori()->setting()->value(SAORI_SETTING_SHOWENTRIES,
                                                                  SAORI_SETTING_SHOWENTRIES_DEFAULT).toInt();
    int e = m_entries.count() - showentries;
    if (e <= 0) return;
    while (showentries < m_entries.count()) {
        delete m_entries.takeLast();
    }
    return;
}

void SaoriView::relationship(qlonglong id, QJsonObject data)
{
    QStringList t = m_viewname.split(':');
    if (t[1].toLongLong() == id) {
        headerParser(m_header,
                     data["following"].toBool(),
                     data["followed_by"].toBool(),
                     data["muting"].toBool(),
                     data["blocking"].toBool());
    }
}

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

void SaoriView::on_actionNewest_triggered()
{
    if (ui->scrollArea->verticalScrollBar()->value() <= 0) {
        viewEntriesAdjustment();
        return;
    }
    ui->scrollArea->verticalScrollBar()->setValue(
                ui->scrollArea->verticalScrollBar()->value() - (ui->scrollArea->verticalScrollBar()->value() / 10) - 1);
    QTimer::singleShot(10,this,&SaoriView::on_actionNewest_triggered);
}