-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amp-ad-network-doubleclick-impl.js
751 lines (697 loc) · 26.3 KB
/
amp-ad-network-doubleclick-impl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Because AdSense and DoubleClick are both operated by Google and their A4A
// implementations share some behavior in common, part of the logic for this
// implementation is located in the ads/google/a4a directory rather than here.
// Most other ad networks will want to put their A4A code entirely in the
// extensions/amp-ad-network-${NETWORK_NAME}-impl directory.
import {
AmpA4A,
RENDERING_TYPE_HEADER,
XORIGIN_MODE,
DEFAULT_SAFEFRAME_VERSION,
assignAdUrlToError,
} from '../../amp-a4a/0.1/amp-a4a';
import {
experimentFeatureEnabled,
DOUBLECLICK_EXPERIMENT_FEATURE,
} from './doubleclick-a4a-config';
import {
isInManualExperiment,
} from '../../../ads/google/a4a/traffic-experiments';
import {
extractGoogleAdCreativeAndSignature,
googleAdUrl,
truncAndTimeUrl,
googleBlockParameters,
googlePageParameters,
isGoogleAdsA4AValidEnvironment,
isReportingEnabled,
AmpAnalyticsConfigDef,
extractAmpAnalyticsConfig,
groupAmpAdsByType,
addCsiSignalsToAmpAnalyticsConfig,
QQID_HEADER,
} from '../../../ads/google/a4a/utils';
import {getMultiSizeDimensions} from '../../../ads/google/utils';
import {
googleLifecycleReporterFactory,
setGoogleLifecycleVarsFromHeaders,
} from '../../../ads/google/a4a/google-data-reporter';
import {
lineDelimitedStreamer,
metaJsonCreativeGrouper,
} from '../../../ads/google/a4a/line-delimited-response-handler';
import {stringHash32} from '../../../src/crypto';
import {removeElement} from '../../../src/dom';
import {tryParseJson} from '../../../src/json';
import {dev, user} from '../../../src/log';
import {getMode} from '../../../src/mode';
import {extensionsFor, xhrFor} from '../../../src/services';
import {isExperimentOn} from '../../../src/experiments';
import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint';
import {insertAnalyticsElement} from '../../../src/analytics';
import {setStyles} from '../../../src/style';
import {utf8Encode} from '../../../src/utils/bytes';
import {isCancellation} from '../../../src/error';
/** @type {string} */
const TAG = 'amp-ad-network-doubleclick-impl';
/** @const {string} */
const DOUBLECLICK_BASE_URL =
'https://securepubads.g.doubleclick.net/gampad/ads';
/** @private @const {!Object<string,string>} */
const PAGE_LEVEL_PARAMS_ = {
'gdfp_req': '1',
'sfv': DEFAULT_SAFEFRAME_VERSION,
'u_sd': window.devicePixelRatio,
};
/**
* @const {string}
* @visibileForTesting
*/
export const TFCD = 'tagForChildDirectedTreatment';
/** @private {?Promise} */
let sraRequests = null;
/**
* Array of functions used to combine block level request parameters for SRA
* request.
* @private @const
* {!Array<!function(!Array<AmpAdNetworkDoubleclickImpl>):?Object<string,string>}
*/
const BLOCK_SRA_COMBINERS_ = [
instances => {
const uniqueIuNames = {};
let uniqueIuNamesCount = 0;
const prevIusEncoded = [];
instances.forEach(instance => {
const iu = dev().assert(instance.element.getAttribute('data-slot'));
const componentNames = (iu || '').split('/');
const encodedNames = [];
for (let i = 0; i < componentNames.length; i++) {
if (componentNames[i] == '') {
continue;
}
let index = uniqueIuNames[componentNames[i]];
if (index == undefined) {
uniqueIuNames[componentNames[i]] = (index = uniqueIuNamesCount++);
}
encodedNames.push(index);
}
prevIusEncoded.push(encodedNames.join('/'));
});
return {
'iu_parts': Object.keys(uniqueIuNames).join(),
'enc_prev_ius': prevIusEncoded.join(),
};
},
// Although declared at a block-level, this is actually page level so
// return true if ANY indicate cookie opt out.
instances => getFirstInstanceValue_(instances, instance => {
return instance.jsonTargeting_ &&
instance.jsonTargeting_['cookieOptOut'] ? {'co': '1'} : null;
}),
instances => {
return {'adks': instances.map(instance => instance.adKey_).join()};
},
instances => {
return {'prev_iu_szs': instances.map(instance =>
`${instance.size_.width}x${instance.size_.height}`).join()};
},
// Although declared at a block-level, this is actually page level so
// return true if ANY indicate TFCD.
instances => getFirstInstanceValue_(instances, instance => {
return instance.jsonTargeting_ && instance.jsonTargeting_[TFCD] ?
{'tfcd': instance.jsonTargeting_[TFCD]} : null;
}),
// Although declared at a block-level, this is actually page level so
// return true if ANY indicate manual experiment.
instances => getFirstInstanceValue_(instances, instance => {
return isInManualExperiment(instance.element) ? {'adtest': 'on'} : null;
}),
instances => {
const scps = [];
instances.forEach(instance => {
if (!instance.jsonTargeting_) {
return;
}
scps.push(serializeTargeting_(
instance.jsonTargeting_['targeting'] || null,
instance.jsonTargeting_['categoryExclusions'] || null));
});
return scps.length ? {'prev_scp': scps.join('|')} : null;
},
instances => {
const eids = {};
instances.forEach(instance => {
const currEids = instance.element.getAttribute('data-experiment-id');
if (currEids) {
currEids.split(',').forEach(eid => eids[eid] = 1);
}
});
return Object.keys(eids).length ? {'eid': Object.keys(eids).join()} : null;
},
];
export class AmpAdNetworkDoubleclickImpl extends AmpA4A {
/**
* @param {!Element} element
*/
constructor(element) {
super(element);
/**
* @type {!../../../ads/google/a4a/performance.GoogleAdLifecycleReporter}
*/
this.lifecycleReporter_ = this.lifecycleReporter_ ||
this.initLifecycleReporter();
/**
* Config to generate amp-analytics element for active view reporting.
* @type {?JsonObject}
* @private
*/
this.ampAnalyticsConfig_ = null;
/** @private {!../../../src/service/extensions-impl.Extensions} */
this.extensions_ = extensionsFor(this.win);
/** @private {?string} */
this.qqid_ = null;
/** @private {?({width, height}|../../../src/layout-rect.LayoutRectDef)} */
this.size_ = null;
/** @private {?Element} */
this.ampAnalyticsElement_ = null;
/** @private {?Object<string,*>}*/
this.jsonTargeting_ = null;
/** @private {number} */
this.adKey_ = 0;
// TODO(keithwrightbos) - how can pub enable?
/** @protected @const {boolean} */
this.useSra = getMode().localDev && /(\?|&)force_sra=true(&|$)/.test(
this.win.location.search) ||
!!this.win.document.querySelector(
'meta[name=amp-ad-doubleclick-sra]') ||
experimentFeatureEnabled(this.win, DOUBLECLICK_EXPERIMENT_FEATURE.SRA);
const sraInitializer = this.initializeSraPromise_();
/** @protected {?function(?../../../src/service/xhr-impl.FetchResponse)} */
this.sraResponseResolver = sraInitializer.resolver;
/** @protected {?function(*)} */
this.sraResponseRejector = sraInitializer.rejector;
/** @private {!Promise<?../../../src/service/xhr-impl.FetchResponse>} */
this.sraResponsePromise_ = sraInitializer.promise;
}
/** @override */
isValidElement() {
return isGoogleAdsA4AValidEnvironment(this.win) &&
this.isAmpAdElement() &&
// Ensure not within remote.html iframe.
!document.querySelector('meta[name=amp-3p-iframe-src]');
}
/** @override */
delayAdRequestEnabled() {
return experimentFeatureEnabled(
this.win, DOUBLECLICK_EXPERIMENT_FEATURE.DELAYED_REQUEST);
}
/**
* @return {!{
* resolver: ?function(?../../../src/service/xhr-impl.FetchResponse),
* rejector: ?function(*),
* promise: !Promise<?../../../src/service/xhr-impl.FetchResponse>,
* }}
* @private
*/
initializeSraPromise_() {
let resolver = null;
let rejector = null;
const promise = new Promise((inResolver, inRejector) => {
resolver = inResolver;
rejector = inRejector;
});
return {resolver, rejector, promise};
}
/**
* Constructs block-level url parameters with side effect of setting
* size_, jsonTargeting_, and adKey_ fields.
* @return {!Object<string,string|boolean|number>}
*/
getBlockParameters_() {
dev().assert(this.size_);
dev().assert(this.jsonTargeting_);
let sizeStr = `${this.size_.width}x${this.size_.height}`;
const tfcd = this.jsonTargeting_ && this.jsonTargeting_[TFCD];
const multiSizeDataStr = this.element.getAttribute('data-multi-size');
if (multiSizeDataStr) {
const multiSizeValidation = this.element
.getAttribute('data-multi-size-validation') || 'true';
// The following call will check all specified multi-size dimensions,
// verify that they meet all requirements, and then return all the valid
// dimensions in an array.
const dimensions = getMultiSizeDimensions(
multiSizeDataStr,
Number(this.element.getAttribute('width')),
Number(this.element.getAttribute('height')),
multiSizeValidation == 'true');
sizeStr += '|' + dimensions
.map(dimension => dimension.join('x'))
.join('|');
}
return Object.assign({
'iu': this.element.getAttribute('data-slot'),
'co': this.jsonTargeting_ &&
this.jsonTargeting_['cookieOptOut'] ? '1' : null,
'adk': this.adKey_,
'sz': sizeStr,
'tfcd': tfcd == undefined ? null : tfcd,
'adtest': isInManualExperiment(this.element) ? 'on' : null,
'scp': serializeTargeting_(
(this.jsonTargeting_ && this.jsonTargeting_['targeting']) || null,
(this.jsonTargeting_ &&
this.jsonTargeting_['categoryExclusions']) || null),
}, googleBlockParameters(this));
}
/**
* Populate's block-level state for ad URL construction.
* @visibileForTesting
*/
populateAdUrlState() {
const width = Number(this.element.getAttribute('width'));
const height = Number(this.element.getAttribute('height'));
// If dc-use-attr-for-format experiment is on, we want to make our attribute
// check to be more strict.
const useAttributesForSize =
isExperimentOn(this.win, 'dc-use-attr-for-format')
? !isNaN(width) && width > 0 && !isNaN(height) && height > 0
: width && height;
this.size_ = useAttributesForSize
? {width, height}
: this.getIntersectionElementLayoutBox();
this.jsonTargeting_ =
tryParseJson(this.element.getAttribute('json')) || {};
this.adKey_ =
this.generateAdKey_(`${this.size_.width}x${this.size_.height}`);
}
/** @override */
getAdUrl() {
if (this.iframe) {
dev().warn(TAG, `Frame already exists, sra: ${this.useSra}`);
return '';
}
// TODO(keithwrightbos): SRA blocks currently unnecessarily generate full
// ad url. This could be optimized however non-SRA ad url is required to
// fallback to non-SRA if single block.
this.populateAdUrlState();
// TODO: Check for required and allowed parameters. Probably use
// validateData, from 3p/3p/js, after noving it someplace common.
const startTime = Date.now();
return getPageLevelParameters_(this.win, this.getAmpDoc(), startTime)
.then(pageLevelParameters =>
googleAdUrl(this, DOUBLECLICK_BASE_URL, startTime,
Object.assign(this.getBlockParameters_(), pageLevelParameters),
['108809080']));
}
/** @override */
extractCreativeAndSignature(responseText, responseHeaders) {
setGoogleLifecycleVarsFromHeaders(responseHeaders, this.lifecycleReporter_);
this.ampAnalyticsConfig_ = extractAmpAnalyticsConfig(this, responseHeaders);
this.qqid_ = responseHeaders.get(QQID_HEADER);
if (this.ampAnalyticsConfig_) {
// Load amp-analytics extensions
this.extensions_./*OK*/loadExtension('amp-analytics');
}
const adResponsePromise =
extractGoogleAdCreativeAndSignature(responseText, responseHeaders);
return adResponsePromise.then(adResponse => {
// If the server returned a size, use that, otherwise use the size that
// we sent in the ad request.
if (adResponse.size) {
this.size_ = adResponse.size;
} else {
adResponse.size = this.size_;
}
this.handleResize_(adResponse.size.width, adResponse.size.height);
return Promise.resolve(adResponse);
});
}
/** @override */
emitLifecycleEvent(eventName, opt_extraVariables) {
if (opt_extraVariables) {
this.lifecycleReporter_.setPingParameters(opt_extraVariables);
}
this.lifecycleReporter_.sendPing(eventName);
}
/** @override */
shouldUnlayoutAmpCreatives() {
// If using SRA, remove AMP creatives if we have at least one non-AMP
// creative present.
return this.useSra && !!this.win.document.querySelector(
'amp-ad[data-a4a-upgrade-type="amp-ad-network-doubleclick-impl"] ' +
'iframe[src]');
}
/** @override */
unlayoutCallback() {
super.unlayoutCallback();
this.element.setAttribute('data-amp-slot-index',
this.win.ampAdSlotIdCounter++);
this.lifecycleReporter_ = this.initLifecycleReporter();
if (this.ampAnalyticsElement_) {
removeElement(this.ampAnalyticsElement_);
this.ampAnalyticsElement_ = null;
}
this.ampAnalyticsConfig_ = null;
this.jsonTargeting_ = null;
// Reset SRA requests to allow for resumeCallback to re-fetch
// ad requests. Assumes that unlayoutCallback will be called for all slots
// in rapid succession (meaning onLayoutMeasure initiated promise chain
// will not be started until resumeCallback).
sraRequests = null;
const sraInitializer = this.initializeSraPromise_();
this.sraResponseResolver = sraInitializer.resolver;
this.sraResponseRejector = sraInitializer.rejector;
this.sraResponsePromise_ = sraInitializer.promise;
this.qqid_ = null;
}
/**
* @return {!../../../ads/google/a4a/performance.BaseLifecycleReporter}
*/
initLifecycleReporter() {
return googleLifecycleReporterFactory(this);
}
/** @override */
onCreativeRender(isVerifiedAmpCreative) {
super.onCreativeRender(isVerifiedAmpCreative);
if (this.ampAnalyticsConfig_) {
dev().assert(!this.ampAnalyticsElement_);
if (isReportingEnabled(this)) {
addCsiSignalsToAmpAnalyticsConfig(
this.win,
this.element,
this.ampAnalyticsConfig_,
this.qqid_,
isVerifiedAmpCreative,
this.lifecycleReporter_.getDeltaTime(),
this.lifecycleReporter_.getInitTime());
}
this.ampAnalyticsElement_ =
insertAnalyticsElement(this.element, this.ampAnalyticsConfig_, true);
}
this.lifecycleReporter_.addPingsForVisibility(this.element);
setStyles(dev().assertElement(this.iframe), {
width: `${this.size_.width}px`,
height: `${this.size_.height}px`,
});
}
/**
* @param {string} size
* @return {string} The ad unit hash key string.
* @private
*/
generateAdKey_(size) {
const element = this.element;
const domFingerprint = domFingerprintPlain(element);
const slot = element.getAttribute('data-slot') || '';
const multiSize = element.getAttribute('data-multi-size') || '';
const string = `${slot}:${size}:${multiSize}:${domFingerprint}`;
return stringHash32(string);
}
/**
* Attempts to resize the ad, if the returned size is smaller than the primary
* dimensions.
* @param {number} width
* @param {number} height
* @private
*/
handleResize_(width, height) {
const pWidth = this.element.getAttribute('width');
const pHeight = this.element.getAttribute('height');
// We want to resize only if neither returned dimension is larger than its
// primary counterpart, and if at least one of the returned dimensions
// differ from its primary counterpart.
if ((width != pWidth || height != pHeight)
&& (width <= pWidth && height <= pHeight)) {
this.attemptChangeSize(height, width).catch(() => {});
}
}
/** @override */
sendXhrRequest(adUrl) {
if (!this.useSra) {
return super.sendXhrRequest(adUrl);
}
// Wait for SRA request which will call response promise when this block's
// response has been returned.
this.initiateSraRequests();
// Null response indicates single slot should execute using non-SRA method.
return this.sraResponsePromise_.then(
response => response || super.sendXhrRequest(adUrl));
}
/**
* Groups slots by type and networkId from data-slot parameter. Exposed for
* ease of testing.
* @return {!Promise<!Object<string,!Array<!Promise<!../../../src/base-element.BaseElement>>>>}
* @visibileForTesting
*/
groupSlotsForSra() {
return groupAmpAdsByType(
this.win, this.element.getAttribute('type'), getNetworkId);
}
/**
* Executes SRA request via the following steps:
* - create only one executor per page
* - get all doubleclick amp-ad instances on the page
* - group by networkID allowing for separate SRA requests
* - for each grouping, construct SRA request
* - handle chunks for streaming response for each block
* @visibileForTesting
*/
initiateSraRequests() {
if (sraRequests) {
return;
}
// Use cancellation of the first slot's promiseId as indication of
// unlayoutCallback execution. Assume that if called for one slot, it will
// be called for all and we should cancel SRA execution.
const checkStillCurrent = this.verifyStillCurrent();
sraRequests = this.groupSlotsForSra()
.then(groupIdToBlocksAry => {
checkStillCurrent();
Object.keys(groupIdToBlocksAry).forEach(networkId => {
const blocks = dev().assert(groupIdToBlocksAry[networkId]);
// TODO: filter blocks with SRA disabled?
Promise.all(blocks).then(instances => {
dev().assert(instances.length);
checkStillCurrent();
// Exclude any instances that do not have an adPromise_ as this
// indicates they were invalid.
const typeInstances =
/** @type {!Array<!AmpAdNetworkDoubleclickImpl>}*/(instances)
.filter(instance => {
const isValid = instance.hasAdPromise();
if (!isValid) {
dev().info(TAG,
'Ignoring instance without ad promise as likely invalid',
instance.element);
}
return isValid;
});
if (!typeInstances.length) {
// Only contained invalid elements.
return;
}
// Determine if more than one block for this element, if not do not
// set sra request promise which results in sending as
// non-SRA request (benefit is it allows direct cache method).
if (typeInstances.length == 1) {
dev().info(TAG, `single block in network ${networkId}`);
typeInstances[0].sraResponseResolver(null);
return;
}
// Construct and send SRA request.
// Chunk hanlder called with metadata and creative for each slot
// in order of URLs given. Construct promise for each slot
// such that its resolver will be called.
const sraRequestAdUrlResolvers =
typeInstances.map(instance => instance.sraResponseResolver);
const slotCallback = metaJsonCreativeGrouper(
(creative, headersObj, done) => {
checkStillCurrent();
// Force safeframe rendering method.
headersObj[RENDERING_TYPE_HEADER] = XORIGIN_MODE.SAFEFRAME;
// Construct pseudo fetch response to be passed down the A4A
// promise chain for this block.
const headers =
/** @type {?../../../src/service/xhr-impl.FetchResponseHeaders} */
({
get: name => headersObj[name],
has: name => !!headersObj[name],
});
const fetchResponse =
/** @type {?../../../src/service/xhr-impl.FetchResponse} */
({
headers,
arrayBuffer: () => utf8Encode(creative),
});
// Pop head off of the array of resolvers as the response
// should match the order of blocks declared in the ad url.
// This allows the block to start rendering while the SRA
// response is streaming back to the client.
dev().assert(sraRequestAdUrlResolvers.shift())(fetchResponse);
// If done, expect array to be empty (ensures ad response
// included data for all slots).
if (done && sraRequestAdUrlResolvers.length) {
dev().warn(TAG, 'Premature end of SRA response',
sraRequestAdUrlResolvers.length, sraUrl);
}
});
// TODO(keithwrightbos) - how do we handle per slot 204 response?
let sraUrl;
return constructSRARequest_(
this.win, this.getAmpDoc(), typeInstances)
.then(sraUrlIn => {
checkStillCurrent();
sraUrl = sraUrlIn;
return xhrFor(this.win).fetch(sraUrl, {
mode: 'cors',
method: 'GET',
credentials: 'include',
});
})
.then(response => {
checkStillCurrent();
return lineDelimitedStreamer(this.win, response, slotCallback);
})
.catch(error => {
assignAdUrlToError(/** @type {!Error} */(error), sraUrl);
const canceled = isCancellation(error);
if (!canceled) {
user().error(TAG, 'SRA request failure', error);
}
// Collapse all slots on failure so long as they are not
// cancellation.
typeInstances.forEach(instance => {
// Reset ad url to ensure layoutCallback does not fallback to
// frame get which would lose SRA guarantees.
// TODO(keithwrightbos): publisher should indicate if
// explicit is required!
instance.resetAdUrl();
if (!canceled) {
instance.attemptCollapse();
}
instance.sraResponseRejector(error);
});
});
});
});
});
}
getPreconnectUrls() {
return ['https://partner.googleadservices.com',
'https://tpc.googlesyndication.com'];
}
}
AMP.registerElement(
'amp-ad-network-doubleclick-impl', AmpAdNetworkDoubleclickImpl);
/** @visibileForTesting */
export function resetSraStateForTesting() {
sraRequests = null;
}
/**
* @param {!Element} element
* @return {string} networkId from data-ad-slot attribute.
* @visibileForTesting
*/
export function getNetworkId(element) {
const networkId = /^(?:\/)?(\d+)/.exec(
dev().assertString(element.getAttribute('data-slot')));
// TODO: guarantee data-ad-slot format as part of isValidElement?
return networkId ? networkId[1] : '';
}
/**
* @param {!Window} win
* @param {!Node|!../../../src/service/ampdoc-impl.AmpDoc} doc
* @param {!Array<!AmpAdNetworkDoubleclickImpl>} instances
* @return {!Promise<string>} SRA request URL
*/
function constructSRARequest_(win, doc, instances) {
const startTime = Date.now();
return getPageLevelParameters_(win, doc, startTime, true)
.then(pageLevelParameters => {
const blockParameters = constructSRABlockParameters(instances);
return truncAndTimeUrl(DOUBLECLICK_BASE_URL,
Object.assign(blockParameters, pageLevelParameters), startTime);
});
}
/**
* @param {!Array<!AmpAdNetworkDoubleclickImpl>} instances
* @visibileForTesting
*/
export function constructSRABlockParameters(instances) {
const parameters = {};
BLOCK_SRA_COMBINERS_.forEach(
combiner => Object.assign(parameters, combiner(instances)));
return parameters;
}
/**
* @param {!Window} win
* @param {!Node|!../../../src/service/ampdoc-impl.AmpDoc} doc
* @param {number} startTime
* @param {boolean=} isSra
* @return {!Promise<!Object<string,string|number|boolean>>}
*/
function getPageLevelParameters_(win, doc, startTime, isSra) {
return googlePageParameters(win, doc, startTime, 'ldjh')
.then(pageLevelParameters => {
const parameters = Object.assign({}, PAGE_LEVEL_PARAMS_);
parameters['impl'] = isSra ? 'fifs' : 'ifr';
return Object.assign(parameters, pageLevelParameters);
});
}
/**
* @param {?Object<string, (!Array<string>|string)>} targeting
* @param {?(!Array<string>|string)} categoryExclusions
* @return {?string}
* @private
*/
function serializeTargeting_(targeting, categoryExclusions) {
const serialized = targeting ?
Object.keys(targeting).map(key => serializeItem_(key, targeting[key])) :
[];
if (categoryExclusions) {
serialized.push(serializeItem_('excl_cat', categoryExclusions));
}
return serialized.length ? serialized.join('&') : null;
}
/**
* @param {string} key
* @param {(!Array<string>|string)} value
* @return {string}
* @private
*/
function serializeItem_(key, value) {
const serializedValue =
(Array.isArray(value) ? value : [value]).map(encodeURIComponent).join();
return `${encodeURIComponent(key)}=${serializedValue}`;
}
/**
* @param {!Array<!AmpAdNetworkDoubleclickImpl>} instances
* @param {!function(AmpAdNetworkDoubleclickImpl):?T} extractFn
* @return {?T} value of first instance with non-null/undefined value or null
* if none can be found
* @template T
* @private
*/
function getFirstInstanceValue_(instances, extractFn) {
for (let i = 0; i < instances.length; i++) {
const val = extractFn(instances[i]);
if (val) {
return val;
}
}
return null;
}