@playpilot/tpi 8.40.0-beta.1 → 8.40.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,518 +1,526 @@
1
- import { cleanPhrase, findNumberOfMatchesInString, findShortestMatchBetweenPhrases, findTextNodeContaining, getIndexOfPhraseInElement, getIndexOfPhraseInBoundary, getNumberOfLeadingAndTrailingSpaces, isNodeInLink, replaceBetween, replaceStartingFrom, findSurroundingPhrases } from './text'
2
- import type { LinkInjection, LinkInjectionTypes } from './types/injection'
3
- import { getNumberOfOccurrencesInArray } from './array'
4
- import { destroyAllModals, openModalForInjectedLink } from './modal'
5
- import { clearCurrentlyHoveredInjection, destroyLinkPopover, destroyLinkPopoverOnMouseleave, isPopoverActive, openPopoverForInjectedLink } from './popover'
6
- import { clearAfterArticlePlaylinks, insertAfterArticlePlaylinks } from './afterArticle'
7
- import { clearInTextDisclaimer, insertInTextDisclaimer } from './disclaimer'
8
- import { exploreModalUrl, participantUrl, titleUrl } from './routes'
9
- import { clearInTextWidgets, insertInTextWidgets } from './inTextWidgets'
10
- import { encodeHtmlEntities } from './html'
11
- import type { ParticipantData } from './types/participant'
12
-
13
- export const keyDataAttribute = 'data-playpilot-injection-key'
14
- export const keySelector = `[${keyDataAttribute}]`
15
-
16
- /**
17
- * Replace all found injections within all given elements on the page
18
- * @returns Returns an array of injections with injections that failed to be inserted marked as `failed`.
19
- */
20
- export function injectLinksInDocument(elements: HTMLElement[], injections: LinkInjectionTypes = { aiInjections: [], manualInjections: [] }): LinkInjection[] {
21
- clearLinkInjections()
22
- removePlayPilotTitleLinks()
23
-
24
- const mergedInjections = mergeInjectionTypes(injections)
25
- if (!mergedInjections.length) return []
26
-
27
- // Find injection in text content of all elements together, ignore potential HTML elements.
28
- // This is to filter out injections that can't be injected anyway.
29
- const fullText = cleanPhrase(elements.map(element => element.innerText).join(' '))
30
-
31
- const validInjections = filterInvalidInTextInjections(mergedInjections)
32
- const foundInjections = validInjections.filter(i => fullText.includes(cleanPhrase(i.sentence)))
33
-
34
- const failedMessages: Record<string, string> = {}
35
- const aiInjectionSidsCount: Record<string, number> = {}
36
-
37
- let injectionIndex = -1 // This index is used in Option 3 below.
38
- for (const injection of sortInjections(foundInjections)) {
39
- injectionIndex++
40
-
41
- // TODO: REMOVE ME. This is a temporary hack. Popularity should be on participant_details but currently it is only on the injection.
42
- if (injection.type === 'participant') injection.participant_details!.popularity ||= injection.popularity
43
-
44
- if (!injection.manual) {
45
- const previousCount = aiInjectionSidsCount[injection.sid] || 0
46
-
47
- if (previousCount >= (window.PlayPilotLinkInjections?.config?.unique_injection_count_limit || 10)) {
48
- failedMessages[injection.key] = 'Injection was withheld because it exceeded the maximum unique count.'
49
- continue
50
- } else {
51
- aiInjectionSidsCount[injection.sid] = previousCount + 1
52
- }
53
-
54
- if (injection.type === 'participant' && !doesParticipantMeetThreshold(mergedInjections, injection.participant_details!)) {
55
- failedMessages[injection.key] = 'Participant does not meet popularity threshold.'
56
- continue
57
- }
58
- }
59
-
60
- const elementIndex = elements.findIndex(element => cleanPhrase(element.innerText).includes(cleanPhrase(injection.sentence)))
61
- const element = elements[elementIndex]
62
-
63
- if (!element) continue
64
-
65
- const nodeContainingText = findTextNodeContaining(injection.title, element, ['A'])
66
-
67
- if (!nodeContainingText?.nodeValue || isNodeInLink(nodeContainingText)) {
68
- // We check once more where the text was found, this time without ignoring links
69
- // so we can determine if the failure was due to it being in a link
70
- const linkNodeContainingText = findTextNodeContaining(injection.title, element)
71
- if (linkNodeContainingText && isNodeInLink(linkNodeContainingText)) {
72
- failedMessages[injection.key] = 'Given text is already inside of a link.'
73
- continue
74
- }
75
- }
76
-
77
- const { injectionElement, linkElement } = createLinkInjectionElement(injection)
78
-
79
- let replacementIndex = -1
80
- let hasBeenReplaced = false
81
-
82
- // !! Option 1 - Simple replacements
83
- // Check if there is only one occurance in the element, in which case the replacement is simple
84
- // It's important that we check against the phrase without cleanPhrase(), as we need to check if an
85
- // element might contain attributes that contain the phrase.
86
- const numberOfHtmlMatches = findNumberOfMatchesInString(element.innerHTML, injection.title)
87
- if (numberOfHtmlMatches === 1) replacementIndex = element.innerHTML.indexOf(injection.title)
88
-
89
- // !! Option 2 - Replace by phrase_before and phrase_after
90
- // If multiple or no occurences were found, we use the phrases before and after the injection to find
91
- // the location of the correct title. This helps with multiple occurrences of the same phrase, but also
92
- // with text that is broken up by html elements.
93
- const { phrase_before, phrase_after } = getPhrasesSurroundingInjection(element, injection)
94
-
95
- if (replacementIndex === -1 && (phrase_before || phrase_after)) {
96
- // The before and after phrase are combined to see if the sentence contains the match exactly.
97
- // This is a fairly simple comparison that will fail on special characters, html tags, or inconsistencies
98
- const fullPhrase = [phrase_before, injection.title, phrase_after].filter(Boolean).join(' ')
99
-
100
- replacementIndex = element.innerHTML.indexOf(fullPhrase)
101
-
102
- // If we reach this point the match wasn't straight forward and we need to replace whatever is between phrase_before and phrase_after fully.
103
- // We insert the html here separately from below, where it's done with replacementIndex because we need to capture all html
104
- // that may have been inside of the match.
105
- if (replacementIndex === -1) {
106
- let match = findShortestMatchBetweenPhrases(element.innerHTML, injection.title, phrase_before || '', phrase_after || '')
107
-
108
- if (match) {
109
- // This is a crude way of checking if a match contains HTML elements
110
- // If the title is directly inside of an element we discard the rest.
111
- // This happens sometimes in lists that consists of nothing but titles and may contain special characters
112
- if (match.match.includes('>') && match.match.includes('<')) {
113
- const encodedTitle = encodeHtmlEntities(injection.title)
114
- const matchInsideHTMLIndex = match.match.search(new RegExp(`>\s*${encodedTitle}\s*<`)) + 1
115
-
116
- if (matchInsideHTMLIndex > 0) {
117
- match = { match: match.match.slice(matchInsideHTMLIndex, matchInsideHTMLIndex + encodedTitle.length), index: matchInsideHTMLIndex }
118
- }
119
- }
120
-
121
- const { leadingSpaces, trailingSpaces } = getNumberOfLeadingAndTrailingSpaces(match.match)
122
-
123
- linkElement.innerHTML = match.match.trim()
124
-
125
- const startIndex = match.index + leadingSpaces
126
- const endIndex = match.index + match.match.length - trailingSpaces
127
-
128
- // Stop if the content already contains a link, which we identify soley by if the contain string contains a href attribute
129
- if (element.innerHTML.slice(startIndex, endIndex).includes('href=')) continue
130
-
131
- if (replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, startIndex, endIndex)) {
132
- replacementIndex = match.index
133
- hasBeenReplaced = true
134
- }
135
- }
136
- }
137
- }
138
-
139
- // !! Option 3 - Replace by title only, taking previous injections into account
140
- // If no occurences were found previously, we check the element from start to finish only checking for the title,
141
- // without considering phrase_before and phrase_after. Here we check the index of multiple different types of matches
142
- // and go with the highest index between them all, assuming that is always going to be the correct phrase.
143
- if (replacementIndex === -1 && nodeContainingText?.nodeValue) {
144
- // Start searching for injection from either the value, the sentence, or the occurrence. This prevents injecting into
145
- // text in an element earlier than the sentence started. A element might contain many sentences, after all.
146
- const valueIndex = element.innerHTML.indexOf(nodeContainingText.nodeValue)
147
- const sentenceIndex = element.innerHTML.indexOf(injection.sentence)
148
-
149
- // Sentences are often broken up by HTML elements. When that happens the index of the sentence can't be found in the HTML.
150
- // In that case we can attempt to search for part of the sentence instead, and hope for the best. We grab the first 20 characters
151
- // of the sentence and look for that instead. This will not work if sentence is broken up within those first characters,
152
- // if the injections is right at the start of the sentence, or the element contains multiple matches for that same slice.
153
- // But it's something to fall back on regardless.
154
- const startOfSentenceIndex = sentenceIndex === -1 ? element.innerHTML.indexOf(injection.sentence.slice(0, 20)) : -1
155
-
156
- // Similar to the start of the sentence, we look first just the first word of the sentence. This is only relevant if the start
157
- // of the sentence is broken up by HTML is less characters than is required for startOfSentenceIndex.
158
- // This only works if the first word occurs only once, as otherwise we might match on the incorrect part of the sentence.
159
- const firstWordOfSentence = injection.sentence.split(' ')[0]
160
- const firstWordOccurrences = findNumberOfMatchesInString(element.innerHTML, firstWordOfSentence)
161
- const firstWordIndex = firstWordOccurrences === 1 ? element.innerHTML.indexOf(firstWordOfSentence) : -1
162
-
163
- // Starting from occurence happens when a sentence might include multiple occurences of the same phrase.
164
- // We might still prefer the valueIndex if that is higher than this value.
165
-
166
- // A sentence might include multiple matches for the same phrase. We get the number of previous occurences in order to get the index
167
- // of the match we actually want to get.
168
- const indexOfOccurrence = getNumberOfOccurrencesInArray<LinkInjection>(foundInjections.slice(0, injectionIndex + 1), injection, ['title', 'sentence']) - 1
169
- const indexInSentence = getIndexOfPhraseInElement(nodeContainingText.nodeValue, element, indexOfOccurrence)
170
-
171
- replacementIndex = Math.max(valueIndex, startOfSentenceIndex, indexInSentence, firstWordIndex, sentenceIndex, 0)
172
- }
173
-
174
- if (replacementIndex === -1) continue
175
- if (hasBeenReplaced) continue
176
-
177
- if (!replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, replacementIndex)) {
178
- // If all else fails, we try one more time with a word boundary. If it has gotten to this point it likely means an
179
- // injection tried to match into another that match partially. For example in the sentence:
180
- // "Some Movie: The Sequel is a follow up to Some Movie", there are two matches for "Some Movie". But because the first
181
- // match contains the second, the second will also try to inject itself into the first. In this case we try and find it
182
- // again using a word boundary. This will fail in cases such as "Some Movie 2 is a follow up to Some Movie" because
183
- // the word boundary still the first one.
184
- const wordBoundaryMatchIndex = getIndexOfPhraseInBoundary(injection.title, element.innerHTML)
185
-
186
- if (wordBoundaryMatchIndex > -1) {
187
- replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, wordBoundaryMatchIndex)
188
- } else {
189
- failedMessages[injection.key] = 'Injection would have lead to broken HTML.'
190
- }
191
- }
192
- }
193
-
194
- addLinkInjectionEventListeners(foundInjections)
195
- addCSSVariablesToLinks()
196
-
197
- const afterArticleInjections = filterInvalidAfterArticleInjections(mergedInjections)
198
- if (afterArticleInjections.length) insertAfterArticlePlaylinks(elements, afterArticleInjections)
199
-
200
- // Attempt to insert in text disclaimer if at least 1 injection is found in the article.
201
- // The function itself will decide whether or not it should actually insert the component based on the config.
202
- if (document.querySelector(keySelector)) insertInTextDisclaimer(elements)
203
-
204
- insertInTextWidgets(foundInjections)
205
-
206
- return mergedInjections.filter(injection => hasValidTypeData(injection)).map((injection, index) => {
207
- const hasManualEquivalent = !injection.manual && isAvailableAsManualInjection(injection, index, mergedInjections)
208
- const duplicate = injection.duplicate ?? hasManualEquivalent
209
-
210
- if (duplicate) failedMessages[injection.key] = hasManualEquivalent ? 'Injection was manually removed.' : 'Injection was marked as duplicate.'
211
-
212
- const matchingElement = document.querySelector(`[${keyDataAttribute}="${injection.key}"]`)
213
- const failed = isValidPlaylinkType(injection) && !injection.inactive && !injection.removed && !injection.after_article && !matchingElement
214
- const anyElementContainsSentence = failed && elements.some(element => cleanPhrase(element.innerText).includes(cleanPhrase(injection.sentence)))
215
- const failedMessage =
216
- !failed ? '' :
217
- failedMessages[injection.key] ||
218
- (!anyElementContainsSentence ? 'Given sentence was not found in the article.' : 'The link failed to inject for unknown reasons.')
219
-
220
- return {
221
- ...injection,
222
- inactive: injection.inactive ?? false,
223
- duplicate,
224
- failed,
225
- failed_message: failedMessage,
226
- matchingElement,
227
- }
228
- })
229
- }
230
-
231
- function createLinkInjectionElement(injection: LinkInjection): { injectionElement: HTMLSpanElement, linkElement: HTMLAnchorElement } {
232
- // Create a wrapper in which the link will be placed. This wrapper exists as a parent for the popover
233
- // so that it is not directly inside of the link.
234
- const injectionElement = document.createElement('span')
235
- injectionElement.dataset.playpilotInjectionKey = injection.key
236
- injectionElement.dataset.playpilotInjectionType = injection.type
237
-
238
- const openInExplore = !!window.PlayPilotLinkInjections?.config?.open_tpi_links_in_explore
239
-
240
- const sid = injection.title_details?.sid || injection.participant_details?.sid
241
- const href = openInExplore ? exploreModalUrl(sid!) : (injection.type === 'title' ? titleUrl(injection.title_details!) : participantUrl(injection.participant_details!))
242
-
243
- const linkElement = document.createElement('a')
244
- linkElement.innerText = injection.title
245
- linkElement.href = href
246
- linkElement.target = openInExplore ? '' : '_blank'
247
- linkElement.rel = 'noopener nofollow noreferrer'
248
-
249
- if (injection.type === 'title') linkElement.dataset.playpilotPosterUrl = injection.title_details?.standing_poster
250
-
251
- injectionElement.insertAdjacentElement('beforeend', linkElement)
252
-
253
- return { injectionElement, linkElement }
254
- }
255
-
256
- /**
257
- * In some coses injections lead to broken HTML. The reason for this varies and is hard to figure out. In any case, we
258
- * should never serve broken HTML.
259
- * Before replacing the HTML, we apply the the replacement to a dummy element. From here we check if the length of the text has
260
- * increased. If it did, something went wrong. What exactly is hard to say, we just know something didn't go as intended and
261
- * we should not inject.
262
- *
263
- * No tests exists for this function because writing tests would require finding a scenario in which things break. If we knew
264
- * when things break we'd fix it instead.
265
- */
266
- function replaceIfSafeInjection(originalHtml: string, phrase: string, sentenceElement: HTMLElement, injectionElement: HTMLElement, replacementIndex: number, endIndex: number = -1): boolean {
267
- const getNumberOfEmptyLinksAndInjections = (element: HTMLElement): number => Array.from(element.querySelectorAll<HTMLElement>(`a, ${keySelector}`)).filter(a => !a.innerText).length
268
-
269
- const dummyElement = document.createElement('div')
270
- dummyElement.innerHTML = originalHtml
271
-
272
- const originalNumberOfEmptyLinks = getNumberOfEmptyLinksAndInjections(dummyElement)
273
- const originalText = dummyElement.innerText
274
-
275
- // If an endIndex is given we can replace using replaceBetween. This is the case when injections come from using `phrase_before` and `phrase_after`.
276
- if (endIndex > 0) {
277
- dummyElement.innerHTML = replaceBetween(originalHtml, injectionElement.outerHTML, replacementIndex, endIndex)
278
- } else {
279
- dummyElement.innerHTML = replaceStartingFrom(originalHtml, phrase, injectionElement.outerHTML, replacementIndex)
280
- }
281
-
282
- // If the text has changed at all, something probably went wrong as the new text is supposed to be the same as the old.
283
- if (Math.abs(dummyElement.innerText.length - originalText.length) > 1) return false
284
- // One of our links pushed out an existing link on the page. When this happens the original link is emptied (because a link inserted into a link, and that is invalid)
285
- // Not sure of the exact circumstances this might happen in, but it has happened on DigitalSpy.
286
- // If the parent key contains no text something broke. This can happen when a link tries to injection partially into another link, leaving the closing link tag dangling.
287
- if (originalNumberOfEmptyLinks != getNumberOfEmptyLinksAndInjections(dummyElement)) return false
288
-
289
- sentenceElement.innerHTML = dummyElement.innerHTML
290
-
291
- return true
292
- }
293
-
294
- /**
295
- * phrase_before and phrase_after are set for manual injections to better get their placement within a sentence.
296
- * This helps when an injection contains multiple injections of the same word and it also helps when an injection
297
- * is broken up by html elements. For instance, DigitalSpy sometimes uses multiple styling tags on the same phrase.
298
- * Something like `<strong>phr</strong><strong>ase</strong.
299
- *
300
- * Secondary to manual injections we can also get the phrase_before and phrase_after for ai injections.
301
- * This only works if the injection occurs only once. In this case it is only used when the phrase is broken up
302
- * by html elements, like before.
303
- */
304
- function getPhrasesSurroundingInjection(element: HTMLElement, injection: LinkInjection): { phrase_before: string | null | undefined, phrase_after: string | null | undefined } {
305
- const { phrase_before, phrase_after } = injection
306
-
307
- if (phrase_before || phrase_after) return { phrase_before, phrase_after }
308
-
309
- // Get the number of occurrences of the same phrase in the element. We can only use the before and after
310
- // phrases if there is only 1 occurrence, as we can't guarentee we injection into the expected phrase otherwise.
311
- const numberOfTextMatches = findNumberOfMatchesInString(element.innerText, injection.title)
312
-
313
- if (numberOfTextMatches !== 1) return { phrase_before: null, phrase_after: null }
314
-
315
- const startIndex = element.innerText.indexOf(injection.title)
316
- const surroundingPhrases = findSurroundingPhrases(element, startIndex, startIndex + injection.title.length)
317
-
318
- return { phrase_before: surroundingPhrases.before, phrase_after: surroundingPhrases.after }
319
- }
320
-
321
- /**
322
- * Add all used CSS variables to a data attribute. This data attribute is then used for selectors that for each
323
- * individual CSS variable. This is done this way so that CSS variables are only set when they are used.
324
- * Using the variables straight up or with a fallback value would not allow them to use their default page styling.
325
- */
326
- function addCSSVariablesToLinks(): void {
327
- const createdLinkElements = Array.from(document.querySelectorAll(`${keySelector} a`)) as HTMLElement[]
328
-
329
- const variables = [
330
- '--playpilot-injection-text-color',
331
- '--playpilot-injection-text-color-hover',
332
- '--playpilot-injection-font-weight',
333
- '--playpilot-injection-font-weight-headings',
334
- '--playpilot-injection-text-decoration',
335
- '--playpilot-injection-text-decoration-hover',
336
- '--playpilot-injection-background-color',
337
- '--playpilot-injection-background-color-hover',
338
- ]
339
-
340
- for (const element of createdLinkElements) {
341
- const style = getComputedStyle(element)
342
-
343
- for (const value of variables) {
344
- if (!style.getPropertyValue(value)) continue
345
-
346
- element.dataset.usedCssVariables = `${element.dataset.usedCssVariables || ''} ${value}`
347
- }
348
- }
349
- }
350
-
351
- function addLinkInjectionEventListeners(injections: LinkInjection[]): void {
352
- window.addEventListener('mousemove', destroyLinkPopoverOnMouseleave)
353
-
354
- window.addEventListener('click', (event) => {
355
- if (window.PlayPilotLinkInjections?.config?.open_tpi_links_in_explore) return
356
-
357
- openModalForInjectedLink(event, injections)
358
- })
359
-
360
- const createdInjectionElements = document.querySelectorAll<HTMLElement>(keySelector)
361
-
362
- // Open and close popover on mouseenter/mouseleave
363
- createdInjectionElements.forEach((injectionElement) => {
364
- const key = injectionElement.dataset.playpilotInjectionKey
365
- const injection = injections.find(injection => key === injection.key)
366
-
367
- if (!injection) return
368
-
369
- injectionElement.addEventListener('mouseenter', (event) => {
370
- if (!isPopoverActive()) openPopoverForInjectedLink(event, injection)
371
- })
372
-
373
- injectionElement.addEventListener('mouseleave', clearCurrentlyHoveredInjection)
374
- })
375
- }
376
-
377
- export function clearLinkInjections(): void {
378
- const elements = document.querySelectorAll(keySelector)
379
-
380
- elements.forEach((element) => clearLinkInjection(element.getAttribute(keyDataAttribute) || ''))
381
-
382
- clearAfterArticlePlaylinks()
383
- clearInTextDisclaimer()
384
- clearInTextWidgets()
385
-
386
- if (!elements.length) return
387
-
388
- destroyAllModals(false)
389
- destroyLinkPopover(false)
390
- }
391
-
392
- export function clearLinkInjection(key: string): void {
393
- const element: HTMLAnchorElement | null = document.querySelector(`[${keyDataAttribute}="${key}"]`)
394
- if (!element) return
395
-
396
- const playpilotElements = element.querySelectorAll('[data-playpilot-element]')
397
- playpilotElements.forEach(element => element.remove())
398
-
399
- const linkContent = element.querySelector('a')?.innerHTML
400
- element.outerHTML = linkContent || ''
401
- }
402
-
403
- /**
404
- * DigitalSpy tends to copy paste existing links via their CMS. They copy over injected links into new articles.
405
- * Injections won't run on those links because they already are links.
406
- * As a simple fix, we clear all title links to PlayPilot pages before injecting.
407
- */
408
- export function removePlayPilotTitleLinks(): void {
409
- const playPilotLinks = document.querySelectorAll<HTMLAnchorElement>('a[href*="playpilot.com"]')
410
-
411
- playPilotLinks.forEach(link => {
412
- if (link.closest(keySelector)) return
413
- if (!(/\/movie|show\//).test(link.href)) return
414
-
415
- link.outerHTML = link.innerHTML
416
- })
417
- }
418
-
419
- export function mergeInjectionTypes({ aiInjections, manualInjections }: LinkInjectionTypes): LinkInjection[] {
420
- return [...manualInjections.map(i => ({ ...i, manual: true })), ...aiInjections]
421
- }
422
-
423
- export function separateLinkInjectionTypes(injections: LinkInjection[]): LinkInjectionTypes {
424
- return {
425
- aiInjections: injections.filter(i => !i.manual),
426
- manualInjections: injections.filter(i => i.manual),
427
- }
428
- }
429
-
430
- export function isValidInjection(injection: LinkInjection): boolean {
431
- return !injection.inactive && !injection.removed && !injection.duplicate && hasValidTypeData(injection) && isValidPlaylinkType(injection)
432
- }
433
-
434
- /**
435
- * An injection can be of various playlink types, when all are false equivalent, the link is not valid.
436
- * It should be treated similar to an inactive playlink in this case.
437
- */
438
- export function isValidPlaylinkType(injection: LinkInjection): boolean {
439
- if (injection.in_text || injection.in_text === undefined) return true
440
- return !!injection.after_article
441
- }
442
-
443
- export function filterInvalidInTextInjections(injections: LinkInjection[]): LinkInjection[] {
444
- return filterRemovedAndInactiveInjections(injections).filter(i => i.in_text !== false && isValidInjection(i))
445
- }
446
-
447
- export function filterInvalidAfterArticleInjections(injections: LinkInjection[]): LinkInjection[] {
448
- return filterRemovedAndInactiveInjections(injections).filter(i => i.after_article === true && isValidInjection(i))
449
- }
450
-
451
- /**
452
- * Filter injections that were marked as removed or inactive or have an equivalent removed or inactive manual injections, soley based on the same sentence and title.
453
- */
454
- export function filterRemovedAndInactiveInjections(injections: LinkInjection[]): LinkInjection[] {
455
- return injections.filter(injection => {
456
- if (injection.removed || injection.inactive) return false
457
- if (injection.manual && (!injection.removed && !injection.inactive)) return true
458
-
459
- return !injections.some(i => i.manual && (i.removed || i.inactive) && isEquivalentInjection(i, injection))
460
- })
461
- }
462
-
463
- /**
464
- * Injections are sorted first by their sentence and second by their title length. The first sorting, sentence, is so that injections remain
465
- * roughly grouped. The second sorting is to prevent shorter titles from merging into longer ones. For instance;
466
- * "Shrek 2 is the sequel to Shrek". If "Shrek" appears as an injection before Shrek 2, it will incorrect inject into "Shrek 2".
467
- * By placing the longer titles first, we prevent that.
468
- */
469
- export function sortInjections(injections: LinkInjection[]): LinkInjection[] {
470
- return injections.slice().sort((a, b) => {
471
- if (a.sentence < b.sentence) return -1
472
- if (a.sentence > b.sentence) return 1
473
-
474
- const difference = b.title.length - a.title.length
475
- if (difference !== 0) return difference
476
-
477
- return 0
478
- })
479
- }
480
-
481
- export function isAvailableAsManualInjection(injection: LinkInjection, injectionIndex: number, injections: LinkInjection[]): boolean {
482
- return injections.some((i, index) => {
483
- return injectionIndex !== index && i.manual && isEquivalentInjection(i, injection)
484
- })
485
- }
486
-
487
- export function isEquivalentInjection(injection1: LinkInjection, injection2: LinkInjection): boolean {
488
- return injection1.title === injection2.title && cleanPhrase(injection1.sentence) === cleanPhrase(injection2.sentence)
489
- }
490
-
491
- export function hasValidTypeData(injection: LinkInjection): boolean {
492
- if (injection.type === 'title' && !!injection.title_details) return true
493
- if (injection.type === 'participant' && !!injection.participant_details) return true
494
-
495
- return false
496
- }
497
-
498
- export function getPlayPilotWrapperElement(): Element {
499
- return document.querySelector('[data-playpilot-link-injections]') || document.body
500
- }
501
-
502
- export function doesParticipantMeetThreshold(injections: LinkInjection[], participant: ParticipantData): boolean {
503
- if (participant.popularity === null || participant.popularity === undefined) return true
504
-
505
- const useArticleAverage = window.PlayPilotLinkInjections?.config?.participant_injection_popularity_threshold_use_article_average ?? true
506
- const defaultThreshold = 0
507
- const configThreshold = window.PlayPilotLinkInjections?.config?.participant_injection_popularity_threshold
508
- const threshold = configThreshold ?? defaultThreshold
509
-
510
- if (threshold === 0) return true
511
- if (!useArticleAverage) return participant.popularity >= threshold
512
-
513
- const averagePopularity = injections
514
- .filter(i => i.type === 'participant')
515
- .reduce((total, { participant_details }, _, { length }) => total + (participant_details!.popularity || 0) / length, 0)
516
-
517
- return participant.popularity >= averagePopularity * (threshold / 100)
518
- }
1
+ import { cleanPhrase, findNumberOfMatchesInString, findShortestMatchBetweenPhrases, findTextNodeContaining, getIndexOfPhraseInElement, getIndexOfPhraseInBoundary, getNumberOfLeadingAndTrailingSpaces, isNodeInLink, replaceBetween, replaceStartingFrom, findSurroundingPhrases } from './text'
2
+ import type { LinkInjection, LinkInjectionTypes } from './types/injection'
3
+ import { getNumberOfOccurrencesInArray } from './array'
4
+ import { destroyAllModals, openModalForInjectedLink } from './modal'
5
+ import { clearCurrentlyHoveredInjection, destroyLinkPopover, destroyLinkPopoverOnMouseleave, isPopoverActive, openPopoverForInjectedLink } from './popover'
6
+ import { clearAfterArticlePlaylinks, insertAfterArticlePlaylinks } from './afterArticle'
7
+ import { clearInTextDisclaimer, insertInTextDisclaimer } from './disclaimer'
8
+ import { exploreModalUrl, participantUrl, titleUrl } from './routes'
9
+ import { clearInTextWidgets, insertInTextWidgets } from './inTextWidgets'
10
+ import { encodeHtmlEntities } from './html'
11
+ import type { ParticipantData } from './types/participant'
12
+
13
+ export const keyDataAttribute = 'data-playpilot-injection-key'
14
+ export const keySelector = `[${keyDataAttribute}]`
15
+
16
+ /**
17
+ * Replace all found injections within all given elements on the page
18
+ * @returns Returns an array of injections with injections that failed to be inserted marked as `failed`.
19
+ */
20
+ export function injectLinksInDocument(elements: HTMLElement[], injections: LinkInjectionTypes = { aiInjections: [], manualInjections: [] }): LinkInjection[] {
21
+ clearLinkInjections()
22
+ removePlayPilotTitleLinks()
23
+
24
+ const mergedInjections = mergeInjectionTypes(injections)
25
+ if (!mergedInjections.length) return []
26
+
27
+ // Find injection in text content of all elements together, ignore potential HTML elements.
28
+ // This is to filter out injections that can't be injected anyway.
29
+ const fullText = cleanPhrase(elements.map(element => element.innerText).join(' '))
30
+
31
+ const validInjections = filterInvalidInTextInjections(mergedInjections)
32
+ const foundInjections = validInjections.filter(i => fullText.includes(cleanPhrase(i.sentence)))
33
+
34
+ const failedMessages: Record<string, string> = {}
35
+ const aiInjectionSidsCount: Record<string, number> = {}
36
+ let aiParticipantInjectionsCount = 0
37
+
38
+ let injectionIndex = -1 // This index is used in Option 3 below.
39
+ for (const injection of sortInjections(foundInjections)) {
40
+ injectionIndex++
41
+
42
+ if (!injection.manual) {
43
+ const previousCount = aiInjectionSidsCount[injection.sid] || 0
44
+
45
+ const exceedsUniqueCount =
46
+ window.PlayPilotLinkInjections?.config?.unique_injection_count_limit &&
47
+ previousCount >= window.PlayPilotLinkInjections?.config?.unique_injection_count_limit
48
+
49
+ const exceedsTotalParticipantsCount =
50
+ injection.type === 'participant' &&
51
+ window.PlayPilotLinkInjections?.config?.total_participant_injection_count_limit &&
52
+ aiParticipantInjectionsCount >= window.PlayPilotLinkInjections?.config?.total_participant_injection_count_limit
53
+
54
+ if (exceedsUniqueCount || exceedsTotalParticipantsCount) {
55
+ failedMessages[injection.key] = 'Injection was withheld because it exceeded the maximum unique count.'
56
+ continue
57
+ } else {
58
+ aiInjectionSidsCount[injection.sid] = previousCount + 1
59
+ aiParticipantInjectionsCount++
60
+ }
61
+
62
+ if (injection.type === 'participant' && !doesParticipantMeetThreshold(mergedInjections, injection.participant_details!)) {
63
+ failedMessages[injection.key] = 'Participant does not meet popularity threshold.'
64
+ continue
65
+ }
66
+ }
67
+
68
+ const elementIndex = elements.findIndex(element => cleanPhrase(element.innerText).includes(cleanPhrase(injection.sentence)))
69
+ const element = elements[elementIndex]
70
+
71
+ if (!element) continue
72
+
73
+ const nodeContainingText = findTextNodeContaining(injection.title, element, ['A'])
74
+
75
+ if (!nodeContainingText?.nodeValue || isNodeInLink(nodeContainingText)) {
76
+ // We check once more where the text was found, this time without ignoring links
77
+ // so we can determine if the failure was due to it being in a link
78
+ const linkNodeContainingText = findTextNodeContaining(injection.title, element)
79
+ if (linkNodeContainingText && isNodeInLink(linkNodeContainingText)) {
80
+ failedMessages[injection.key] = 'Given text is already inside of a link.'
81
+ continue
82
+ }
83
+ }
84
+
85
+ const { injectionElement, linkElement } = createLinkInjectionElement(injection)
86
+
87
+ let replacementIndex = -1
88
+ let hasBeenReplaced = false
89
+
90
+ // !! Option 1 - Simple replacements
91
+ // Check if there is only one occurance in the element, in which case the replacement is simple
92
+ // It's important that we check against the phrase without cleanPhrase(), as we need to check if an
93
+ // element might contain attributes that contain the phrase.
94
+ const numberOfHtmlMatches = findNumberOfMatchesInString(element.innerHTML, injection.title)
95
+ if (numberOfHtmlMatches === 1) replacementIndex = element.innerHTML.indexOf(injection.title)
96
+
97
+ // !! Option 2 - Replace by phrase_before and phrase_after
98
+ // If multiple or no occurences were found, we use the phrases before and after the injection to find
99
+ // the location of the correct title. This helps with multiple occurrences of the same phrase, but also
100
+ // with text that is broken up by html elements.
101
+ const { phrase_before, phrase_after } = getPhrasesSurroundingInjection(element, injection)
102
+
103
+ if (replacementIndex === -1 && (phrase_before || phrase_after)) {
104
+ // The before and after phrase are combined to see if the sentence contains the match exactly.
105
+ // This is a fairly simple comparison that will fail on special characters, html tags, or inconsistencies
106
+ const fullPhrase = [phrase_before, injection.title, phrase_after].filter(Boolean).join(' ')
107
+
108
+ replacementIndex = element.innerHTML.indexOf(fullPhrase)
109
+
110
+ // If we reach this point the match wasn't straight forward and we need to replace whatever is between phrase_before and phrase_after fully.
111
+ // We insert the html here separately from below, where it's done with replacementIndex because we need to capture all html
112
+ // that may have been inside of the match.
113
+ if (replacementIndex === -1) {
114
+ let match = findShortestMatchBetweenPhrases(element.innerHTML, injection.title, phrase_before || '', phrase_after || '')
115
+
116
+ if (match) {
117
+ // This is a crude way of checking if a match contains HTML elements
118
+ // If the title is directly inside of an element we discard the rest.
119
+ // This happens sometimes in lists that consists of nothing but titles and may contain special characters
120
+ if (match.match.includes('>') && match.match.includes('<')) {
121
+ const encodedTitle = encodeHtmlEntities(injection.title)
122
+ const matchInsideHTMLIndex = match.match.search(new RegExp(`>\s*${encodedTitle}\s*<`)) + 1
123
+
124
+ if (matchInsideHTMLIndex > 0) {
125
+ match = { match: match.match.slice(matchInsideHTMLIndex, matchInsideHTMLIndex + encodedTitle.length), index: matchInsideHTMLIndex }
126
+ }
127
+ }
128
+
129
+ const { leadingSpaces, trailingSpaces } = getNumberOfLeadingAndTrailingSpaces(match.match)
130
+
131
+ linkElement.innerHTML = match.match.trim()
132
+
133
+ const startIndex = match.index + leadingSpaces
134
+ const endIndex = match.index + match.match.length - trailingSpaces
135
+
136
+ // Stop if the content already contains a link, which we identify soley by if the contain string contains a href attribute
137
+ if (element.innerHTML.slice(startIndex, endIndex).includes('href=')) continue
138
+
139
+ if (replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, startIndex, endIndex)) {
140
+ replacementIndex = match.index
141
+ hasBeenReplaced = true
142
+ }
143
+ }
144
+ }
145
+ }
146
+
147
+ // !! Option 3 - Replace by title only, taking previous injections into account
148
+ // If no occurences were found previously, we check the element from start to finish only checking for the title,
149
+ // without considering phrase_before and phrase_after. Here we check the index of multiple different types of matches
150
+ // and go with the highest index between them all, assuming that is always going to be the correct phrase.
151
+ if (replacementIndex === -1 && nodeContainingText?.nodeValue) {
152
+ // Start searching for injection from either the value, the sentence, or the occurrence. This prevents injecting into
153
+ // text in an element earlier than the sentence started. A element might contain many sentences, after all.
154
+ const valueIndex = element.innerHTML.indexOf(nodeContainingText.nodeValue)
155
+ const sentenceIndex = element.innerHTML.indexOf(injection.sentence)
156
+
157
+ // Sentences are often broken up by HTML elements. When that happens the index of the sentence can't be found in the HTML.
158
+ // In that case we can attempt to search for part of the sentence instead, and hope for the best. We grab the first 20 characters
159
+ // of the sentence and look for that instead. This will not work if sentence is broken up within those first characters,
160
+ // if the injections is right at the start of the sentence, or the element contains multiple matches for that same slice.
161
+ // But it's something to fall back on regardless.
162
+ const startOfSentenceIndex = sentenceIndex === -1 ? element.innerHTML.indexOf(injection.sentence.slice(0, 20)) : -1
163
+
164
+ // Similar to the start of the sentence, we look first just the first word of the sentence. This is only relevant if the start
165
+ // of the sentence is broken up by HTML is less characters than is required for startOfSentenceIndex.
166
+ // This only works if the first word occurs only once, as otherwise we might match on the incorrect part of the sentence.
167
+ const firstWordOfSentence = injection.sentence.split(' ')[0]
168
+ const firstWordOccurrences = findNumberOfMatchesInString(element.innerHTML, firstWordOfSentence)
169
+ const firstWordIndex = firstWordOccurrences === 1 ? element.innerHTML.indexOf(firstWordOfSentence) : -1
170
+
171
+ // Starting from occurence happens when a sentence might include multiple occurences of the same phrase.
172
+ // We might still prefer the valueIndex if that is higher than this value.
173
+
174
+ // A sentence might include multiple matches for the same phrase. We get the number of previous occurences in order to get the index
175
+ // of the match we actually want to get.
176
+ const indexOfOccurrence = getNumberOfOccurrencesInArray<LinkInjection>(foundInjections.slice(0, injectionIndex + 1), injection, ['title', 'sentence']) - 1
177
+ const indexInSentence = getIndexOfPhraseInElement(nodeContainingText.nodeValue, element, indexOfOccurrence)
178
+
179
+ replacementIndex = Math.max(valueIndex, startOfSentenceIndex, indexInSentence, firstWordIndex, sentenceIndex, 0)
180
+ }
181
+
182
+ if (replacementIndex === -1) continue
183
+ if (hasBeenReplaced) continue
184
+
185
+ if (!replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, replacementIndex)) {
186
+ // If all else fails, we try one more time with a word boundary. If it has gotten to this point it likely means an
187
+ // injection tried to match into another that match partially. For example in the sentence:
188
+ // "Some Movie: The Sequel is a follow up to Some Movie", there are two matches for "Some Movie". But because the first
189
+ // match contains the second, the second will also try to inject itself into the first. In this case we try and find it
190
+ // again using a word boundary. This will fail in cases such as "Some Movie 2 is a follow up to Some Movie" because
191
+ // the word boundary still the first one.
192
+ const wordBoundaryMatchIndex = getIndexOfPhraseInBoundary(injection.title, element.innerHTML)
193
+
194
+ if (wordBoundaryMatchIndex > -1) {
195
+ replaceIfSafeInjection(element.innerHTML, injection.title, element, injectionElement, wordBoundaryMatchIndex)
196
+ } else {
197
+ failedMessages[injection.key] = 'Injection would have lead to broken HTML.'
198
+ }
199
+ }
200
+ }
201
+
202
+ addLinkInjectionEventListeners(foundInjections)
203
+ addCSSVariablesToLinks()
204
+
205
+ const afterArticleInjections = filterInvalidAfterArticleInjections(mergedInjections)
206
+ if (afterArticleInjections.length) insertAfterArticlePlaylinks(elements, afterArticleInjections)
207
+
208
+ // Attempt to insert in text disclaimer if at least 1 injection is found in the article.
209
+ // The function itself will decide whether or not it should actually insert the component based on the config.
210
+ if (document.querySelector(keySelector)) insertInTextDisclaimer(elements)
211
+
212
+ insertInTextWidgets(foundInjections)
213
+
214
+ return mergedInjections.filter(injection => hasValidTypeData(injection)).map((injection, index) => {
215
+ const hasManualEquivalent = !injection.manual && isAvailableAsManualInjection(injection, index, mergedInjections)
216
+ const duplicate = injection.duplicate ?? hasManualEquivalent
217
+
218
+ if (duplicate) failedMessages[injection.key] = hasManualEquivalent ? 'Injection was manually removed.' : 'Injection was marked as duplicate.'
219
+
220
+ const matchingElement = document.querySelector(`[${keyDataAttribute}="${injection.key}"]`)
221
+ const failed = isValidPlaylinkType(injection) && !injection.inactive && !injection.removed && !injection.after_article && !matchingElement
222
+ const anyElementContainsSentence = failed && elements.some(element => cleanPhrase(element.innerText).includes(cleanPhrase(injection.sentence)))
223
+ const failedMessage =
224
+ !failed ? '' :
225
+ failedMessages[injection.key] ||
226
+ (!anyElementContainsSentence ? 'Given sentence was not found in the article.' : 'The link failed to inject for unknown reasons.')
227
+
228
+ return {
229
+ ...injection,
230
+ inactive: injection.inactive ?? false,
231
+ duplicate,
232
+ failed,
233
+ failed_message: failedMessage,
234
+ matchingElement,
235
+ }
236
+ })
237
+ }
238
+
239
+ function createLinkInjectionElement(injection: LinkInjection): { injectionElement: HTMLSpanElement, linkElement: HTMLAnchorElement } {
240
+ // Create a wrapper in which the link will be placed. This wrapper exists as a parent for the popover
241
+ // so that it is not directly inside of the link.
242
+ const injectionElement = document.createElement('span')
243
+ injectionElement.dataset.playpilotInjectionKey = injection.key
244
+ injectionElement.dataset.playpilotInjectionType = injection.type
245
+
246
+ const openInExplore = !!window.PlayPilotLinkInjections?.config?.open_tpi_links_in_explore
247
+
248
+ const sid = injection.title_details?.sid || injection.participant_details?.sid
249
+ const href = openInExplore ? exploreModalUrl(sid!) : (injection.type === 'title' ? titleUrl(injection.title_details!) : participantUrl(injection.participant_details!))
250
+
251
+ const linkElement = document.createElement('a')
252
+ linkElement.innerText = injection.title
253
+ linkElement.href = href
254
+ linkElement.target = openInExplore ? '' : '_blank'
255
+ linkElement.rel = 'noopener nofollow noreferrer'
256
+
257
+ if (injection.type === 'title') linkElement.dataset.playpilotPosterUrl = injection.title_details?.standing_poster
258
+
259
+ injectionElement.insertAdjacentElement('beforeend', linkElement)
260
+
261
+ return { injectionElement, linkElement }
262
+ }
263
+
264
+ /**
265
+ * In some coses injections lead to broken HTML. The reason for this varies and is hard to figure out. In any case, we
266
+ * should never serve broken HTML.
267
+ * Before replacing the HTML, we apply the the replacement to a dummy element. From here we check if the length of the text has
268
+ * increased. If it did, something went wrong. What exactly is hard to say, we just know something didn't go as intended and
269
+ * we should not inject.
270
+ *
271
+ * No tests exists for this function because writing tests would require finding a scenario in which things break. If we knew
272
+ * when things break we'd fix it instead.
273
+ */
274
+ function replaceIfSafeInjection(originalHtml: string, phrase: string, sentenceElement: HTMLElement, injectionElement: HTMLElement, replacementIndex: number, endIndex: number = -1): boolean {
275
+ const getNumberOfEmptyLinksAndInjections = (element: HTMLElement): number => Array.from(element.querySelectorAll<HTMLElement>(`a, ${keySelector}`)).filter(a => !a.innerText).length
276
+
277
+ const dummyElement = document.createElement('div')
278
+ dummyElement.innerHTML = originalHtml
279
+
280
+ const originalNumberOfEmptyLinks = getNumberOfEmptyLinksAndInjections(dummyElement)
281
+ const originalText = dummyElement.innerText
282
+
283
+ // If an endIndex is given we can replace using replaceBetween. This is the case when injections come from using `phrase_before` and `phrase_after`.
284
+ if (endIndex > 0) {
285
+ dummyElement.innerHTML = replaceBetween(originalHtml, injectionElement.outerHTML, replacementIndex, endIndex)
286
+ } else {
287
+ dummyElement.innerHTML = replaceStartingFrom(originalHtml, phrase, injectionElement.outerHTML, replacementIndex)
288
+ }
289
+
290
+ // If the text has changed at all, something probably went wrong as the new text is supposed to be the same as the old.
291
+ if (Math.abs(dummyElement.innerText.length - originalText.length) > 1) return false
292
+ // One of our links pushed out an existing link on the page. When this happens the original link is emptied (because a link inserted into a link, and that is invalid)
293
+ // Not sure of the exact circumstances this might happen in, but it has happened on DigitalSpy.
294
+ // If the parent key contains no text something broke. This can happen when a link tries to injection partially into another link, leaving the closing link tag dangling.
295
+ if (originalNumberOfEmptyLinks != getNumberOfEmptyLinksAndInjections(dummyElement)) return false
296
+
297
+ sentenceElement.innerHTML = dummyElement.innerHTML
298
+
299
+ return true
300
+ }
301
+
302
+ /**
303
+ * phrase_before and phrase_after are set for manual injections to better get their placement within a sentence.
304
+ * This helps when an injection contains multiple injections of the same word and it also helps when an injection
305
+ * is broken up by html elements. For instance, DigitalSpy sometimes uses multiple styling tags on the same phrase.
306
+ * Something like `<strong>phr</strong><strong>ase</strong.
307
+ *
308
+ * Secondary to manual injections we can also get the phrase_before and phrase_after for ai injections.
309
+ * This only works if the injection occurs only once. In this case it is only used when the phrase is broken up
310
+ * by html elements, like before.
311
+ */
312
+ function getPhrasesSurroundingInjection(element: HTMLElement, injection: LinkInjection): { phrase_before: string | null | undefined, phrase_after: string | null | undefined } {
313
+ const { phrase_before, phrase_after } = injection
314
+
315
+ if (phrase_before || phrase_after) return { phrase_before, phrase_after }
316
+
317
+ // Get the number of occurrences of the same phrase in the element. We can only use the before and after
318
+ // phrases if there is only 1 occurrence, as we can't guarentee we injection into the expected phrase otherwise.
319
+ const numberOfTextMatches = findNumberOfMatchesInString(element.innerText, injection.title)
320
+
321
+ if (numberOfTextMatches !== 1) return { phrase_before: null, phrase_after: null }
322
+
323
+ const startIndex = element.innerText.indexOf(injection.title)
324
+ const surroundingPhrases = findSurroundingPhrases(element, startIndex, startIndex + injection.title.length)
325
+
326
+ return { phrase_before: surroundingPhrases.before, phrase_after: surroundingPhrases.after }
327
+ }
328
+
329
+ /**
330
+ * Add all used CSS variables to a data attribute. This data attribute is then used for selectors that for each
331
+ * individual CSS variable. This is done this way so that CSS variables are only set when they are used.
332
+ * Using the variables straight up or with a fallback value would not allow them to use their default page styling.
333
+ */
334
+ function addCSSVariablesToLinks(): void {
335
+ const createdLinkElements = Array.from(document.querySelectorAll(`${keySelector} a`)) as HTMLElement[]
336
+
337
+ const variables = [
338
+ '--playpilot-injection-text-color',
339
+ '--playpilot-injection-text-color-hover',
340
+ '--playpilot-injection-font-weight',
341
+ '--playpilot-injection-font-weight-headings',
342
+ '--playpilot-injection-text-decoration',
343
+ '--playpilot-injection-text-decoration-hover',
344
+ '--playpilot-injection-background-color',
345
+ '--playpilot-injection-background-color-hover',
346
+ ]
347
+
348
+ for (const element of createdLinkElements) {
349
+ const style = getComputedStyle(element)
350
+
351
+ for (const value of variables) {
352
+ if (!style.getPropertyValue(value)) continue
353
+
354
+ element.dataset.usedCssVariables = `${element.dataset.usedCssVariables || ''} ${value}`
355
+ }
356
+ }
357
+ }
358
+
359
+ function addLinkInjectionEventListeners(injections: LinkInjection[]): void {
360
+ window.addEventListener('mousemove', destroyLinkPopoverOnMouseleave)
361
+
362
+ window.addEventListener('click', (event) => {
363
+ if (window.PlayPilotLinkInjections?.config?.open_tpi_links_in_explore) return
364
+
365
+ openModalForInjectedLink(event, injections)
366
+ })
367
+
368
+ const createdInjectionElements = document.querySelectorAll<HTMLElement>(keySelector)
369
+
370
+ // Open and close popover on mouseenter/mouseleave
371
+ createdInjectionElements.forEach((injectionElement) => {
372
+ const key = injectionElement.dataset.playpilotInjectionKey
373
+ const injection = injections.find(injection => key === injection.key)
374
+
375
+ if (!injection) return
376
+
377
+ injectionElement.addEventListener('mouseenter', (event) => {
378
+ if (!isPopoverActive()) openPopoverForInjectedLink(event, injection)
379
+ })
380
+
381
+ injectionElement.addEventListener('mouseleave', clearCurrentlyHoveredInjection)
382
+ })
383
+ }
384
+
385
+ export function clearLinkInjections(): void {
386
+ const elements = document.querySelectorAll(keySelector)
387
+
388
+ elements.forEach((element) => clearLinkInjection(element.getAttribute(keyDataAttribute) || ''))
389
+
390
+ clearAfterArticlePlaylinks()
391
+ clearInTextDisclaimer()
392
+ clearInTextWidgets()
393
+
394
+ if (!elements.length) return
395
+
396
+ destroyAllModals(false)
397
+ destroyLinkPopover(false)
398
+ }
399
+
400
+ export function clearLinkInjection(key: string): void {
401
+ const element: HTMLAnchorElement | null = document.querySelector(`[${keyDataAttribute}="${key}"]`)
402
+ if (!element) return
403
+
404
+ const playpilotElements = element.querySelectorAll('[data-playpilot-element]')
405
+ playpilotElements.forEach(element => element.remove())
406
+
407
+ const linkContent = element.querySelector('a')?.innerHTML
408
+ element.outerHTML = linkContent || ''
409
+ }
410
+
411
+ /**
412
+ * DigitalSpy tends to copy paste existing links via their CMS. They copy over injected links into new articles.
413
+ * Injections won't run on those links because they already are links.
414
+ * As a simple fix, we clear all title links to PlayPilot pages before injecting.
415
+ */
416
+ export function removePlayPilotTitleLinks(): void {
417
+ const playPilotLinks = document.querySelectorAll<HTMLAnchorElement>('a[href*="playpilot.com"]')
418
+
419
+ playPilotLinks.forEach(link => {
420
+ if (link.closest(keySelector)) return
421
+ if (!(/\/movie|show\//).test(link.href)) return
422
+
423
+ link.outerHTML = link.innerHTML
424
+ })
425
+ }
426
+
427
+ export function mergeInjectionTypes({ aiInjections, manualInjections }: LinkInjectionTypes): LinkInjection[] {
428
+ return [...manualInjections.map(i => ({ ...i, manual: true })), ...aiInjections]
429
+ }
430
+
431
+ export function separateLinkInjectionTypes(injections: LinkInjection[]): LinkInjectionTypes {
432
+ return {
433
+ aiInjections: injections.filter(i => !i.manual),
434
+ manualInjections: injections.filter(i => i.manual),
435
+ }
436
+ }
437
+
438
+ export function isValidInjection(injection: LinkInjection): boolean {
439
+ return !injection.inactive && !injection.removed && !injection.duplicate && hasValidTypeData(injection) && isValidPlaylinkType(injection)
440
+ }
441
+
442
+ /**
443
+ * An injection can be of various playlink types, when all are false equivalent, the link is not valid.
444
+ * It should be treated similar to an inactive playlink in this case.
445
+ */
446
+ export function isValidPlaylinkType(injection: LinkInjection): boolean {
447
+ if (injection.in_text || injection.in_text === undefined) return true
448
+ return !!injection.after_article
449
+ }
450
+
451
+ export function filterInvalidInTextInjections(injections: LinkInjection[]): LinkInjection[] {
452
+ return filterRemovedAndInactiveInjections(injections).filter(i => i.in_text !== false && isValidInjection(i))
453
+ }
454
+
455
+ export function filterInvalidAfterArticleInjections(injections: LinkInjection[]): LinkInjection[] {
456
+ return filterRemovedAndInactiveInjections(injections).filter(i => i.after_article === true && isValidInjection(i))
457
+ }
458
+
459
+ /**
460
+ * Filter injections that were marked as removed or inactive or have an equivalent removed or inactive manual injections, soley based on the same sentence and title.
461
+ */
462
+ export function filterRemovedAndInactiveInjections(injections: LinkInjection[]): LinkInjection[] {
463
+ return injections.filter(injection => {
464
+ if (injection.removed || injection.inactive) return false
465
+ if (injection.manual && (!injection.removed && !injection.inactive)) return true
466
+
467
+ return !injections.some(i => i.manual && (i.removed || i.inactive) && isEquivalentInjection(i, injection))
468
+ })
469
+ }
470
+
471
+ /**
472
+ * Injections are sorted first by their sentence and second by their title length. The first sorting, sentence, is so that injections remain
473
+ * roughly grouped. The second sorting is to prevent shorter titles from merging into longer ones. For instance;
474
+ * "Shrek 2 is the sequel to Shrek". If "Shrek" appears as an injection before Shrek 2, it will incorrect inject into "Shrek 2".
475
+ * By placing the longer titles first, we prevent that.
476
+ */
477
+ export function sortInjections(injections: LinkInjection[]): LinkInjection[] {
478
+ return injections.slice().sort((a, b) => {
479
+ if (a.sentence < b.sentence) return -1
480
+ if (a.sentence > b.sentence) return 1
481
+
482
+ const difference = b.title.length - a.title.length
483
+ if (difference !== 0) return difference
484
+
485
+ return 0
486
+ })
487
+ }
488
+
489
+ export function isAvailableAsManualInjection(injection: LinkInjection, injectionIndex: number, injections: LinkInjection[]): boolean {
490
+ return injections.some((i, index) => {
491
+ return injectionIndex !== index && i.manual && isEquivalentInjection(i, injection)
492
+ })
493
+ }
494
+
495
+ export function isEquivalentInjection(injection1: LinkInjection, injection2: LinkInjection): boolean {
496
+ return injection1.title === injection2.title && cleanPhrase(injection1.sentence) === cleanPhrase(injection2.sentence)
497
+ }
498
+
499
+ export function hasValidTypeData(injection: LinkInjection): boolean {
500
+ if (injection.type === 'title' && !!injection.title_details) return true
501
+ if (injection.type === 'participant' && !!injection.participant_details) return true
502
+
503
+ return false
504
+ }
505
+
506
+ export function getPlayPilotWrapperElement(): Element {
507
+ return document.querySelector('[data-playpilot-link-injections]') || document.body
508
+ }
509
+
510
+ export function doesParticipantMeetThreshold(injections: LinkInjection[], participant: ParticipantData): boolean {
511
+ if (participant.popularity === null || participant.popularity === undefined) return true
512
+
513
+ const useArticleAverage = window.PlayPilotLinkInjections?.config?.participant_injection_popularity_threshold_use_article_average ?? true
514
+ const defaultThreshold = 0
515
+ const configThreshold = window.PlayPilotLinkInjections?.config?.participant_injection_popularity_threshold
516
+ const threshold = configThreshold ?? defaultThreshold
517
+
518
+ if (threshold === 0) return true
519
+ if (!useArticleAverage) return participant.popularity >= threshold
520
+
521
+ const averagePopularity = injections
522
+ .filter(i => i.type === 'participant')
523
+ .reduce((total, { participant_details }, _, { length }) => total + (participant_details!.popularity || 0) / length, 0)
524
+
525
+ return participant.popularity >= averagePopularity * (threshold / 100)
526
+ }