9
|
1 #include "services/anilist.h"
|
|
2 #include "core/anime.h"
|
10
|
3 #include "core/anime_db.h"
|
9
|
4 #include "core/config.h"
|
|
5 #include "core/json.h"
|
|
6 #include "core/session.h"
|
|
7 #include "core/strings.h"
|
15
|
8 #include "gui/translate/anilist.h"
|
9
|
9 #include <QDesktopServices>
|
|
10 #include <QInputDialog>
|
|
11 #include <QLineEdit>
|
|
12 #include <QMessageBox>
|
10
|
13 #include <QUrl>
|
9
|
14 #include <chrono>
|
|
15 #include <curl/curl.h>
|
|
16 #include <exception>
|
|
17 #include <format>
|
|
18 #define CLIENT_ID "13706"
|
|
19
|
15
|
20 using nlohmann::literals::operator"" _json_pointer;
|
11
|
21
|
9
|
22 namespace Services::AniList {
|
|
23
|
|
24 class Account {
|
|
25 public:
|
10
|
26 std::string Username() const { return session.config.anilist.username; }
|
15
|
27 void SetUsername(std::string const& username) {
|
|
28 session.config.anilist.username = username;
|
|
29 }
|
9
|
30
|
10
|
31 int UserId() const { return session.config.anilist.user_id; }
|
|
32 void SetUserId(const int id) { session.config.anilist.user_id = id; }
|
9
|
33
|
10
|
34 std::string AuthToken() const { return session.config.anilist.auth_token; }
|
15
|
35 void SetAuthToken(std::string const& auth_token) {
|
|
36 session.config.anilist.auth_token = auth_token;
|
|
37 }
|
9
|
38
|
|
39 bool Authenticated() const { return !AuthToken().empty(); }
|
10
|
40 };
|
9
|
41
|
|
42 static Account account;
|
|
43
|
|
44 static size_t CurlWriteCallback(void* contents, size_t size, size_t nmemb, void* userdata) {
|
|
45 ((std::string*)userdata)->append((char*)contents, size * nmemb);
|
|
46 return size * nmemb;
|
|
47 }
|
|
48
|
|
49 /* A wrapper around cURL to send requests to AniList */
|
|
50 std::string SendRequest(std::string data) {
|
|
51 struct curl_slist* list = NULL;
|
|
52 std::string userdata;
|
|
53 CURL* curl = curl_easy_init();
|
|
54 if (curl) {
|
15
|
55 std::string bearer = "Authorization: Bearer " + account.AuthToken();
|
9
|
56 list = curl_slist_append(list, "Accept: application/json");
|
|
57 list = curl_slist_append(list, "Content-Type: application/json");
|
|
58 list = curl_slist_append(list, bearer.c_str());
|
|
59 curl_easy_setopt(curl, CURLOPT_URL, "https://graphql.anilist.co");
|
|
60 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
|
|
61 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
|
|
62 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &userdata);
|
|
63 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlWriteCallback);
|
|
64 /* Use system certs... useful on Windows. */
|
|
65 curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
|
|
66 CURLcode res = curl_easy_perform(curl);
|
|
67 curl_slist_free_all(list);
|
|
68 curl_easy_cleanup(curl);
|
|
69 if (res != CURLE_OK) {
|
|
70 QMessageBox box(QMessageBox::Icon::Critical, "",
|
15
|
71 QString("curl_easy_perform(curl) failed!: ") +
|
|
72 QString(curl_easy_strerror(res)));
|
9
|
73 box.exec();
|
|
74 return "";
|
|
75 }
|
|
76 return userdata;
|
|
77 }
|
|
78 return "";
|
|
79 }
|
|
80
|
15
|
81 void ParseListStatus(std::string status, Anime::Anime& anime) {
|
|
82 std::unordered_map<std::string, Anime::ListStatus> map = {
|
|
83 {"CURRENT", Anime::ListStatus::CURRENT },
|
|
84 {"PLANNING", Anime::ListStatus::PLANNING },
|
|
85 {"COMPLETED", Anime::ListStatus::COMPLETED},
|
|
86 {"DROPPED", Anime::ListStatus::DROPPED },
|
|
87 {"PAUSED", Anime::ListStatus::PAUSED }
|
|
88 };
|
9
|
89
|
15
|
90 if (status == "REPEATING") {
|
|
91 anime.SetUserIsRewatching(true);
|
|
92 anime.SetUserStatus(Anime::ListStatus::CURRENT);
|
|
93 return;
|
|
94 }
|
9
|
95
|
15
|
96 if (!map.contains(status)) {
|
|
97 anime.SetUserStatus(Anime::ListStatus::NOT_IN_LIST);
|
|
98 return;
|
|
99 }
|
9
|
100
|
15
|
101 anime.SetUserStatus(map[status]);
|
|
102 }
|
9
|
103
|
15
|
104 std::string ListStatusToString(const Anime::Anime& anime) {
|
|
105 std::unordered_map<Anime::ListStatus, std::string> map = {
|
|
106 {Anime::ListStatus::CURRENT, "CURRENT" },
|
|
107 {Anime::ListStatus::PLANNING, "PLANNING" },
|
|
108 {Anime::ListStatus::COMPLETED, "COMPLETED"},
|
|
109 {Anime::ListStatus::DROPPED, "DROPPED" },
|
|
110 {Anime::ListStatus::PAUSED, "PAUSED" }
|
|
111 };
|
9
|
112
|
15
|
113 if (anime.GetUserIsRewatching())
|
|
114 return "REWATCHING";
|
|
115
|
|
116 if (!map.contains(anime.GetUserStatus()))
|
|
117 return "CURRENT";
|
|
118 return map[anime.GetUserStatus()];
|
|
119 }
|
9
|
120
|
10
|
121 Date ParseDate(const nlohmann::json& json) {
|
|
122 Date date;
|
11
|
123 if (json.contains("/year"_json_pointer) && json.at("/year"_json_pointer).is_number())
|
9
|
124 date.SetYear(JSON::GetInt(json, "/year"_json_pointer));
|
|
125 else
|
|
126 date.VoidYear();
|
|
127
|
11
|
128 if (json.contains("/month"_json_pointer) && json.at("/month"_json_pointer).is_number())
|
9
|
129 date.SetMonth(JSON::GetInt(json, "/month"_json_pointer));
|
|
130 else
|
|
131 date.VoidMonth();
|
|
132
|
11
|
133 if (json.contains("/day"_json_pointer) && json.at("/day"_json_pointer).is_number())
|
9
|
134 date.SetDay(JSON::GetInt(json, "/day"_json_pointer));
|
|
135 else
|
|
136 date.VoidDay();
|
10
|
137 return date;
|
9
|
138 }
|
|
139
|
|
140 void ParseTitle(const nlohmann::json& json, Anime::Anime& anime) {
|
|
141 anime.SetNativeTitle(JSON::GetString(json, "/native"_json_pointer));
|
|
142 anime.SetEnglishTitle(JSON::GetString(json, "/english"_json_pointer));
|
|
143 anime.SetRomajiTitle(JSON::GetString(json, "/romaji"_json_pointer));
|
|
144 }
|
|
145
|
|
146 int ParseMediaJson(const nlohmann::json& json) {
|
|
147 int id = JSON::GetInt(json, "/id"_json_pointer);
|
|
148 if (!id)
|
|
149 return 0;
|
|
150 Anime::Anime& anime = Anime::db.items[id];
|
|
151 anime.SetId(id);
|
|
152
|
11
|
153 ParseTitle(json.at("/title"_json_pointer), anime);
|
9
|
154
|
|
155 anime.SetEpisodes(JSON::GetInt(json, "/episodes"_json_pointer));
|
15
|
156 anime.SetFormat(Translate::AniList::ToSeriesFormat(JSON::GetString(json, "/format"_json_pointer)));
|
9
|
157
|
15
|
158 anime.SetAiringStatus(Translate::AniList::ToSeriesStatus(JSON::GetString(json, "/status"_json_pointer)));
|
9
|
159
|
10
|
160 anime.SetAirDate(ParseDate(json["/startDate"_json_pointer]));
|
9
|
161
|
|
162 anime.SetAudienceScore(JSON::GetInt(json, "/averageScore"_json_pointer));
|
15
|
163 anime.SetSeason(Translate::AniList::ToSeriesSeason(JSON::GetString(json, "/season"_json_pointer)));
|
9
|
164 anime.SetDuration(JSON::GetInt(json, "/duration"_json_pointer));
|
10
|
165 anime.SetSynopsis(Strings::TextifySynopsis(JSON::GetString(json, "/description"_json_pointer)));
|
9
|
166
|
|
167 if (json.contains("/genres"_json_pointer) && json["/genres"_json_pointer].is_array())
|
|
168 anime.SetGenres(json["/genres"_json_pointer].get<std::vector<std::string>>());
|
|
169 if (json.contains("/synonyms"_json_pointer) && json["/synonyms"_json_pointer].is_array())
|
10
|
170 anime.SetTitleSynonyms(json["/synonyms"_json_pointer].get<std::vector<std::string>>());
|
|
171 return id;
|
9
|
172 }
|
|
173
|
10
|
174 int ParseListItem(const nlohmann::json& json) {
|
|
175 int id = ParseMediaJson(json["media"]);
|
|
176
|
|
177 Anime::Anime& anime = Anime::db.items[id];
|
|
178
|
|
179 anime.AddToUserList();
|
9
|
180
|
10
|
181 anime.SetUserScore(JSON::GetInt(json, "/score"_json_pointer));
|
|
182 anime.SetUserProgress(JSON::GetInt(json, "/progress"_json_pointer));
|
15
|
183 ParseListStatus(JSON::GetString(json, "/status"_json_pointer), anime);
|
10
|
184 anime.SetUserNotes(JSON::GetString(json, "/notes"_json_pointer));
|
9
|
185
|
10
|
186 anime.SetUserDateStarted(ParseDate(json["/startedAt"_json_pointer]));
|
|
187 anime.SetUserDateCompleted(ParseDate(json["/completedAt"_json_pointer]));
|
9
|
188
|
10
|
189 anime.SetUserTimeUpdated(JSON::GetInt(json, "/updatedAt"_json_pointer));
|
|
190
|
|
191 return id;
|
9
|
192 }
|
|
193
|
|
194 int ParseList(const nlohmann::json& json) {
|
|
195 for (const auto& entry : json["entries"].items()) {
|
|
196 ParseListItem(entry.value());
|
|
197 }
|
10
|
198 return 1;
|
9
|
199 }
|
|
200
|
10
|
201 int GetAnimeList() {
|
9
|
202 /* NOTE: these should be in the qrc file */
|
|
203 const std::string query = "query ($id: Int) {\n"
|
15
|
204 " MediaListCollection (userId: $id, type: ANIME) {\n"
|
|
205 " lists {\n"
|
|
206 " name\n"
|
|
207 " entries {\n"
|
|
208 " score\n"
|
|
209 " notes\n"
|
|
210 " status\n"
|
|
211 " progress\n"
|
|
212 " startedAt {\n"
|
|
213 " year\n"
|
|
214 " month\n"
|
|
215 " day\n"
|
|
216 " }\n"
|
|
217 " completedAt {\n"
|
|
218 " year\n"
|
|
219 " month\n"
|
|
220 " day\n"
|
|
221 " }\n"
|
|
222 " updatedAt\n"
|
|
223 " media {\n"
|
|
224 " id\n"
|
|
225 " title {\n"
|
|
226 " romaji\n"
|
|
227 " english\n"
|
|
228 " native\n"
|
|
229 " }\n"
|
|
230 " format\n"
|
|
231 " status\n"
|
|
232 " averageScore\n"
|
|
233 " season\n"
|
|
234 " startDate {\n"
|
|
235 " year\n"
|
|
236 " month\n"
|
|
237 " day\n"
|
|
238 " }\n"
|
|
239 " genres\n"
|
|
240 " episodes\n"
|
|
241 " duration\n"
|
|
242 " synonyms\n"
|
|
243 " description(asHtml: false)\n"
|
|
244 " }\n"
|
|
245 " }\n"
|
|
246 " }\n"
|
|
247 " }\n"
|
|
248 "}\n";
|
9
|
249 // clang-format off
|
|
250 nlohmann::json json = {
|
|
251 {"query", query},
|
|
252 {"variables", {
|
10
|
253 {"id", account.UserId()}
|
9
|
254 }}
|
|
255 };
|
|
256 // clang-format on
|
|
257 /* TODO: do a try catch here, catch any json errors and then call
|
|
258 Authorize() if needed */
|
|
259 auto res = nlohmann::json::parse(SendRequest(json.dump()));
|
|
260 /* TODO: make sure that we actually need the wstring converter and see
|
|
261 if we can just get wide strings back from nlohmann::json */
|
|
262 for (const auto& list : res["data"]["MediaListCollection"]["lists"].items()) {
|
10
|
263 ParseList(list.value());
|
9
|
264 }
|
|
265 return 1;
|
|
266 }
|
|
267
|
10
|
268 int UpdateAnimeEntry(const Anime::Anime& anime) {
|
9
|
269 /**
|
|
270 * possible values:
|
15
|
271 *
|
9
|
272 * int mediaId,
|
|
273 * MediaListStatus status,
|
|
274 * float score,
|
|
275 * int scoreRaw,
|
|
276 * int progress,
|
|
277 * int progressVolumes,
|
|
278 * int repeat,
|
|
279 * int priority,
|
|
280 * bool private,
|
|
281 * string notes,
|
|
282 * bool hiddenFromStatusLists,
|
|
283 * string[] customLists,
|
|
284 * float[] advancedScores,
|
|
285 * Date startedAt,
|
|
286 * Date completedAt
|
15
|
287 **/
|
|
288 const std::string query = "mutation ($media_id: Int, $progress: Int, $status: MediaListStatus, "
|
|
289 "$score: Int, $notes: String) {\n"
|
|
290 " SaveMediaListEntry (mediaId: $media_id, progress: $progress, "
|
|
291 "status: $status, scoreRaw: $score, notes: "
|
|
292 "$notes) {\n"
|
|
293 " id\n"
|
|
294 " }\n"
|
|
295 "}\n";
|
9
|
296 // clang-format off
|
|
297 nlohmann::json json = {
|
|
298 {"query", query},
|
|
299 {"variables", {
|
10
|
300 {"media_id", anime.GetId()},
|
|
301 {"progress", anime.GetUserProgress()},
|
15
|
302 {"status", ListStatusToString(anime)},
|
10
|
303 {"score", anime.GetUserScore()},
|
|
304 {"notes", anime.GetUserNotes()}
|
9
|
305 }}
|
|
306 };
|
|
307 // clang-format on
|
|
308 SendRequest(json.dump());
|
|
309 return 1;
|
|
310 }
|
|
311
|
|
312 int ParseUser(const nlohmann::json& json) {
|
|
313 account.SetUsername(JSON::GetString(json, "/name"_json_pointer));
|
|
314 account.SetUserId(JSON::GetInt(json, "/id"_json_pointer));
|
10
|
315 return account.UserId();
|
9
|
316 }
|
|
317
|
|
318 int AuthorizeUser() {
|
|
319 /* Prompt for PIN */
|
15
|
320 QDesktopServices::openUrl(QUrl("https://anilist.co/api/v2/oauth/authorize?client_id=" CLIENT_ID
|
|
321 "&response_type=token"));
|
9
|
322 bool ok;
|
|
323 QString token = QInputDialog::getText(
|
15
|
324 0, "Credentials needed!",
|
|
325 "Please enter the code given to you after logging in to AniList:", QLineEdit::Normal, "",
|
|
326 &ok);
|
9
|
327 if (ok && !token.isEmpty())
|
|
328 account.SetAuthToken(token.toStdString());
|
15
|
329 else // fail
|
9
|
330 return 0;
|
|
331 const std::string query = "query {\n"
|
15
|
332 " Viewer {\n"
|
|
333 " id\n"
|
|
334 " name\n"
|
|
335 " mediaListOptions {\n"
|
|
336 " scoreFormat\n"
|
|
337 " }\n"
|
|
338 " }\n"
|
|
339 "}\n";
|
9
|
340 nlohmann::json json = {
|
15
|
341 {"query", query}
|
|
342 };
|
9
|
343 auto ret = nlohmann::json::parse(SendRequest(json.dump()));
|
10
|
344 ParseUser(json["Viewer"]);
|
9
|
345 return 1;
|
|
346 }
|
|
347
|
|
348 } // namespace Services::AniList
|