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