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