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