aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Media/Anime/Airing/Subtitled/match.ts
blob: d6168d2c6ddbd3c0b31bf88606245dd5e6d25254 (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
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
import { get } from 'svelte/store';
import type { Media } from '../../../../Data/AniList/media';
import settings from '$stores/settings';
import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
import stringSimilarity from 'string-similarity';
import excludeMatch from '$lib/Data/Static/matchExclude.json';
import { season } from '../../season';

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

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 preprocessTitle = (title: string): string => {
  return title
    .toLowerCase()
    .replace(/\b(season|s|part|cour)\b/g, ' ')
    .replace(/[^a-z0-9\s]/gi, '')
    .trim()
    .split(/\s+/)
    .join(' ');
};

const NON_DISTINCTIVE_TOKENS = new Set([
  'a',
  'and',
  'de',
  'e',
  'for',
  'ga',
  'in',
  'na',
  'ni',
  'no',
  'o',
  'of',
  'on',
  'the',
  'to',
  'wa',
  'wo'
]);

const isMeaningfulToken = (token: string): boolean =>
  /^\d+$/.test(token) || (token.length >= 3 && !NON_DISTINCTIVE_TOKENS.has(token));

const calculateWeightedSimilarity = (title1: string, title2: string): number => {
  const tokens1 = title1.split(' ').filter(isMeaningfulToken);
  const tokens2 = title2.split(' ').filter(isMeaningfulToken);

  if (tokens1.length === 0 || tokens2.length === 0) return 0;

  const set2 = new Set(tokens2);
  let score = 0;

  tokens1.forEach((token) => {
    if (set2.has(token)) {
      score += /^\d+$/.test(token) ? 2 : 1;
    }
  });

  return score / ((Math.max(tokens1.length, tokens2.length) || 1) * 2);
};

export const findClosestMatch = (times: Time[], anime: Media): Time | null => {
  if (excludeMatch.includes(anime.id)) return null;

  const airingDay = new Date((anime.nextAiringEpisode?.airingAt || 0) * 1000).toLocaleString(
    'en-US',
    { weekday: 'long' }
  );
  const dayTimes = times.filter((time) => time.day === airingDay);

  if (dayTimes.length === 0) return null;

  const preprocessedTimes = dayTimes.map((time) => ({
    time,
    normalized: preprocessTitle(time.title)
  }));
  let bestMatch: Time | null = null;
  let bestScore = 0;
  const searchTitles = [anime.title.romaji, anime.title.english, ...anime.synonyms].filter(Boolean);

  for (const searchTitle of searchTitles) {
    if (searchTitle.includes('OVA') || searchTitle.includes('Special')) continue;

    const normalizedSearchTitle = preprocessTitle(searchTitle);

    for (const { time, normalized } of preprocessedTimes) {
      const similarityScore = calculateWeightedSimilarity(normalizedSearchTitle, normalized);

      if (similarityScore > bestScore) {
        bestScore = similarityScore;
        bestMatch = time;
      }
    }
  }

  return bestMatch;
};

const normalizeTitle = (title: string | null) =>
  (title || '')
    .toLowerCase()
    .replace(/\b(s|season|part|cour)\s*\d+/g, '')
    .replace(/[\W_]+/g, ' ')
    .trim();

const findClosestMediaCache = new Map<string, Media | null>();

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

  const cached = findClosestMediaCache.get(matchFor);

  if (cached !== undefined) return cached;

  const normalisedMatchFor = normalizeTitle(matchFor);
  const matchForWords = normalisedMatchFor.split(' ');
  let bestFitMedia: Media | null = null;
  let bestDistance = -Infinity;

  for (const m of media) {
    const titles = [m.title.romaji, m.title.english, ...m.synonyms].filter(Boolean);

    if (
      titles.some(
        (title) => title.toLowerCase().includes('special') || title.toLowerCase().includes('ova')
      )
    )
      continue;

    const normalisedTitles = titles.map(normalizeTitle);

    for (const normalisedTitle of normalisedTitles) {
      const distance = stringSimilarity.compareTwoStrings(normalisedMatchFor, normalisedTitle);

      if (distance <= bestDistance) continue;

      const wordMatch =
        matchForWords.every((word) => normalisedTitles.some((t) => t.includes(word))) ||
        normalisedTitles.some((t) => t.includes(normalisedMatchFor));

      if (wordMatch) {
        bestDistance = distance;
        bestFitMedia = m;

        if (distance === 1) break;
      }
    }

    if (bestDistance === 1) break;
  }

  findClosestMediaCache.set(matchFor, bestFitMedia);

  return bestFitMedia as Media | null;
};

export const clearClosestMediaCache = () => findClosestMediaCache.clear();

export const injectAiringTime = (anime: Media, subsPlease: SubsPlease | null) => {
  if (season() !== anime.season) return anime;

  const airingAt = anime.nextAiringEpisode?.airingAt;
  const now = new Date();
  // 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
        });
      }
    }

    if ((anime.nextAiringEpisode?.episode || 0) > 1) {
      const foundTime: Time | null = findClosestMatch(times, anime);

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

  const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000;

  if (nativeTime > time) {
    nextEpisode -= 1;
  }

  if (nativeTime.getTime() - now.getTime() > SEVEN_DAYS) {
    const beforeTime = time;

    time = nativeTime;

    time.setHours(beforeTime.getHours());
    time.setMinutes(beforeTime.getMinutes());
  }

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