File: ratingshelper.cpp

package info (click to toggle)
dde-store 1.2.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 740 kB
  • sloc: cpp: 2,037; makefile: 3
file content (60 lines) | stat: -rw-r--r-- 1,907 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "ratingshelper.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QtMath>
#include <QDebug>

RatingsHelper *RatingsHelper::currentInstance = nullptr;

RatingsHelper *RatingsHelper::instance()
{
    if (!currentInstance) {
        currentInstance = new RatingsHelper;
    }
    return currentInstance;
}

RatingsHelper::RatingsHelper()
{
    QNetworkAccessManager *networkManager = new QNetworkAccessManager;
    QNetworkRequest request(QUrl("https://odrs.gnome.org/1.0/reviews/api/ratings"));
    networkManager->get(request);
    qDebug() << "[ RATINGS ] Fetching ratings...";
    connect(networkManager, &QNetworkAccessManager::finished, this, [ = ] (QNetworkReply *reply) {
        QByteArray data = reply->readAll();
        QJsonObject array = QJsonDocument::fromJson(data).object();
        for (const QString &key : array.keys()) {
            ratingsList.insert(key, array.value(key).toObject());
        }
        emit(fetched());
        available = true;
        qDebug() << "[ RATINGS ] Ratings fetched";
        disconnect(this, &RatingsHelper::fetched, nullptr, nullptr);
    });
}

double RatingsHelper::averageRating(QString app)
{
    double ratings = 0;
    ratings += ratingsList.value(app).value("star1").toInt();
    ratings += ratingsList.value(app).value("star2").toInt() * 2;
    ratings += ratingsList.value(app).value("star3").toInt() * 3;
    ratings += ratingsList.value(app).value("star4").toInt() * 4;
    ratings += ratingsList.value(app).value("star5").toInt() * 5;
    double rating = floor((ratings / totalRatings(app) * 2) + 0.5) / 2;
    if (rating != rating) {
        rating = 0;
    }
    return rating;
}

int RatingsHelper::totalRatings(QString app)
{
    int total = ratingsList.value(app).value("total").toInt();
    if (total != total) {
        total = 0;
    }
    return total;
}