aboutsummaryrefslogtreecommitdiff
path: root/src/lib/AniList/activity.ts
blob: 0735b2913ff354134e2b594754f2588606ceb26e (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
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
import type { AniListAuthorisation, UserIdentity } from './identity';

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

export const fillMissingDays = (
	inputActivities: ActivityHistoryEntry[],
	startOfYear = false
): ActivityHistoryEntry[] => {
	if (inputActivities.length === 0)
		return startOfYear
			? fillDateRange(
					new Date(new Date().getUTCFullYear(), 0, 1),
					new Date(new Date().getUTCFullYear() + 1, 0, 1)
			  )
			: [];

	const sortedActivities = [...inputActivities].sort((a, b) => a.date - b.date);
	const endDate = new Date(sortedActivities[sortedActivities.length - 1].date * 1000);

	endDate.setUTCDate(endDate.getUTCDate() + 1);

	return fillDateRange(
		startOfYear
			? new Date(new Date().getUTCFullYear(), 0, 1)
			: new Date(sortedActivities[0].date * 1000),
		endDate,
		sortedActivities
	);
};

const fillDateRange = (
	startDate: Date,
	endDate: Date,
	existingActivities: ActivityHistoryEntry[] = []
): ActivityHistoryEntry[] => {
	const outputActivities: ActivityHistoryEntry[] = [];

	for (let dt = new Date(startDate); dt < endDate; dt.setUTCDate(dt.getUTCDate() + 1)) {
		const dateString = dt.toDateString();

		if (
			!new Set(
				existingActivities.map((activity) => new Date(activity.date * 1000).toDateString())
			).has(dateString)
		) {
			outputActivities.push({ date: Math.floor(dt.getTime() / 1000), amount: 0 });
		} else {
			const activity = existingActivities.find(
				(activity) => new Date(activity.date * 1000).toDateString() === dateString
			);

			if (activity) outputActivities.push(activity);
		}
	}

	return outputActivities;
};

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;
};

interface ActivitiesPage {
	data: {
		Page: {
			pageInfo: {
				hasNextPage: boolean;
			};
			activities: {
				createdAt: number;
			}[];
		};
	};
}

const activitiesPage = async (
	page: number,
	anilistAuthorisation: AniListAuthorisation,
	userIdentity: UserIdentity
): Promise<ActivitiesPage> =>
	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: `{
					Page(page: ${page}) {
    				pageInfo { hasNextPage }
						activities(userId: ${userIdentity.id}, createdAt_greater: ${Math.floor(
					new Date(new Date().getFullYear(), 0, 1).getTime() / 1000
				)}, createdAt_lesser: ${Math.floor(
					new Date(new Date().getFullYear(), 6, 1).getTime() / 1000
				)}) {
							... on TextActivity    { createdAt }
							... on ListActivity    { createdAt }
							... on MessageActivity { createdAt }
						}
					}
				}`
			})
		})
	).json();

export const fullActivityHistory = async (
	anilistAuthorisation: AniListAuthorisation,
	userIdentity: UserIdentity
): Promise<ActivityHistoryEntry[]> => {
	const activities: any[] = [];
	let page = 1;
	let currentPage = await activitiesPage(page, anilistAuthorisation, userIdentity);

	for (const activity of currentPage.data.Page.activities) activities.push(activity);

	while (currentPage['data']['Page']['pageInfo']['hasNextPage']) {
		for (const activity of currentPage.data.Page.activities) activities.push(activity);

		page += 1;
		currentPage = await activitiesPage(page, anilistAuthorisation, userIdentity);
	}

	let fullLocalActivityHistory: ActivityHistoryEntry[] = [];

	for (const activity of activities) {
		const date = new Date(activity.createdAt * 1000);
		const dateString = date.toDateString();

		const activityHistoryEntry = fullLocalActivityHistory.find(
			(activityHistoryEntry) =>
				new Date(activityHistoryEntry.date * 1000).toDateString() === dateString
		);

		if (activityHistoryEntry) activityHistoryEntry.amount += 1;
		else fullLocalActivityHistory.push({ date: Math.floor(date.getTime() / 1000), amount: 1 });
	}

	fullLocalActivityHistory = fullLocalActivityHistory.filter((a) => !isNaN(a.date));

	fullLocalActivityHistory.push(...(await activityHistory(userIdentity)));

	fullLocalActivityHistory = fullLocalActivityHistory.filter(
		(activityHistoryEntry, index, self) =>
			self.findIndex(
				(a) =>
					new Date(a.date * 1000).toDateString() ===
					new Date(activityHistoryEntry.date * 1000).toDateString()
			) === index
	);

	return fullLocalActivityHistory;
};