1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
import type { AniListAuthorisation } from '$lib/AniList/identity';
import type { UserIdentity } from './identity';
import anime from '../../stores/anime';
import manga from '../../stores/manga';
import settings from '../../stores/settings';
import lastPruneTimes from '../../stores/lastPruneTimes';
export enum Type {
Anime,
Manga
}
export interface Media {
id: number;
status: string;
type: string;
episodes: number;
chapters: number;
format: string;
title: {
romaji: string;
english: string;
native: string;
};
nextAiringEpisode?: {
episode: number;
timeUntilAiring?: number;
};
mediaListEntry?: {
progress: number;
status: string;
score: number;
startedAt: {
year: number;
};
};
startDate: {
year: number;
};
coverImage: {
extraLarge: string;
};
}
export const flattenLists = (lists: { entries: { media: Media }[] }[]) => {
if (lists === undefined) {
return [];
}
let flattenedList: { media: Media }[] = [];
const minimisedList: Media[] = [];
for (const list of lists) {
flattenedList = flattenedList.concat(list.entries);
}
for (const [position, entry] of flattenedList.entries()) {
minimisedList[position] = entry.media;
}
return minimisedList.filter((item, index, array) => {
return (
array.findIndex((i) => {
return i.id === item.id;
}) === index
);
});
};
export const mediaListCollection = async (
anilistAuthorisation: AniListAuthorisation,
userIdentity: UserIdentity,
type: Type,
mediaCache: string | undefined,
currentLastPruneAt: string | number,
forcePrune = false,
includeCompleted = false
): Promise<Media[]> => {
let currentCacheMinutes;
settings.subscribe((value) => {
currentCacheMinutes = value.cacheMinutes;
});
if (String(currentLastPruneAt) === '') {
if (type === Type.Anime) {
lastPruneTimes.setKey('anime', new Date().getTime());
} else {
lastPruneTimes.setKey('manga', new Date().getTime());
}
} else {
if (
(new Date().getTime() - Number(currentLastPruneAt)) / 1000 / 60 >
Number(currentCacheMinutes) ||
forcePrune
) {
if (type === Type.Anime) {
lastPruneTimes.setKey('anime', new Date().getTime());
anime.set('');
} else {
lastPruneTimes.setKey('manga', new Date().getTime());
manga.set('');
}
mediaCache = '';
}
}
if (mediaCache !== undefined && mediaCache !== '') {
return JSON.parse(mediaCache);
}
const userIdResponse = await (
await fetch('https://graphql.anilist.co', {
method: 'POST',
headers: {
Authorization: `${anilistAuthorisation.tokenType} ${anilistAuthorisation.accessToken}`,
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
query: `{ MediaListCollection(userId: ${userIdentity.id}, type: ${
type === Type.Anime ? 'ANIME' : 'MANGA'
}${includeCompleted ? '' : ', status_not_in: [ COMPLETED ]'}) {
lists { entries { media {
id
status
type
episodes
chapters
format
title { romaji english native }
nextAiringEpisode { episode timeUntilAiring }
mediaListEntry { progress status score(format: POINT_100) startedAt { year } }
startDate { year }
coverImage { extraLarge }
} } }
}
}`
})
})
).json();
if (mediaCache === '') {
if (type === Type.Anime) {
anime.set(
JSON.stringify(flattenLists(userIdResponse['data']['MediaListCollection']['lists']))
);
} else {
manga.set(
JSON.stringify(flattenLists(userIdResponse['data']['MediaListCollection']['lists']))
);
}
}
return flattenLists(userIdResponse['data']['MediaListCollection']['lists']);
};
export const publicMediaListCollection = async (userId: number, type: Type): Promise<Media[]> => {
const userIdResponse = await (
await fetch('https://graphql.anilist.co', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
query: `{ MediaListCollection(userId: ${userId}, type: ${
type === Type.Anime ? 'ANIME' : 'MANGA'
}, status_not_in: [ COMPLETED ]) {
lists { entries { media {
id
status
type
episodes
format
title { romaji english native }
nextAiringEpisode { episode timeUntilAiring }
mediaListEntry { progress status }
startDate { year }
} } }
}
}`
})
})
).json();
return flattenLists(userIdResponse['data']['MediaListCollection']['lists']);
};
export const recentMediaActivities = async (
userIdentity: UserIdentity,
media: Media
): Promise<number | null> => {
const activities = await (
await fetch('https://graphql.anilist.co', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
query: `{
Page(page: 1) {
activities(mediaId: ${media.id}, sort: ID_DESC) {
... on ListActivity { progress }
}
}
MediaList(userId: ${userIdentity.id}, mediaId: ${media.id}) { progress }
}`
})
})
).json();
// Essentially, just Automail estimation. All credit to hoh and the Automail contributors.
let guesses: number[] = [];
activities['data']['Page']['activities'].forEach((activity: { progress: string }) => {
if (activity.progress !== null) {
const progress = Number((activity.progress.match(/\d+$/) || [0])[0]);
if (progress !== 65535) {
guesses.push(progress);
}
}
});
guesses.sort((a, b) => b - a);
if (guesses.length) {
let bestGuess = guesses[0];
if (guesses.length > 2) {
if (guesses.filter((val) => val < 7000).length) {
guesses = guesses.filter((val) => val < 7000);
}
const difference = guesses[0] - guesses[1];
const inverseDifference = 1 + Math.ceil(25 / (difference + 1));
if (guesses.length >= inverseDifference) {
if (
guesses[1] === guesses[inverseDifference] ||
guesses[0] - guesses[1] > 500 ||
(guesses[0] - guesses[1] > 100 && guesses[1] >= guesses[inverseDifference] - 1)
) {
bestGuess = guesses[1];
if (
guesses.length > 15 &&
guesses[1] - guesses[2] > 50 &&
guesses[2] === guesses[guesses.length - 1]
) {
bestGuess = guesses[2];
}
}
}
}
if (activities['data']['MediaList']['progress'] !== null) {
if (activities['data']['MediaList']['progress'] > bestGuess) {
bestGuess = activities['data']['MediaList']['progress'];
}
}
return bestGuess;
}
return null;
};
|