@playpilot/tpi 8.41.0 → 8.42.0

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