PageSourceSearch

https://quatrorodas.abril.com.br/wp-content/themes/abril-master2/p…/js/pip-bootstrap.js?ver=0298283839390303

js abril.com.br collected 2026-09-24 06:44:08 UTC 23,950 bytes, 730 lines download raw bytes

1/**
2 * Bootstrap unificado dos players Dailymotion.
3 *
4 * Prioridade de PIP:
5 * 1) thumbnail
6 * 2) primeiro vídeo do conteúdo
7 * 3) fallback (bloco final)
8 */
9/* phpcs:ignoreFile WordPress.Security.NonceVerification.Recommended -- Script de frontend sem processamento de dados de formulário. */
10(function() {
11    'use strict';
12
13    if (window.__abrilDmBootstrapInitialized) {
14        return;
15    }
16    window.__abrilDmBootstrapInitialized = true;
17
18    var CONTEXT_THUMBNAIL = 'thumbnail';
19    var CONTEXT_CONTENT = 'content';
20    var CONTEXT_FALLBACK = 'fallback';
21    var DOC_POSITION_FOLLOWING = (typeof Node !== 'undefined' && Node.DOCUMENT_POSITION_FOLLOWING) ? Node.DOCUMENT_POSITION_FOLLOWING : 4;
22    var DOC_POSITION_PRECEDING = (typeof Node !== 'undefined' && Node.DOCUMENT_POSITION_PRECEDING) ? Node.DOCUMENT_POSITION_PRECEDING : 2;
23    var promotedCounter = 0;
24
25    function onReady(callback) {
26        if (document.readyState === 'loading') {
27            document.addEventListener('DOMContentLoaded', callback);
28            return;
29        }
30        callback();
31    }
32
33    function toArray(list) {
34        return Array.prototype.slice.call(list || []);
35    }
36
37    function hasClass(el, className) {
38        return !!(el && el.classList && el.classList.contains(className));
39    }
40
41    function closestByClass(el, className) {
42        var node = el;
43        while (node) {
44            if (hasClass(node, className)) {
45                return node;
46            }
47            node = node.parentElement;
48        }
49        return null;
50    }
51
52    function closestWithContext(el) {
53        var node = el;
54        while (node) {
55            if (node.getAttribute) {
56                var ctx = node.getAttribute('data-dailymotion-context');
57                if (ctx) {
58                    return ctx;
59                }
60            }
61            node = node.parentElement;
62        }
63        return '';
64    }
65
66    function normalizeContext(ctx) {
67        if (ctx === CONTEXT_THUMBNAIL || ctx === CONTEXT_CONTENT || ctx === CONTEXT_FALLBACK) {
68            return ctx;
69        }
70        return CONTEXT_CONTENT;
71    }
72
73    function inferContextFromElement(el) {
74        var explicitContext = closestWithContext(el);
75        if (explicitContext) {
76            return normalizeContext(explicitContext);
77        }
78
79        if (closestByClass(el, 'custom-featured-media') || closestByClass(el, 'embed-dailymotion')) {
80            return CONTEXT_THUMBNAIL;
81        }
82
83        if (closestByClass(el, 'abril-dailymotion-container')) {
84            return CONTEXT_FALLBACK;
85        }
86
87        if (closestByClass(el, 'content') || closestByClass(el, 'article-content')) {
88            return CONTEXT_CONTENT;
89        }
90
91        return CONTEXT_CONTENT;
92    }
93
94    function compareDomOrder(a, b) {
95        if (!a || !b || !a.element || !b.element || a.element === b.element) {
96            return 0;
97        }
98
99        var relation = a.element.compareDocumentPosition(b.element);
100        if (relation & DOC_POSITION_FOLLOWING) {
101            return -1;
102        }
103        if (relation & DOC_POSITION_PRECEDING) {
104            return 1;
105        }
106        return 0;
107    }
108
109    function parseVideoIdFromUrl(rawUrl) {
110        if (!rawUrl || typeof rawUrl !== 'string') {
111            return '';
112        }
113
114        var normalizedUrl = rawUrl.trim();
115        if (!normalizedUrl) {
116            return '';
117        }
118
119        if (normalizedUrl.indexOf('//') === 0) {
120            normalizedUrl = window.location.protocol + normalizedUrl;
121        }
122
123        var matches = normalizedUrl.match(/(?:dailymotion\.com\/(?:embed\/video|video)\/|dai\.ly\/)([a-zA-Z0-9]+)/i);
124        if (matches && matches[1]) {
125            return matches[1];
126        }
127
128        if (normalizedUrl.indexOf('geo.dailymotion.com/player/') !== -1) {
129            var query = normalizedUrl.split('?')[1] || '';
130            if (query) {
131                var params = query.split('&');
132                for (var i = 0; i < params.length; i++) {
133                    var parts = params[i].split('=');
134                    if (parts.length === 2 && parts[0] === 'video' && parts[1]) {
135                        return parts[1];
136                    }
137                }
138            }
139        }
140
141        return '';
142    }
143
144    function readCandidateMetadataFromElement(el) {
145        var wrapper = closestByClass(el, 'abril-video-wrapper--dailymotion');
146        if (!wrapper || !wrapper.getAttribute) {
147            return {
148                title: '',
149                thumbnail_url: ''
150            };
151        }
152
153        return {
154            title: wrapper.getAttribute('data-video-title') || wrapper.getAttribute('data-dailymotion-title') || '',
155            thumbnail_url: wrapper.getAttribute('data-video-thumbnail') || wrapper.getAttribute('data-dailymotion-thumbnail') || ''
156        };
157    }
158
159    function replaceIframeWithContainer(iframe, context, videoId) {
160        promotedCounter += 1;
161
162        var container = document.createElement('div');
163        container.id = 'dailymotion-promoted-player-' + promotedCounter;
164        container.className = 'abril-dailymotion-video-embed abril-dailymotion-promoted-embed';
165        container.setAttribute('data-dailymotion-promoted', '1');
166        container.setAttribute('data-video-provider', 'dailymotion');
167        container.setAttribute('data-video-id', videoId);
168        container.setAttribute('data-dailymotion-context', context);
169
170        if (closestByClass(iframe, 'fit-video')) {
171            container.style.position = 'absolute';
172            container.style.top = '0';
173            container.style.left = '0';
174            container.style.width = '100%';
175            container.style.height = '100%';
176        } else {
177            container.style.width = iframe.style.width || '100%';
178            container.style.height = iframe.style.height || '100%';
179        }
180
181        iframe.parentNode.replaceChild(container, iframe);
182        return container;
183    }
184
185    function collectPromotedIframeCandidates() {
186        var selector = [
187            'iframe[src*="dailymotion.com/embed/video"]',
188            'iframe[src*="dailymotion.com/video/"]',
189            'iframe[src*="dai.ly/"]',
190            'iframe[src*="geo.dailymotion.com/player/"]'
191        ].join(',');
192
193        var iframeNodes = toArray(document.querySelectorAll(selector));
194        var candidates = [];
195
196        iframeNodes.forEach(function(iframe) {
197            if (iframe.getAttribute('data-abril-dm-promoted') === '1') {
198                return;
199            }
200
201            if (closestByClass(iframe, 'dailymotion-player-wrapper')) {
202                return;
203            }
204
205            var isThumbnailEmbed = !!closestByClass(iframe, 'custom-featured-media');
206            var isArticleEmbed = !!closestByClass(iframe, 'article') || !!close
206stByClass(iframe, 'article-content') || !!closestByClass(iframe, 'content');
207            if (!isThumbnailEmbed && !isArticleEmbed) {
208                return;
209            }
210
211            var src = iframe.getAttribute('src') || '';
212            var videoId = parseVideoIdFromUrl(src);
213            if (!videoId) {
214                return;
215            }
216
217            var context = inferContextFromElement(iframe);
218            var metadata = readCandidateMetadataFromElement(iframe);
219            var container = replaceIframeWithContainer(iframe, context, videoId);
220
221            candidates.push({
222                key: container.id,
223                container_id: container.id,
224                type: 'video',
225                id: videoId,
226                title: metadata.title,
227                thumbnail_url: metadata.thumbnail_url,
228                player_id: null,
229                context: context,
230                source: 'promoted-iframe',
231                element: container
232            });
233        });
234
235        return candidates;
236    }
237
238    function collectQueuedCandidates() {
239        var queue = window.__abrilDmQueuedPlayers || [];
240        var candidates = [];
241
242        queue.forEach(function(payload) {
243            var players = (payload && payload.playersData) ? payload.playersData : [];
244            players.forEach(function(playerData) {
245                if (!playerData || !playerData.container_id || !playerData.id) {
246                    return;
247                }
248
249                var container = document.getElementById(playerData.container_id);
250                if (!container) {
251                    return;
252                }
253
254                var context = normalizeContext(playerData.context || inferContextFromElement(container));
255                candidates.push({
256                    key: playerData.container_id,
257                    container_id: playerData.container_id,
258                    type: playerData.type || 'video',
259                    id: playerData.id,
260                    player_id: playerData.player_id || null,
261                    context: context,
262                    source: 'queued',
263                    element: container
264                });
265            });
266        });
267
268        return candidates;
269    }
270
271    function uniqueCandidates(candidates) {
272        var seen = {};
273        return candidates.filter(function(candidate) {
274            if (!candidate || !candidate.key || seen[candidate.key]) {
275                return false;
276            }
277            seen[candidate.key] = true;
278            return true;
279        });
280    }
281
282    function pickOwner(candidates) {
283        var thumbnails = [];
284        var contents = [];
285        var fallbacks = [];
286
287        candidates.forEach(function(candidate) {
288            var context = normalizeContext(candidate.context);
289            if (context === CONTEXT_THUMBNAIL) {
290                thumbnails.push(candidate);
291            } else if (context === CONTEXT_FALLBACK) {
292                fallbacks.push(candidate);
293            } else {
294                contents.push(candidate);
295            }
296        });
297
298        thumbnails.sort(compareDomOrder);
299        contents.sort(compareDomOrder);
300        fallbacks.sort(compareDomOrder);
301
302        if (thumbnails.length) {
303            return thumbnails[0];
304        }
305        if (contents.length) {
306            return contents[0];
307        }
308        if (fallbacks.length) {
309            return fallbacks[0];
310        }
311        return null;
312    }
313
314    function getLibraryPlayerId(owner) {
315        if (owner && owner.player_id && owner.player_id !== 'default') {
316            return owner.player_id;
317        }
318
319        var queue = window.__abrilDmQueuedPlayers || [];
320        for (var i = 0; i < queue.length; i++) {
321            if (queue[i] && queue[i].libraryPlayerId && queue[i].libraryPlayerId !== 'default') {
322                return queue[i].libraryPlayerId;
323            }
324        }
325
326        if (window.abrilDailymotionPipConfig && window.abrilDailymotionPipConfig.defaultPlayerId) {
327            return window.abrilDailymotionPipConfig.defaultPlayerId;
328        }
329
330        return 'default';
331    }
332
333    function sanitizeText(text) {
334        if (!text || typeof text !== 'string') {
335            return '';
336        }
337
338        var str = text.toLowerCase();
339        if (str.normalize) {
340            str = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
341        }
342        str = str.replace(/&amp/g, 'e').replace(/&/g, 'e');
343        str = str.replace(/[$%@#\(\)+*!><"'}{|^~;]/g, '');
344        str = str.replace(/\s+/g, ' ').trim();
345        return str;
346    }
347
348    function isValidPpid(value) {
349        if (!value || typeof value !== 'string') {
350            return false;
351        }
352
353        return /^[0-9a-zA-Z]{32,150}$/.test(value.trim());
354    }
355
356    function getLocalStorageItem(key) {
357        try {
358            return window.localStorage ? window.localStorage.getItem(key) : '';
359        } catch (e) {
360            return '';
361        }
362    }
363
364    function setLocalStorageItem(key, value) {
365        try {
366            if (window.localStorage) {
367                window.localStorage.setItem(key, value);
368            }
369        } catch (e) {
370            return;
371        }
372    }
373
374    function getFallbackPpidSource() {
375        var logUser = '';
376
377        try {
378            var rawAssetsUser = getLocalStorageItem('abrilAssetsUser');
379            var assetsUser = rawAssetsUser ? JSON.parse(rawAssetsUser) : null;
380            if (assetsUser && assetsUser.crm) {
381                logUser = String(assetsUser.crm);
382            }
383        } catch (e) {
384            logUser = '';
385        }
386
387        if (logUser) {
388            return logUser;
389        }
390
391        return getLocalStorageItem('abrilUserId') || '';
392    }
393
394    function hashPpidSource(value) {
395        if (typeof window.md5 !== 'function') {
396            return '';
397        }
398
399        try {
400            return window.md5(String(value));
401        } catch (e) {
402            return '';
403        }
404    }
405
406    function getPpid() {
407        var storedPpid = getLocalStorageItem('abrAdPPID');
408        if (isValidPpid(storedPpid)) {
409            return storedPpid.trim();
410        }
411
412        var fallbackSource = getFallbackPpidSource();
413        if (!fallbackSource) {
414            return '';
415        }
416
417        var fallbackPpid = hashPpidSource(fallbackSource);
418        if (!isValidPpid(fallbackPpid)) {
419            return '';
420        }
421
422        setLocalStorageItem('abrAdPPID', fallbackPpid);
423        return fallbackPpid;
424    }
425
426    function getConfiguredCustomConfig() {
427        var config = window.abrilDailymotionPipConfig;
428        if (!config || !config.customConfig || typeof config.customConfig !== 'object') {
429            return {};
430        }
431
432        return config.customConfig;
433    }
434
435    function appendKeyvalue(keyvalues, key, value) {
436        if (value === null || typeof value === 'undefined' || value === '') {
437            return keyvalues;
438        }
439
440        var separator = keyvalues ? '&' : '';
441        return keyvalues + separator + encodeURIComponent(key) + '=' + encodeURIComponent(String(value));
442    }
443
444    function mergeConfiguredCustomConfig(customConfig) {
445        var configuredCustomConfig = getConfiguredCustomConfig();
446        var allowedKeys = ['pmnd', 'pmxd', 'pmad', 'vpos'];
447
448        allowedKeys.forEach(function(key) {
449            var value = configuredCustomConfig[key];
450            if (value === null || typeof value === 'undefined' || value === '') {
451                return;
452            }
453            customConfig[key] = value;
454        });
455
456        customConfig.keyvalues = appendKeyvalue(
457            customConfig.keyvalues || '',
458            'pod',
459            configuredCustomConfig.pod
460        );
461
462        if (!customConfig.keyvalues) {
463            delete customConfig.keyvalues;
464        }
465    }
466
467    function buildCustomConfig() {
468        var cd = window.customData;
469        var customConfig = {};
470
471        if (cd && typeof cd === 'object') {
472            var marca = sanitizeText(cd.marca || '').replace(/\s/g, '');
473            if (marca) {
474                if (marca === 'vejasaopaulo') {
475                    marca = 'vejasp';
476                }
477                if (marca === 'casacombr') {
478                    marca = 'casa';
479                }
480
481                var editoria = '';
482                if (cd.editoria && typeof cd.editoria === 'object' && cd.editoria.length > 0) {
483                    editoria = sanitizeText(cd.editoria[0]).replace(/\s/g, '-');
484                } else if (cd.editoria && typeof cd.editoria === 'string') {
485                    editoria = sanitizeText(cd.editoria).replace(/\s/g, '-');
486                }
487
488                var tags = '';
489                if (cd.keywords && typeof cd.keywords === 'string') {
490                    var rawKeywords = cd.keywords.replace(/[\r\n]+/g, ',');
491                    var keywordsArray = rawKeywords.split(',');
492                    var sanitizedTags = [];
493                    for (var i = 0; i < keywordsArray.length; i++) {
494                        var tag = sanitizeText(keywordsArray[i]).replace(/\s/g, '-');
495                        if (tag) {
496                            sanitizedTags.push(tag);
497                        }
498                    }
499                    tags = sanitizedTags.join(',');
500                }
501
502                var tipoPagina = sanitizeText(cd['tipo-pagina'] || '').replace(/\s/g, '-');
503                var marcaCanal = editoria ? marca + '/' + editoria : marca;
504
505                var keyvalues = '';
506                if (marcaCanal) {
507                    keyvalues += 'marca_canal=' + marcaCanal;
508                }
509                if (tags) {
510                    keyvalues += '&tags=' + tags;
511                }
512                if (tipoPagina) {
513                    keyvalues += '&tipo_pagina=' + tipoPagina;
514                }
515
516                if (keyvalues) {
517                    customConfig.dynamiciu = '/9287/' + marca + '/instream_broadcast';
518                    customConfig.keyvalues = keyvalues;
519                }
520            }
521        }
522
523        var ppid = getPpid();
524        if (ppid) {
525            customConfig.ppid = ppid;
526        }
527
528        mergeConfiguredCustomConfig(customConfig);
529
530        if (Object.keys(customConfig).length === 0) {
531            return null;
532        }
533
534        return customConfig;
535    }
536
537    function loadDailymotionLibrary(libraryPlayerId, callback) {
538        if (typeof window.dailymotion !== 'undefined' && window.dailymotion && window.dailymotion.createPlayer) {
539            callback();
540            return;
541        }
542
543        var scriptId = 'abril-dailymotion-sdk-script';
544        var existingScript = document.getElementById(scriptId);
545        if (existingScript) {
546            if (existingScript.getAttribute('data-loaded') === '1') {
547                callback();
548                return;
549            }
550            existingScript.addEventListener('load', callback);
551            return;
552        }
553
554        var script = document.createElement('script');
555        script.id = scriptId;
556        if (libraryPlayerId && libraryPlayerId !== 'default') {
557            script.src = 'https://geo.dailymotion.com/libs/player/' + encodeURIComponent(libraryPlayerId) + '.js';
558        } else {
559            script.src = 'https://geo.dailymotion.com/libs/player.js';
560        }
561        script.async = true;
562        script.addEventListener('load', function() {
563            script.setAttribute('data-loaded', '1');
564            callback();
565        });
566        document.head.appendChild(script);
567    }
568
569    function getSecondaryPlayerId() {
570        if (window.abrilDailymotionPipConfig && window.abrilDailymotionPipConfig.secondaryPlayerId) {
571            return window.abrilDailymotionPipConfig.secondaryPlayerId;
572        }
573
574        return '';
575    }
576
577    function buildStandardEmbedUrl(candidate, libraryPlayerId) {
578        if (!candidate || !candidate.id) {
579            return '';
580        }
581
582        var itemId = encodeURIComponent(candidate.id);
583        var iframePlayerId = '';
584        if (candidate.player_id && candidate.player_id !== 'default') {
585            iframePlayerId = candidate.player_id;
586        } else if (libraryPlayerId && libraryPlayerId !== 'default') {
587            iframePlayerId = libraryPlayerId;
588        }
589
590        if (iframePlayerId) {
591            var query = [];
592            if (candidate.type === 'playlist') {
593                query.push('playlist=' + itemId);
594            } else {
595                query.push('video=' + itemId);
596            }
597            query.push('autostart=off');
598
599            return 'https://geo.dailymotion.com/player/' + encodeURIComponent(iframePlayerId) + '.html?' + query.join('&');
600        }
601
602        if (candidate.type === 'playlist') {
603            return 'https://www.dailymotion.com/embed/playlist/' + itemId + '?autoplay=0';
604        }
605
606        return 'https://www.dailymotion.com/embed/video/' + itemId + '?autoplay=0';
607    }
608
609    function renderSecondaryIframe(candidate, libraryPlayerId) {
610        if (!candidate || !candidate.container_id) {
611            return;
612        }
613
614        var container = document.getElementById(candidate.container_id);
615        if (!container || container.getAttribute('data-dm-secondary-ready') === '1') {
616            return;
617        }
618
619        var embedUrl = buildStandardEmbedUrl(candidate, libraryPlayerId);
620        if (!embedUrl) {
621            return;
622        }
623
624        container.setAttribute('data-dm-secondary-ready', '1');
625        container.setAttribute('data-dailymotion-context', normalizeContext(candidate.context));
626        container.innerHTML = '';
627
628        var iframe = document.createElement('iframe');
629        iframe.src = embedUrl;
630        iframe.setAttribute('frameborder', '0');
631        iframe.setAttribute('allowfullscreen', '');
632        iframe.setAttribute('allow', 'fullscreen; picture-in-picture; web-share');
633        iframe.setAttribute('loading', 'lazy');
634        iframe.setAttribute('title', candidate && candidate.title ? candidate.title : 'Dailymotion video player');
635
636        container.appendChild(iframe);
637    }
638
639    function createPlayer(candidate, libraryPlayerId, customConfig, allowAutoplay, overridePlayerId) {
640        if (!window.dailymotion || !window.dailymotion.createPlayer) {
641            return Promise.resolve();
642        }
643
644        var config = {
645            params: {
646                mute: true
647            }
648        };
649
650        if (!allowAutoplay) {
651            config.params.autostart = 'off';
652        }
653
654        if (customConfig) {
655            config.params.customConfig = customConfig;
656        }
657
658        if (candidate.type === 'playlist') {
659            config.playlist = candidate.id;
660        } else {
661            config.video = candidate.id;
662        }
663
664        if (overridePlayerId && overridePlayerId !== libraryPlayerId && overridePlayerId !== 'default') {
665            config.player = overridePlayerId;
666        } else if (candidate.player_id && candidate.player_id !== libraryPlayerId && candidate.player_id !== 'default') {
667            config.player = candidate.player_id;
668        }
669
670        return window.dailymotion.createPlayer(candidate.container_id, config)
671            .then(function(player) {
672                var container = document.getElementById(candidate.container_id);
673                if (container) {
674                    container.setAttribute('data-dailymotion-context', normalizeContext(candidate.context));
675                    var iframe = container.querySelector('iframe');
676                    if (iframe) {
677                        iframe.setAttribute('loading', 'lazy');
678                    }
679                }
680
681                return player;
682            })
683            .catch(function() {
684                return null;
685            });
686    }
687
688    function bootstrap() {
689        var queuedCandidates = collectQueuedCandidates();
690        var iframeCandidates = collectPromotedIframeCandidates();
691        var candidates = uniqueCandidates(queuedCandidates.concat(iframeCandidates));
692
693        if (!candidates.length) {
694            return;
695        }
696
697        var owner = pickOwner(candidates);
698        if (!owner) {
699            return;
700        }
701
702        var orderedCandidates = candidates.slice().sort(compareDomOrder);
703        var autoplayCandidate = orderedCandidates[0] || owner;
704        var libraryPlayerId = getLibraryPlayerId(owner);
705        var secondaryPlayerId = getSecondaryPlayerId();
706        var customConfig = buildCustomConfig();
707
708        loadDailymotionLibrary(libraryPlayerId, function() {
709            var prepareRemaining = function() {
710                candidates.forEach(function(candidate) {
711                    if (candidate.key === autoplayCandidate.key) {
712                        return;
713                    }
714
715                    if (secondaryPlayerId) {
716                        createPlayer(candidate, libraryPlayerId, customConfig, false, secondaryPlayerId);
717                    } else {
718                        renderSecondaryIframe(candidate, libraryPlayerId);
719                    }
720                });
721            };
722
723            createPlayer(autoplayCandidate, libraryPlayerId, customConfig, true, '')
724                .then(prepareRemaining)
725                .catch(prepareRemaining);
726        });
727    }
728
729    onReady(bootstrap);
730})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.