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