aboutsummaryrefslogtreecommitdiff
path: root/src/lib/AniList/activity.ts
blob: df150c961150b543eb2dc95dabc0a5050370de6e (plain) (blame)
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
import type { UserIdentity } from './identity';

export interface ActivityHistoryEntry {
	date: number;
	amount: number;
}

export const fillMissingDays = (
	inputActivities: ActivityHistoryEntry[],
	startOfYear = false
): ActivityHistoryEntry[] => {
	const timezoneOffset = new Date().getTimezoneOffset() * 60 * 1000;
	const activities = inputActivities;
	const firstDate = startOfYear
		? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0)
		: new Date(activities[0].date * 1000 + timezoneOffset);
	const lastDate = new Date(activities[activities.length - 1].date * 1000 + timezoneOffset);
	const currentDate = firstDate;

	while (currentDate <= lastDate) {
		const current_unix_timestamp = currentDate.getTime();
		let found = false;

		for (let i = 0; i < activities.length; i++) {
			if (activities[i].date * 1000 + timezoneOffset === current_unix_timestamp) {
				found = true;

				break;
			}
		}

		if (!found) {
			activities.push({
				date: current_unix_timestamp / 1000,
				amount: 0
			});
		}

		currentDate.setDate(currentDate.getDate() + 1);
	}

	// activities.sort((a: { date: number }, b: { date: number }) => a.date - b.date);

	return activities;
};

export const activityHistory = async (
	userIdentity: UserIdentity
): Promise<ActivityHistoryEntry[]> => {
	return (
		await (
			await fetch('https://graphql.anilist.co', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Accept: 'application/json'
				},
				body: JSON.stringify({
					query: `{ User(id: ${userIdentity.id}) {
					stats { activityHistory { date amount } }
        } }`
				})
			})
		).json()
	)['data']['User']['stats']['activityHistory'];
};

export const lastActivityDate = async (userIdentity: UserIdentity): Promise<Date> => {
	const history = await activityHistory(userIdentity);
	const date = new Date(
		Number(history[history.length - 1]['date']) * 1000 + new Date().getTimezoneOffset()
	);

	date.setDate(date.getDate() + 1);

	return date;
};