-
-
Notifications
You must be signed in to change notification settings - Fork 441
/
FfzBadges.cpp
113 lines (91 loc) · 3.21 KB
/
FfzBadges.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "FfzBadges.hpp"
#include "common/NetworkRequest.hpp"
#include "common/NetworkResult.hpp"
#include "common/Outcome.hpp"
#include "messages/Emote.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include <QUrl>
#include <map>
#include <shared_mutex>
namespace chatterino {
void FfzBadges::initialize(Settings &settings, Paths &paths)
{
this->load();
}
std::vector<FfzBadges::Badge> FfzBadges::getUserBadges(const UserId &id)
{
std::vector<Badge> badges;
std::shared_lock lock(this->mutex_);
auto it = this->userBadges.find(id.string);
if (it != this->userBadges.end())
{
for (const auto &badgeID : it->second)
{
if (auto badge = this->getBadge(badgeID); badge)
{
badges.emplace_back(*badge);
}
}
}
return badges;
}
boost::optional<FfzBadges::Badge> FfzBadges::getBadge(const int badgeID)
{
auto it = this->badges.find(badgeID);
if (it != this->badges.end())
{
return it->second;
}
return boost::none;
}
void FfzBadges::load()
{
static QUrl url("https://api.frankerfacez.com/v1/badges/ids");
NetworkRequest(url)
.onSuccess([this](auto result) -> Outcome {
std::unique_lock lock(this->mutex_);
auto jsonRoot = result.parseJson();
for (const auto &jsonBadge_ : jsonRoot.value("badges").toArray())
{
auto jsonBadge = jsonBadge_.toObject();
auto jsonUrls = jsonBadge.value("urls").toObject();
auto emote = Emote{
EmoteName{},
ImageSet{
Url{QString("https:") + jsonUrls.value("1").toString()},
Url{QString("https:") + jsonUrls.value("2").toString()},
Url{QString("https:") +
jsonUrls.value("4").toString()}},
Tooltip{jsonBadge.value("title").toString()}, Url{}};
Badge badge;
int badgeID = jsonBadge.value("id").toInt();
this->badges[badgeID] = Badge{
std::make_shared<const Emote>(std::move(emote)),
QColor(jsonBadge.value("color").toString()),
};
// Find users with this badge
auto badgeIDString = QString::number(badgeID);
for (const auto &user : jsonRoot.value("users")
.toObject()
.value(badgeIDString)
.toArray())
{
auto userIDString = QString::number(user.toInt());
auto [userBadges, created] = this->userBadges.emplace(
std::make_pair<QString, std::set<int>>(
std::move(userIDString), {badgeID}));
if (!created)
{
// User already had a badge assigned
userBadges->second.emplace(badgeID);
}
}
}
return Success;
})
.execute();
}
} // namespace chatterino