aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Media/Anime/Airing/Subtitled/match.ts
blob: 5ffeb064ddeb345bbbf6d87c4e26bee7de7e4558 (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
import { get } from 'svelte/store';
import type { Media } from '../../../../AniList/media';
import settings from '../../../../../stores/settings';
import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
import levenshtein from 'fast-levenshtein';

export interface Time {
	title: string;
	time: string;
	day: string;
}

export const airedUnsubtitled = (anime: Media) =>
	anime.nextAiringEpisode?.airingAt &&
	anime.nextAiringEpisode?.nativeAiringAt &&
	new Date(anime.nextAiringEpisode.airingAt * 1000).getTime() > Date.now() &&
	new Date(anime.nextAiringEpisode.nativeAiringAt * 1000).getTime() - Date.now() >
		6 * 24 * 60 * 60 * 1000;

const secondsUntil = (targetTime: string, targetDay: string) => {
	const now = new Date();
	const [targetHour, targetMinute] = targetTime.split(':').map(Number);
	let dayDifference =
		['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].indexOf(
			targetDay
		) - now.getDay();

	if (dayDifference < 0) dayDifference += 7;

	const targetDate = new Date(now);

	targetDate.setDate(now.getDate() + dayDifference);
	targetDate.setHours(targetHour, targetMinute, 0, 0);

	const secondsDifference = (Number(targetDate) - Number(now)) / 1000;

	return secondsDifference > 0 ? secondsDifference : secondsDifference + 7 * 24 * 60 * 60;
};

const normalizeTitle = (title: string | null) => {
	return (title || '')
		.toLowerCase()
		.replace(/season \d+|s\d+|\W/g, '')
		.replace(/\b(\d)(st|nd|rd|th)\b/g, '$1')
		.replace(/\b(part|pt)\b/gi, '')
		.trim();
};

const findClosestMatch = (times: Time[], titles: string[]) => {
	let closestMatch: Time | null = null;
	let smallestDistance = Infinity;

	titles.forEach((animeTitle) => {
		const normalizedAnimeTitle = normalizeTitle(animeTitle);

		times.forEach((item) => {
			const normalizedItemTitle = normalizeTitle(item.title);
			const distance = levenshtein.get(normalizedAnimeTitle, normalizedItemTitle);

			if (
				distance < smallestDistance &&
				distance < Math.max(3, normalizedAnimeTitle.length * 0.4)
			) {
				smallestDistance = distance;
				closestMatch = item;
			}
		});
	});

	return closestMatch as Time | null;
};

export const findClosestMedia = (media: Media[], matchFor: string) => {
	if (!matchFor) return null;

	let bestFitMedia: Media | null = null;
	let smallestDistance = Infinity;

	media.forEach((m) => {
		[m.title.romaji, m.title.english, ...m.synonyms].filter(Boolean).forEach((title) => {
			const normalizedItemTitle = normalizeTitle(title);
			const distance = levenshtein.get(normalizeTitle(matchFor), normalizedItemTitle);

			if (distance < smallestDistance && distance < Math.max(3, normalizedItemTitle.length * 0.4)) {
				smallestDistance = distance;
				bestFitMedia = m;
			}
		});
	});

	return bestFitMedia as Media | null;
};

export const injectAiringTime = (anime: Media, subsPlease: SubsPlease | null) => {
	const airingAt = anime.nextAiringEpisode?.airingAt;
	// const nativeUntilAiring = airingAt
	// 	? Math.round((airingAt - Date.now() / 1000) * 100) / 100
	// 	: undefined;
	const nativeTime = new Date(airingAt ? airingAt * 1000 : 0);
	let untilAiring;
	let time = new Date(airingAt ? airingAt * 1000 : 0);
	let nextEpisode = anime.nextAiringEpisode?.episode || 0;

	if (
		!(
			(get(settings).displayNativeCountdown || !subsPlease)
			// || !(nativeUntilAiring !== undefined && nativeUntilAiring < 24 * 60 * 60)
		)
	) {
		const times: Time[] = [];

		for (const [key, value] of Object.entries(subsPlease.schedule)) {
			const flattenedValue = Array.isArray(value) ? value.flat() : [];

			for (const time of flattenedValue) {
				times.push({
					title: time.title,
					time: time.time,
					day: key
				});
			}
		}

		const foundTime: Time | null = findClosestMatch(times, [
			anime.title.romaji,
			anime.title.english,
			...anime.synonyms
		]);

		if (foundTime) {
			untilAiring = secondsUntil((foundTime as Time).time, (foundTime as Time).day);
			time = new Date(Date.now() + untilAiring * 1000);
		}
	}

	if (anime.mediaListEntry?.progress === (anime.nextAiringEpisode?.episode ?? 0) - 1)
		if (
			// This was an insane debugging session .... What, like eight hours? ...
			airedUnsubtitled({
				nextAiringEpisode: {
					...anime.nextAiringEpisode,
					airingAt: time.getTime() / 1000,
					nativeAiringAt: nativeTime.getTime() / 1000
				}
			} as Media)
		)
			nextEpisode -= 1;

	return {
		...anime,
		nextAiringEpisode: {
			episode: nextEpisode,
			airingAt: time.getTime() / 1000,
			nativeAiringAt: nativeTime.getTime() / 1000
		}
	} as Media;
};