@playpilot/tpi 8.42.0-beta.1 → 8.42.1

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