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