UNPKG

ng-gpt

Version:
871 lines (854 loc) 35.3 kB
import { isPlatformBrowser, DOCUMENT } from '@angular/common'; import * as i0 from '@angular/core'; import { InjectionToken, PLATFORM_ID, Injectable, Inject, EventEmitter, Optional, Directive, Input, Output, NgModule } from '@angular/core'; import { from, timer } from 'rxjs'; import * as i4 from '@angular/router'; import { loadImaSdk } from '@alugha/ima'; class GptConfig { } const GPT_CONFIG = new InjectionToken('gptConfig'); const GPT_URL = '//www.googletagservices.com/tag/js/gpt.js'; class IdleService { constructor(platformId, zone) { const w = isPlatformBrowser(platformId) ? window : {}; if (w.requestIdleCallback) { this.requestIdleCallback = (fun) => { return w.requestIdleCallback(fun); }; } else { this.requestIdleCallback = (fun) => { return zone.runOutsideAngular(() => w.setTimeout(fun, 50)); }; } } request(fun) { this.requestIdleCallback(fun); } } IdleService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: IdleService, deps: [{ token: PLATFORM_ID }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Injectable }); IdleService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: IdleService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: IdleService, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID] }] }, { type: i0.NgZone }]; } }); class ScriptInjectorService { constructor(httpError) { this.httpError = httpError; } completeURL(url) { const ssl = document.location.protocol === 'https:'; return (ssl ? 'https:' : 'http:') + url; } createScript(url) { const script = document.createElement('script'); script.async = true; script.type = 'text/javascript'; script.src = this.completeURL(url); return script; } promiseScript(script, url) { const promise = new Promise((resolve, reject) => { script.onload = () => { resolve(script); }; script.onerror = () => { reject({ path: url, loaded: false, }); }; }); promise.catch((response) => { this.httpError.httpError({ status: 400 }, `loading script "${url}"`); }); return promise; } injectScript(script) { const head = document.head || document.querySelector('head'); head.appendChild(script); } scriptInjector(url) { const script = this.createScript(url); this.injectScript(script); return this.promiseScript(script, url); } } ScriptInjectorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ScriptInjectorService, deps: [{ token: HttpErrorService }], target: i0.ɵɵFactoryTarget.Injectable }); ScriptInjectorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ScriptInjectorService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ScriptInjectorService, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: HttpErrorService }]; } }); class HttpErrorService { constructor() { this.isErrorCode = function (code) { if (typeof code === 'number') { return !(code >= 200 && code < 300); } return code[0] !== '2'; }; } httpError(response, message) { console.error(`Error (${response.status}) ${message ? message : ''}`); } } HttpErrorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: HttpErrorService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); HttpErrorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: HttpErrorService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: HttpErrorService, decorators: [{ type: Injectable }] }); class PubadsSetConfigService { /** * Passes location information from websites so you can geo-target line items to specific locations. * * @param address Freeform address. * @param pubads Publisher Ads service. This service is used to fetch and show ads from your Google Ad Manager account. */ addLocation(address, pubads) { if (address) { pubads.setLocation(address); } } /** * Sets the value for the publisher-provided ID. * * @param ppid An alphanumeric ID provided by the publisher with a recommended maximum of 150 characters. * @param pubads Publisher Ads service. This service is used to fetch and show ads from your Google Ad Manager account. */ addPPID(ppid, pubads) { if (ppid) { pubads.setPublisherProvidedId(ppid); } } /** * Sets a custom targeting parameter for this slot. * * @param globalTargeting * @param pubads Publisher Ads service. This service is used to fetch and show ads from your Google Ad Manager account. */ addTargeting(globalTargeting, pubads) { if (Object.keys(globalTargeting).length) { for (const key in globalTargeting) { if (globalTargeting.hasOwnProperty(key)) { pubads.setTargeting(key, globalTargeting[key]); } } } } /** * Sets the page-level preferences for SafeFrame configuration. * * @param safeFrameConfig The configuration object. * @param pubads Publisher Ads service. This service is used to fetch and show ads from your Google Ad Manager account. */ addSafeFrameConfig(safeFrameConfig, pubads) { if (Object.keys(safeFrameConfig).length) pubads.setSafeFrameConfig(safeFrameConfig); } } PubadsSetConfigService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: PubadsSetConfigService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); PubadsSetConfigService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: PubadsSetConfigService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: PubadsSetConfigService, decorators: [{ type: Injectable }] }); class GPTDurationError extends Error { constructor(interval) { super(`Invalid interval: '${interval}'ls`); } } class ParseDurationService { convertToMilliseconds(time, unit) { console.assert(/^(m?s|min|h)$/g.test(unit)); if (unit === 'ms') { return time; } if (unit === 's') { return time * 1000; } if (unit === 'min') { return time * 60 * 1000; } return time * 60 * 60 * 1000; } convert(match) { const time = parseFloat(match[1]); if (match.length === 2) { return time; } return this.convertToMilliseconds(time, match[2]); } parseDuration(interval) { if (interval === undefined || interval === null) { throw new GPTDurationError(interval); } if (typeof interval === 'number') { return interval; } if (typeof interval !== 'string') { throw new TypeError(`'${interval}' must be of number or string type`); } const match = interval.match(/((?:\d+)?.?\d+)(m?s|min|h)?/); if (!match) { throw new GPTDurationError(interval); } return this.convert(match); } } ParseDurationService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ParseDurationService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); ParseDurationService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ParseDurationService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: ParseDurationService, decorators: [{ type: Injectable }] }); class GPTRefreshError extends Error { } class GptRefreshService { constructor(config, inject, parseDuration) { this.config = config; this.inject = inject; this.parseDuration = parseDuration; this.refreshEvent = new EventEmitter(); this.refreshSlots = []; this.intervals = {}; } slotRefresh(slot, refreshInterval, initRefresh = false) { const deferred = from([slot]).toPromise(), task = { slot: slot, deferred: deferred }; deferred.then(() => { if (this.hasSlotInterval(slot)) { this.cancelInterval(slot); } if (refreshInterval) { this.addSlotInterval(task, refreshInterval); } }); if (this.config.singleRequestMode === true && initRefresh) { // Use a timer to handle refresh of a single request mode this.refreshSlots.push(slot); if (this.singleRequest && !this.singleRequest.closed) { this.singleRequest.unsubscribe(); } this.singleRequest = timer(100).subscribe(() => { const pubads = googletag.pubads(); pubads.enableSingleRequest(); googletag.enableServices(); this.refreshSlots.forEach((s) => { googletag.display(s.getSlotElementId()); }); pubads.refresh(this.refreshSlots); this.refreshSlots = []; }); } else { googletag.display(slot.getSlotElementId()); this.refresh([task]); } return deferred; } cancelInterval(slot) { if (!this.hasSlotInterval(slot)) { throw new GPTRefreshError('No interval for given slot'); } const interval = this.intervals[this.slotIntervalKey(slot)]; interval.unsubscribe(); delete this.intervals[slot]; return this; } hasSlotInterval(slot) { return this.slotIntervalKey(slot) in this.intervals; } refresh(tasks) { if (tasks === undefined) { googletag.cmd.push(() => { googletag.pubads().refresh(); }); return; } if (tasks.length === 0) { return false; } googletag.cmd.push(() => { googletag.pubads().refresh(tasks.map((task) => task.slot)); tasks.forEach((task) => { Promise.resolve(task.slot); }); }); return true; } addSlotInterval(task, interval) { const parsedInterval = this.parseDuration.parseDuration(interval); this.validateInterval(parsedInterval, interval); const refresh = timer(parsedInterval, parsedInterval).subscribe(() => { const doc = this.inject.get(DOCUMENT); if (!this.hiddenCheck(doc.getElementById(task.slot.getSlotElementId()))) { this.refresh([task]); this.refreshEvent.emit(task.slot); } }); this.intervals[this.slotIntervalKey(task.slot)] = refresh; return refresh; } slotIntervalKey(slot) { return slot.getSlotId().getDomId(); } validateInterval(milliseconds, beforeParsing) { if (milliseconds < 1000) { console.warn('Careful: ${beforeParsing} is quite a low interval!'); } } hiddenCheck(element) { if (typeof window !== 'undefined') { const css = window.getComputedStyle(element); if (css.display === 'none') { return true; } else if (element.parentElement) { return this.hiddenCheck(element.parentElement); } } return false; } } GptRefreshService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptRefreshService, deps: [{ token: GPT_CONFIG, optional: true }, { token: i0.Injector }, { token: ParseDurationService }], target: i0.ɵɵFactoryTarget.Injectable }); GptRefreshService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptRefreshService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptRefreshService, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: GptConfig, decorators: [{ type: Optional }, { type: Inject, args: [GPT_CONFIG] }] }, { type: i0.Injector }, { type: ParseDurationService }]; } }); class GptIDGeneratorService { constructor() { this.generatedIDs = {}; } generateID(type = 'gpt-ad') { let id = ''; do { const number = Math.random().toString().slice(2); id = type + '-' + number; } while (id in this.generatedIDs); this.generatedIDs[id] = true; return id; } gptIDGenerator(element) { if (element && element.id && !(element.id in this.generatedIDs)) { return element.id; } const id = this.generateID(element.tagName.toLowerCase()); if (element) { element.id = id; } return id; } isTaken(id) { return id in this.generatedIDs; } isUnique(id) { return !this.isTaken(id); } } GptIDGeneratorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptIDGeneratorService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); GptIDGeneratorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptIDGeneratorService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: GptIDGeneratorService, decorators: [{ type: Injectable }] }); class NgGptService { constructor(platformID, config, idleLoad, pubadsSetConfig, scriptInjector) { this.platformID = platformID; this.config = config; this.pubadsSetConfig = pubadsSetConfig; this.scriptInjector = scriptInjector; this.collapseEmptyDivs = true; this.enableVideoAds = false; this.enableLazyLoad = {}; this.centering = false; this.personalizedAds = true; this.limitedAds = false; this.forceSafeFrame = false; this.address = ''; this.ppid = ''; this.globalTargeting = {}; this.safeFrameConfig = {}; this.loadGPT = true; this.loaded = false; if (isPlatformBrowser(this.platformID)) { const w = window, googletag = w.googletag || {}; this.gptConfig(); googletag.cmd = googletag.cmd || []; googletag.cmd.push(() => { this.setup(); }); w.googletag = googletag; if (this.loadGPT) { const loadScript = () => { this.scriptInjector.scriptInjector(GPT_URL).then((script) => { this.loaded = true; }); }; if (idleLoad) { idleLoad.request(loadScript); } else { loadScript(); } } } } gptConfig() { for (const key in this.config) { if (this.hasOwnProperty(key)) { this[key] = this.config[key]; } } } setup() { const w = window, googletag = w.googletag, pubads = googletag.pubads(); if (this.enableVideoAds) pubads.enableVideoAds(); if (this.collapseEmptyDivs) pubads.collapseEmptyDivs(); pubads.disableInitialLoad(); pubads.setForceSafeFrame(this.forceSafeFrame); pubads.setCentering(this.centering); pubads.setRequestNonPersonalizedAds(this.personalizedAds ? 0 : 1); this.pubadsSetConfig.addLocation(this.address, pubads); this.pubadsSetConfig.addPPID(this.ppid, pubads); this.pubadsSetConfig.addTargeting(this.globalTargeting, pubads); this.pubadsSetConfig.addSafeFrameConfig(this.safeFrameConfig, pubads); pubads.setPrivacySettings({ limitedAds: this.limitedAds, }); if (this.config.singleRequestMode !== true) { if (this.config.enableVideoAds) { pubads.enableVideoAds(); } googletag.enableServices(); } if (Object.keys(this.enableLazyLoad).length) { pubads.enableLazyLoad(this.enableLazyLoad); } } hasLoaded() { return this.loaded; } defineTask(task) { if (isPlatformBrowser(this.platformID)) { const w = window, googletag = w.googletag; googletag.cmd.push(task); } } } NgGptService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptService, deps: [{ token: PLATFORM_ID }, { token: GPT_CONFIG }, { token: IdleService, optional: true }, { token: PubadsSetConfigService }, { token: ScriptInjectorService }], target: i0.ɵɵFactoryTarget.Injectable }); NgGptService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: function () { return [{ type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID] }] }, { type: GptConfig, decorators: [{ type: Inject, args: [GPT_CONFIG] }] }, { type: IdleService, decorators: [{ type: Optional }] }, { type: PubadsSetConfigService }, { type: ScriptInjectorService }]; } }); class GptRefreshEvent { } class NgGptAdDirective { constructor(platformID, elementRef, gpt, gptRefresh, gptIDGenerator, config, router) { this.platformID = platformID; this.elementRef = elementRef; this.gpt = gpt; this.gptRefresh = gptRefresh; this.gptIDGenerator = gptIDGenerator; this.config = config; this.sizes = 'fluid'; this.sizeMapping = []; this.targetingArguments = {}; this.afterRefresh = new EventEmitter(); this.scripts = []; this.exclusions = []; if (isPlatformBrowser(this.platformID)) { this.gptRefresh.refreshEvent.subscribe((slot) => { if (slot === this.slot) { this.afterRefresh.emit({ type: 'refresh', slot: slot }); } }); if (router) { this.onSameNavigation = router.events.pipe().subscribe((event) => { if (this.slot && !this.refresh && this.config.onSameNavigation === 'refresh') { this.refreshContent.call(this); } }); } } } ngOnInit() { this.checkRequiredFields(this.adUnit, 'adUnit'); if (isPlatformBrowser(this.platformID) && !this.id) { this.gptIDGenerator.gptIDGenerator(this.elementRef.nativeElement); } } ngAfterViewInit() { if (isPlatformBrowser(this.platformID)) { this.gpt.defineTask(() => { this.defineSlot(); }); } } ngOnDestroy() { if (this.slot) { googletag.destroySlots([this.slot]); } if (this.onSameNavigation) { this.onSameNavigation.unsubscribe(); } } setSizeMapping(slot) { const ad = this.getState(); if (ad.sizeMapping.length === 0) { return; } const sizeMapping = googletag.sizeMapping(); ad.sizeMapping.forEach((mapping) => { sizeMapping.addSize(mapping.viewport, mapping.sizes); }); slot.defineSizeMapping(sizeMapping.build()); } defineSlot() { const ad = this.getState(), element = this.elementRef.nativeElement; this.slot = googletag.defineSlot(ad.adUnit, ad.sizes, element.id); if (this.forceSafeFrame !== undefined && ad.forceSafeFrame === !this.config.forceSafeFrame) { this.slot.setForceSafeFrame(ad.forceSafeFrame); } // if (ad.clickUrl) { // this.slot.setClickUrl(ad.clickUrl); // } if (ad.collapseEmptyDivs) { this.slot.setCollapseEmptyDiv(true, true); } if (ad.safeFrameConfig) { this.slot.setSafeFrameConfig(ad.safeFrameConfig); } googletag.pubads().addEventListener('slotRenderEnded', (event) => { if (event.slot === this.slot) { this.afterRefresh.emit({ type: 'renderEnded', slot: this.slot, data: event, }); } }); this.setSizeMapping(this.slot); Object.keys(ad.targetingArguments).forEach((arg) => { this.slot.setTargeting(arg, ad.targetingArguments[arg]); }); ad.exclusions.forEach((exclusion) => { this.slot.setCategoryExclusion(exclusion); }); ad.scripts.forEach((script) => { script(this.slot); }); if (this.config.enableVideoAds) { this.slot.addService(googletag.companionAds()); } this.slot.addService(googletag.pubads()); this.refreshContent(); } refreshContent() { this.gptRefresh.slotRefresh(this.slot, this.refresh, true).then((slot) => { this.afterRefresh.emit({ type: 'init', slot: slot }); }); } get isHidden() { return this.gptRefresh.hiddenCheck(this.elementRef.nativeElement); } getState() { return Object.freeze({ sizes: typeof this.sizes === 'string' ? [this.sizes] : this.sizes, sizeMapping: this.sizeMapping, targetingArguments: this.targetingArguments, exclusions: this.exclusions, adUnit: this.adUnit, forceSafeFrame: this.forceSafeFrame === true, safeFrameConfig: this.safeFrameConfig, // clickUrl: this.clickUrl, refresh: this.refresh, scripts: this.scripts, collapseEmptyDivs: this.collapseEmptyDivs === true, }); } checkRequiredFields(input, name) { if (input === null) { throw new Error(`Attribute ${name} is required`); } } addExclusion(exclusion) { this.exclusions.push(exclusion); } addScript(script) { this.scripts.push(script); } } NgGptAdDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptAdDirective, deps: [{ token: PLATFORM_ID }, { token: i0.ElementRef }, { token: NgGptService }, { token: GptRefreshService }, { token: GptIDGeneratorService }, { token: GPT_CONFIG }, { token: i4.Router, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); NgGptAdDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.2.4", type: NgGptAdDirective, selector: "gpt-ad", inputs: { id: "id", adUnit: "adUnit", sizes: "sizes", sizeMapping: "sizeMapping", forceSafeFrame: "forceSafeFrame", safeFrameConfig: "safeFrameConfig", refresh: "refresh", collapseEmptyDivs: "collapseEmptyDivs", targetingArguments: "targetingArguments" }, outputs: { afterRefresh: "afterRefresh" }, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptAdDirective, decorators: [{ type: Directive, args: [{ selector: 'gpt-ad' }] }], ctorParameters: function () { return [{ type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID] }] }, { type: i0.ElementRef }, { type: NgGptService }, { type: GptRefreshService }, { type: GptIDGeneratorService }, { type: GptConfig, decorators: [{ type: Inject, args: [GPT_CONFIG] }] }, { type: i4.Router, decorators: [{ type: Optional }] }]; }, propDecorators: { id: [{ type: Input }], adUnit: [{ type: Input }], sizes: [{ type: Input }], sizeMapping: [{ type: Input }], forceSafeFrame: [{ type: Input }], safeFrameConfig: [{ type: Input }], refresh: [{ type: Input }], collapseEmptyDivs: [{ type: Input }], targetingArguments: [{ type: Input }], afterRefresh: [{ type: Output }] } }); class NgGptVideoDirective { constructor(platformId, elementRef, renderer, gptIDGenerator) { this.platformId = platformId; this.elementRef = elementRef; this.renderer = renderer; this.gptIDGenerator = gptIDGenerator; this.adEvents = new EventEmitter(); this.adsDone = false; } ngOnInit() { if (isPlatformBrowser(this.platformId)) { const el = this.elementRef.nativeElement; if (!this.id) { this.gptIDGenerator.gptIDGenerator(el); } this.contentPlayer = el.querySelector('video'); this.renderer.setAttribute(this.contentPlayer, 'width', this.sizes[0].toString()); this.renderer.setAttribute(this.contentPlayer, 'height', this.sizes[1].toString()); this.adContainer = el.querySelector('.ad-container'); if (!this.adContainer) { this.adContainer = this.renderer.createElement('div'); this.renderer.addClass(this.adContainer, 'ad-container'); this.renderer.appendChild(el, this.adContainer); } // ima setup loadImaSdk().then((ima) => { this.ima = ima; return this.setUpIMA(); }); this.adActions.subscribe((act) => { switch (act) { case 'play': this.play(); break; case 'pause': this.pause(); break; case 'resume': this.resume(); break; } }); } } play() { if (!this.adsDone) { this.initialUserAction(); this.loadAds(); this.adsDone = true; } } pause() { if (this.adsManager) { this.adsManager.pause(); } } resume() { if (this.adsManager) { this.adsManager.resume(); } } setUpIMA() { // Create the ad display container. this.adDisplayContainer = new this.ima.AdDisplayContainer(this.adContainer, this.contentPlayer); // Create ads loader. this.adsLoader = new this.ima.AdsLoader(this.adDisplayContainer); // Listen and respond to ads loaded and error events. this.adsLoader.addEventListener(this.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, (event) => this.onAdsManagerLoaded(event), false); this.adsLoader.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR, (event) => this.onAdError(event), false); // An event listener to tell the SDK that our content video // is completed so the SDK can play any post-roll ads. this.contentPlayer.onended = () => { this.contentEnded(); }; } initialUserAction() { this.adDisplayContainer.initialize(); this.contentPlayer.load(); } requestAds(adTagUrl) { const adsRequest = new this.ima.AdsRequest(); adsRequest.adTagUrl = adTagUrl; adsRequest.linearAdSlotWidth = this.sizes[0]; adsRequest.linearAdSlotHeight = this.sizes[1]; adsRequest.nonLinearAdSlotWidth = this.sizes[0]; adsRequest.nonLinearAdSlotHeight = this.sizes[1]; this.adsLoader.requestAds(adsRequest); } contentEnded() { this.contentCompleteCalled = true; this.adsLoader.contentComplete(); } onAdsManagerLoaded(adsManagerLoadedEvent) { const adsRenderingSettings = new this.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; this.adsManager = adsManagerLoadedEvent.getAdsManager(this.contentPlayer, adsRenderingSettings); this.startAdsManager(this.adsManager); } startAdsManager(adsManager) { // Attach the pause/resume events. adsManager.addEventListener(this.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, () => this.onContentPauseRequested(), false); adsManager.addEventListener(this.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, () => this.onContentResumeRequested(), false); // Handle errors. adsManager.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR, (event) => this.onAdError(event), false); const events = [ this.ima.AdEvent.Type.ALL_ADS_COMPLETED, this.ima.AdEvent.Type.CLICK, this.ima.AdEvent.Type.COMPLETE, this.ima.AdEvent.Type.FIRST_QUARTILE, this.ima.AdEvent.Type.LOADED, this.ima.AdEvent.Type.MIDPOINT, this.ima.AdEvent.Type.PAUSED, this.ima.AdEvent.Type.STARTED, this.ima.AdEvent.Type.THIRD_QUARTILE, ]; events.forEach((event) => adsManager.addEventListener(event, (adEvent) => this.onAdEvent(adEvent), false)); adsManager.init(this.sizes[0], this.sizes[1], this.ima.ViewMode.NORMAL); adsManager.start(); } onContentPauseRequested() { this.pauseForAd(); } onContentResumeRequested() { // Without this check the video starts over from the beginning on a // post-roll's CONTENT_RESUME_REQUESTED if (!this.contentCompleteCalled) { this.resumeAfterAd(); } } onAdEvent(adEvent) { if (adEvent.type === this.ima.AdEvent.Type.LOADED) { const ad = adEvent.getAd(); if (!ad.isLinear()) { this.onContentResumeRequested(); } } this.adEvents.emit(adEvent); } onAdError(adErrorEvent) { if (this.adsManager) { this.adsManager.destroy(); } this.resumeAfterAd(); this.adEvents.emit(adErrorEvent); } // application functions resumeAfterAd() { this.contentPlayer.play(); } pauseForAd() { this.contentPlayer.pause(); } loadAds() { this.requestAds(this.adTagUrl); } } NgGptVideoDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptVideoDirective, deps: [{ token: PLATFORM_ID }, { token: i0.ElementRef }, { token: i0.Renderer2 }, { token: GptIDGeneratorService }], target: i0.ɵɵFactoryTarget.Directive }); NgGptVideoDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.2.4", type: NgGptVideoDirective, selector: "gpt-video", inputs: { id: "id", adTagUrl: "adTagUrl", sizes: "sizes", adActions: "adActions" }, outputs: { adEvents: "adEvents" }, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptVideoDirective, decorators: [{ type: Directive, args: [{ selector: 'gpt-video' }] }], ctorParameters: function () { return [{ type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID] }] }, { type: i0.ElementRef }, { type: i0.Renderer2 }, { type: GptIDGeneratorService }]; }, propDecorators: { id: [{ type: Input }], adTagUrl: [{ type: Input }], sizes: [{ type: Input }], adEvents: [{ type: Output }], adActions: [{ type: Input }] } }); class NgGptModule { static forRoot(config) { return { ngModule: NgGptModule, providers: [ ...(config && config.idleLoad === true ? [IdleService] : []), { provide: GPT_CONFIG, useValue: config || {} }, ], }; } } NgGptModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); NgGptModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptModule, declarations: [NgGptAdDirective, NgGptVideoDirective], exports: [NgGptAdDirective, NgGptVideoDirective] }); NgGptModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptModule, providers: [ HttpErrorService, ScriptInjectorService, IdleService, PubadsSetConfigService, GptRefreshService, ParseDurationService, GptIDGeneratorService, ] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: NgGptModule, decorators: [{ type: NgModule, args: [{ declarations: [NgGptAdDirective, NgGptVideoDirective], providers: [ HttpErrorService, ScriptInjectorService, IdleService, PubadsSetConfigService, GptRefreshService, ParseDurationService, GptIDGeneratorService, ], exports: [NgGptAdDirective, NgGptVideoDirective], }] }] }); /* * Public API Surface of ng-gpt */ /** * Generated bundle index. Do not edit. */ export { GptRefreshEvent, NgGptAdDirective, NgGptModule, NgGptService, NgGptVideoDirective }; //# sourceMappingURL=ng-gpt.mjs.map