-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amp-ad-network-doubleclick-impl.js
1634 lines (1502 loc) · 55 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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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 '../../amp-a4a/0.1/real-time-config-manager';
import {
AmpA4A,
DEFAULT_SAFEFRAME_VERSION,
RENDERING_TYPE_HEADER,
XORIGIN_MODE,
assignAdUrlToError,
} from '../../amp-a4a/0.1/amp-a4a';
import {
AmpAnalyticsConfigDef,
QQID_HEADER,
ValidAdContainerTypes,
addCsiSignalsToAmpAnalyticsConfig,
extractAmpAnalyticsConfig,
getCsiAmpAnalyticsConfig,
getCsiAmpAnalyticsVariables,
getEnclosingContainerTypes,
getIdentityToken,
googleAdUrl,
googleBlockParameters,
googlePageParameters,
groupAmpAdsByType,
isCdnProxy,
isReportingEnabled,
maybeAppendErrorParameter,
setNameframeExperimentConfigs,
truncAndTimeUrl,
} from '../../../ads/google/a4a/utils';
import {
DOUBLECLICK_EXPERIMENT_FEATURE,
DOUBLECLICK_UNCONDITIONED_EXPERIMENTS,
UNCONDITIONED_CANONICAL_FF_HOLDBACK_EXP_NAME,
experimentFeatureEnabled,
} from './doubleclick-a4a-config';
import {Layout, isLayoutSizeDefined} from '../../../src/layout';
import {RTC_VENDORS} from '../../amp-a4a/0.1/callout-vendors';
import {
RefreshManager, // eslint-disable-line no-unused-vars
getRefreshManager,
} from '../../amp-a4a/0.1/refresh-manager';
import {SafeframeHostApi} from './safeframe-host';
import {Services} from '../../../src/services';
import {VisibilityState} from '../../../src/visibility-state';
import {
addExperimentIdToElement,
} from '../../../ads/google/a4a/traffic-experiments';
import {createElementWithAttributes, removeElement} from '../../../src/dom';
import {deepMerge, dict} from '../../../src/utils/object';
import {dev, user} from '../../../src/log';
import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint';
import {getData} from '../../../src/event-helper';
import {
getExperimentBranch,
isExperimentOn,
randomlySelectUnsetExperiments,
} from '../../../src/experiments';
import {getMode} from '../../../src/mode';
import {getMultiSizeDimensions} from '../../../ads/google/utils';
import {getOrCreateAdCid} from '../../../src/ad-cid';
import {
googleLifecycleReporterFactory,
setGoogleLifecycleVarsFromHeaders,
} from '../../../ads/google/a4a/google-data-reporter';
import {
incrementLoadingAds,
is3pThrottled,
waitFor3pThrottle,
} from '../../amp-ad/0.1/concurrent-load';
import {insertAnalyticsElement} from '../../../src/extension-analytics';
import {
installAnchorClickInterceptor,
} from '../../../src/anchor-click-interceptor';
import {isCancellation} from '../../../src/error';
import {
isInManualExperiment,
} from '../../../ads/google/a4a/traffic-experiments';
import {isSecureUrl, parseQueryString} from '../../../src/url';
import {
lineDelimitedStreamer,
metaJsonCreativeGrouper,
} from '../../../ads/google/a4a/line-delimited-response-handler';
import {setStyles} from '../../../src/style';
import {stringHash32} from '../../../src/string';
import {tryParseJson} from '../../../src/json';
import {utf8Encode} from '../../../src/utils/bytes';
/** @type {string} */
const TAG = 'amp-ad-network-doubleclick-impl';
/** @const {string} */
const DOUBLECLICK_BASE_URL =
'https://securepubads.g.doubleclick.net/gampad/ads';
/** @const {string} */
const RTC_SUCCESS = '2';
/** @visibleForTesting @const {string} */
export const CORRELATOR_CLEAR_EXP_NAME = 'dbclk-correlator-clear';
/** @visibleForTesting @enum {string} */
export const CORRELATOR_CLEAR_EXP_BRANCHES = {
CONTROL: '22302764',
EXPERIMENT: '22302765',
};
/**
* @const {string}
* @visibileForTesting
*/
export const TFCD = 'tagForChildDirectedTreatment';
/** @const {string} */
export const SAFEFRAME_ORIGIN = 'https://tpc.googlesyndication.com';
/** @private {?Promise} */
let sraRequests = null;
/** @typedef {{
adUrl: !Promise<string>,
lineItemId: string,
creativeId: string,
slotId: string,
slotIndex: string,
}} */
let TroubleshootData; // eslint-disable-line no-unused-vars
/** @private {?JsonObject} */
let windowLocationQueryParameters;
/**
* 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.initialSize.width}x${instance.initialSize.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;
},
instances => getFirstInstanceValue_(instances,
instance => instance.buildIdentityParams_()),
];
/**
* Used to manage messages for different fluid ad slots.
*
* Maps a sentinel value to an object consisting of the impl to which that
* sentinel value belongs and the corresponding message handler for that impl.
* @type{!Object<string, !{instance: !AmpAdNetworkDoubleClickDisableSfBinding, connectionEstablished: boolean}>}
*/
// TODO(alanorozco, #13591): Remove.
const fluidListeners = {};
/**
* @param {!Event} event
* @private
*/
// TODO(alanorozco, #13591): Remove.
function fluidMessageListener_(event) {
const data = tryParseJson(getData(event));
if (event.origin != SAFEFRAME_ORIGIN || !data) {
return;
}
if (data['e']) {
// This is a request to establish a postmessaging connection.
const listener = fluidListeners[data['e']];
if (!listener) {
dev().warn(TAG, `Listener for sentinel ${data['e']} not found.`);
return;
}
if (!listener.connectionEstablished) {
listener.instance.connectFluidMessagingChannel();
listener.connectionEstablished = true;
}
return;
}
const payload = tryParseJson(data['p']);
if (!payload || !payload['sentinel']) {
return;
}
const listener = fluidListeners[payload['sentinel']];
if (!listener) {
dev().warn(TAG, `Listener for sentinel ${payload['sentinel']} not found.`);
return;
}
if (data['s'] != 'creative_geometry_update') {
return;
}
listener.instance.receiveMessageForFluid(payload);
}
// TODO(alanorozco, #13591): Flatten into `AmpAdNetworkDoubleclickImpl`
class AmpAdNetworkDoubleclickBinding {
/** @param {!AmpAdNetworkDoubleclickImpl} impl */
constructor(impl) {
/** @protected @const {!AmpAdNetworkDoubleclickImpl} */
this.impl = impl;
/** @private {?./safeframe-host.SafeframeHostApi} */
this.safeframeApi_ = null;
}
/** @public */
layoutCallback() {
// NOOP
}
/** @public */
unlayoutCallback() {
if (this.safeframeApi_) {
this.safeframeApi_.destroy();
}
}
/**
* @param {boolean=} isSafeFrame
* @return {!JsonObject|undefined}
*/
getAdditionalContextMetadata(isSafeFrame = false) {
const {impl} = this;
const {isFluid, initialSize, fluidImpressionUrl} = impl;
const creativeSize = impl.getCreativeSize();
if (!isFluid && !isSafeFrame) {
return;
}
this.safeframeApi_ = this.safeframeApi_ ||
new SafeframeHostApi(
impl, isFluid, initialSize, creativeSize, fluidImpressionUrl);
return this.safeframeApi_.getSafeframeNameAttr();
}
}
// TODO(alanorozco, #13591): Remove
class AmpAdNetworkDoubleClickDisableSfBinding
extends AmpAdNetworkDoubleclickBinding {
/** @override */
layoutCallback() {
const {isFluid} = this.impl;
if (!isFluid) {
return;
}
this.registerListenerForFluid_();
}
/** @private */
registerListenerForFluid_() {
const {sentinel, win} = this.impl;
fluidListeners[sentinel] = fluidListeners[sentinel] || {
instance: this,
connectionEstablished: false,
};
if (Object.keys(fluidListeners).length == 1) {
win.addEventListener('message', fluidMessageListener_, false);
}
}
/** @override */
unlayoutCallback() {
this.maybeRemoveListenerForFluid_();
}
/** @private */
maybeRemoveListenerForFluid_() {
const {isFluid, win, sentinel} = this.impl;
if (!isFluid) {
return;
}
delete fluidListeners[sentinel];
if (!Object.keys(fluidListeners).length) {
win.removeEventListener('message', fluidMessageListener_);
}
}
/** @override */
getAdditionalContextMetadata(unusedIsSafeframe) {
const {
isFluid,
win,
safeframeVersion,
sentinel,
nameframeExperimentConfig,
} = this.impl;
const attributes = dict({});
if (isFluid) {
attributes['uid'] = 1;
attributes['hostPeerName'] = win.location.origin;
// The initial geometry isn't used for anything important, but it is
// expected, so we pass this string with all zero values.
attributes['initialGeometry'] = JSON.stringify(
dict({
'windowCoords_t': 0,
'windowCoords_r': 0,
'windowCoords_b': 0,
'windowCoords_l': 0,
'frameCoords_t': 0,
'frameCoords_r': 0,
'frameCoords_b': 0,
'frameCoords_l': 0,
'styleZIndex': 'auto',
'allowedExpansion_t': 0,
'allowedExpansion_r': 0,
'allowedExpansion_b': 0,
'allowedExpansion_l': 0,
'xInView': 0,
'yInView': 0,
}));
attributes['permissions'] = JSON.stringify(
dict({
'expandByOverlay': false,
'expandByPush': false,
'readCookie': false,
'writeCookie': false,
}));
attributes['metadata'] = JSON.stringify(
dict({
'shared': {
'sf_ver': safeframeVersion,
'ck_on': 1,
'flash_ver': '26.0.0',
},
}));
attributes['reportCreativeGeometry'] = true;
attributes['isDifferentSourceWindow'] = false;
attributes['sentinel'] = sentinel;
} else {
Object.assign(attributes, nameframeExperimentConfig);
}
return attributes;
}
/**
* Handles Fluid-related messages dispatched from SafeFrame.
* @param {!JsonObject} payload
* @public
*/
receiveMessageForFluid(payload) {
const {impl} = this;
const newHeight = payload && parseInt(payload['height'], 10);
if (!newHeight) {
// TODO(levitzky) Add actual error handling here.
impl.forceCollapse();
return;
}
impl.attemptChangeHeight(newHeight)
.then(() => this.onFluidResize_())
.catch(() => {
// TODO(levitzky) Add more error handling here
impl.forceCollapse();
});
}
/**
* Postmessages an initial message to the fluid creative.
* @public
*/
connectFluidMessagingChannel() {
const {iframe} = this.impl;
dev().assert(iframe.contentWindow,
'Frame contentWindow unavailable.');
iframe.contentWindow./*OK*/postMessage(
JSON.stringify(dict({'message': 'connect', 'c': 'sfchannel1'})),
SAFEFRAME_ORIGIN);
}
/**
* Fires a delayed impression and notifies the Fluid creative that its
* container has been resized.
* @private
*/
onFluidResize_() {
const {impl} = this;
const {fluidImpressionUrl, iframe} = this.impl;
if (fluidImpressionUrl) {
impl.fireDelayedImpressions(fluidImpressionUrl);
impl.fluidImpressionUrl = null;
}
dev().assert(iframe.contentWindow,
'Frame contentWindow unavailable.');
iframe.contentWindow./*OK*/postMessage(
JSON.stringify(dict({'message': 'resize-complete', 'c': 'sfchannel1'})),
SAFEFRAME_ORIGIN);
}
}
/** @final */
export class AmpAdNetworkDoubleclickImpl extends AmpA4A {
/**
* @param {!Element} element
*/
constructor(element) {
super(element);
/** @private @const {!AmpAdNetworkDoubleclickBinding} */
// TODO(alanorozco, #13591): Flatten.
this.binding_ = isExperimentOn(this.win, 'a4a-doubleclick-disable-sf') ?
new AmpAdNetworkDoubleClickDisableSfBinding(this) :
new AmpAdNetworkDoubleclickBinding(this);
/* eslint-enable no-undef */
/**
* @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_ = Services.extensionsFor(this.win);
/** @private {?string} */
this.qqid_ = null;
/** @package {?({width: number, height: number}|../../../src/layout-rect.LayoutRectDef)} */
// TODO(alanorozco, #13591): Make `@private`.
this.initialSize = null;
/** @private {?{width: number, height: number}} */
this.returnedSize_ = 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;
/** @private {?RefreshManager} */
this.refreshManager_ = null;
/** @private {number} */
this.refreshCount_ = 0;
/** @private {number} */
this.ifi_ = 0;
/** @package {boolean} */
// TODO(alanorozco, #13591): Make `@private`.
this.isFluid = false;
/** @package {?string} */
// TODO(alanorozco, #13591): Make `@private`.
this.fluidImpressionUrl = null;
/** @private {?Promise<!../../../ads/google/a4a/utils.IdentityToken>} */
this.identityTokenPromise_ = null;
/** @type {?../../../ads/google/a4a/utils.IdentityToken} */
this.identityToken = null;
/** @private {boolean} */
this.preloadSafeframe_ = true;
/** @private {!TroubleshootData} */
this.troubleshootData_ = /** @type {!TroubleshootData} */ ({});
/**
* @private {?boolean} whether preferential rendered AMP creative, null
* indicates no creative render.
*/
this.isAmpCreative_ = null;
/** @private {boolean} */
this.isIdleRender_ = false;
/** @package {!../../../ads/google/a4a/utils.NameframeExperimentConfig} */
// TODO(alanorozco, #13591): Make `@private`.
this.nameframeExperimentConfig = {
instantLoad: false,
writeInBody: false,
};
}
/** @override */
idleRenderOutsideViewport() {
// Disable if publisher has indicated a non-default loading strategy.
if (this.element.getAttribute('data-loading-strategy')) {
return false;
}
const expVal = this.postAdResponseExperimentFeatures['render-idle-vp'];
let vpRange = parseInt(expVal, 10);
if (expVal && isNaN(vpRange)) {
// holdback branch sends non-numeric value.
return false;
}
vpRange = vpRange || 12;
this.isIdleRender_ = true;
// NOTE(keithwrightbos): handle race condition where previous
// idleRenderOutsideViewport marked slot as idle render despite never
// being schedule due to being beyond viewport max offset. If slot
// comes within standard outside viewport range, then ensure throttling
// will not be applied.
this.getResource().whenWithinRenderOutsideViewport().then(
() => this.isIdleRender_ = false);
return vpRange;
}
/** @override */
isLayoutSupported(layout) {
this.isFluid = layout == Layout.FLUID;
return this.isFluid || isLayoutSizeDefined(layout);
}
/** @override */
isValidElement() {
/**
* isValidElement used to also check that we are in a valid A4A environment,
* however this is not necessary as that is checked by doubleclickIsA4AEnabled,
* which is always called as part of the upgrade path from an amp-ad element
* to an amp-ad-doubleclick element. Thus, if we are an amp-ad, we can be sure
* that it has been verified.
*/
return this.isAmpAdElement() &&
// Ensure not within remote.html iframe.
!this.win.document.querySelector('meta[name=amp-3p-iframe-src]');
}
/** @override */
delayAdRequestEnabled() {
return experimentFeatureEnabled(
this.win, DOUBLECLICK_EXPERIMENT_FEATURE.DELAYED_REQUEST);
}
/** @override */
buildCallback() {
super.buildCallback();
this.identityTokenPromise_ = Services.viewerForDoc(this.getAmpDoc())
.whenFirstVisible()
.then(() => getIdentityToken(this.win, this.getAmpDoc()));
this.troubleshootData_.slotId = this.element.getAttribute('data-slot');
this.troubleshootData_.slotIndex =
this.element.getAttribute('data-amp-slot-index');
if (this.win['dbclk_a4a_viz_change']) {
// Only create one per page but ensure all slots get experiment
// selection.
const expId = getExperimentBranch(this.win, CORRELATOR_CLEAR_EXP_NAME);
if (expId) {
// If experiment was already selected, add to element to ensure it is
// included in request.
addExperimentIdToElement(expId, this.element);
}
return;
}
this.win['dbclk_a4a_viz_change'] = true;
const sfPreloadExpName = 'a4a-safeframe-preloading-off';
const experimentInfoMap =
/** @type {!Object<string,
!../../../src/experiments.ExperimentInfo>} */ ({});
experimentInfoMap[sfPreloadExpName] = {
isTrafficEligible: () => true,
branches: ['21061135', '21061136'],
};
randomlySelectUnsetExperiments(this.win, experimentInfoMap);
const sfPreloadExpId = getExperimentBranch(this.win, sfPreloadExpName);
if (sfPreloadExpId) {
addExperimentIdToElement(sfPreloadExpId, this.element);
this.preloadSafeframe_ = sfPreloadExpId == '21061135';
}
const viewer = Services.viewerForDoc(this.getAmpDoc());
viewer.onVisibilityChanged(() => {
if (viewer.getVisibilityState() != VisibilityState.PAUSED ||
this.useSra || !this.win.ampAdPageCorrelator) {
// Do not allow experiment selection if SRA or correlator was not set.
return;
}
// Select into correlator clear experiment of pause visibility change.
// Should execute prior to resumeCallback.
// TODO(keithwrightbos,glevitzy) - determine behavior for correlator
// interaction with refresh.
const experimentInfoMap =
/** @type {!Object<string,
!../../../src/experiments.ExperimentInfo>} */ ({});
experimentInfoMap[CORRELATOR_CLEAR_EXP_NAME] = {
isTrafficEligible: () => true,
branches: ['22302764','22302765'],
};
randomlySelectUnsetExperiments(this.win, experimentInfoMap);
const expId = getExperimentBranch(this.win, CORRELATOR_CLEAR_EXP_NAME);
if (expId) {
// Adding to experiment id will cause it to be included in subsequent ad
// requests.
addExperimentIdToElement(expId, this.element);
if (expId === CORRELATOR_CLEAR_EXP_BRANCHES.EXPERIMENT) {
// TODO(keithwrightbos) - do not clear if at least one slot on the page
// is an AMP creative that survived unlayoutCallback in order to
// ensure competitive exclusion/roadblocking. Note this only applies
// to non-backfill inventory.
dev().info(TAG, 'resetting page correlator');
this.win.ampAdPageCorrelator = null;
}
}
});
}
/** @override */
shouldPreferentialRenderWithoutCrypto() {
dev().assert(!isCdnProxy(this.win));
return !experimentFeatureEnabled(
this.win, DOUBLECLICK_UNCONDITIONED_EXPERIMENTS.CANONICAL_HLDBK_EXP,
UNCONDITIONED_CANONICAL_FF_HOLDBACK_EXP_NAME);
}
/** @override */
layoutCallback() {
this.binding_.layoutCallback();
return super.layoutCallback();
}
/**
* @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};
}
/** @return {!Object<string,string|boolean|number>} */
getPageParameters_() {
return {
'gdfp_req': '1',
'sfv': DEFAULT_SAFEFRAME_VERSION,
'u_sd': this.win.devicePixelRatio,
'gct': this.getLocationQueryParameterValue('google_preview') || null,
};
}
/**
* 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.initialSize);
dev().assert(this.jsonTargeting_);
let sizeStr = this.isFluid ?
'320x50' : `${this.initialSize.width}x${this.initialSize.height}`;
const tfcd = this.jsonTargeting_ && this.jsonTargeting_[TFCD];
const multiSizeDataStr = this.element.getAttribute('data-multi-size');
if (multiSizeDataStr) {
if (this.element.getAttribute('layout') == 'responsive') {
// TODO(levitzky) Define the behavior and remove this warning.
user().warn(TAG, 'Behavior of multi-size and responsive layout is ' +
'currently not well defined. Proceed with caution.');
}
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,
this.initialSize.width,
this.initialSize.height,
multiSizeValidation == 'true',
this.isFluid);
sizeStr += '|' + dimensions
.map(dimension => dimension.join('x'))
.join('|');
}
this.win['ampAdGoogleIfiCounter'] = this.win['ampAdGoogleIfiCounter'] || 1;
this.ifi_ = (this.isRefreshing && this.ifi_) ||
this.win['ampAdGoogleIfiCounter']++;
return Object.assign({
'iu': this.element.getAttribute('data-slot'),
'co': this.jsonTargeting_ &&
this.jsonTargeting_['cookieOptOut'] ? '1' : null,
'adk': this.adKey_,
'sz': sizeStr,
'output': 'html',
'impl': 'ifr',
'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),
'ifi': this.ifi_,
'rc': this.refreshCount_ || null,
'frc': Number(this.fromResumeCallback) || null,
'fluid': this.isFluid ? 'height' : null,
}, googleBlockParameters(this));
}
/**
* Populate's block-level state for ad URL construction.
* @visibileForTesting
*/
populateAdUrlState() {
// Allow for pub to override height/width via override attribute.
const width = Number(this.element.getAttribute('data-override-width')) ||
Number(this.element.getAttribute('width'));
const height = Number(this.element.getAttribute('data-override-height')) ||
Number(this.element.getAttribute('height'));
this.initialSize = this.isFluid ? {width: 0, height: 0} :
(width && height ?
// width/height could be 'auto' in which case we fallback to measured.
{width, height} : this.getIntersectionElementLayoutBox());
this.jsonTargeting_ =
tryParseJson(this.element.getAttribute('json')) || {};
this.adKey_ = this.generateAdKey_(
`${this.initialSize.width}x${this.initialSize.height}`);
}
/** @override */
getAdUrl(opt_rtcResponsesPromise) {
if (this.iframe && !this.isRefreshing) {
dev().warn(TAG, `Frame already exists, sra: ${this.useSra}`);
return '';
}
opt_rtcResponsesPromise = opt_rtcResponsesPromise || Promise.resolve();
// 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();
const identityPromise = Services.timerFor(this.win)
.timeoutPromise(1000, this.identityTokenPromise_)
.catch(() => {
// On error/timeout, proceed.
return /**@type {!../../../ads/google/a4a/utils.IdentityToken}*/({});
});
const urlPromise = Promise.all([opt_rtcResponsesPromise, identityPromise])
.then(results => {
const rtcParams = this.mergeRtcResponses_(results[0]);
this.identityToken = results[1];
return googleAdUrl(
this, DOUBLECLICK_BASE_URL, startTime, Object.assign(
this.getBlockParameters_(), rtcParams,
this.buildIdentityParams_(), this.getPageParameters_()));
});
this.troubleshootData_.adUrl = urlPromise;
return urlPromise;
}
/**
* @return {!Object<string,string>}
* @private
*/
buildIdentityParams_() {
return this.identityToken ? {
adsid: this.identityToken.token || null,
jar: this.identityToken.jar || null,
pucrd: this.identityToken.pucrd || null,
} : {};
}
/**
* Merges all of the rtcResponses into the JSON targeting and
* category exclusions.
* @param {?Array<!rtcResponseDef>} rtcResponseArray
* @private
*/
mergeRtcResponses_(rtcResponseArray) {
if (!rtcResponseArray) {
return null;
}
const artc = [];
const ati = [];
const ard = [];
let exclusions;
rtcResponseArray.forEach(rtcResponse => {
artc.push(rtcResponse.rtcTime);
ati.push(rtcResponse.error || RTC_SUCCESS);
ard.push(rtcResponse.callout);
if (rtcResponse.response) {
if (rtcResponse.response['targeting']) {
const rewrittenResponse = this.rewriteRtcKeys_(
rtcResponse.response['targeting'],
rtcResponse.callout);
this.jsonTargeting_['targeting'] =
!!this.jsonTargeting_['targeting'] ?
deepMerge(this.jsonTargeting_['targeting'],
rewrittenResponse) :
rewrittenResponse;
}
if (rtcResponse.response['categoryExclusions']) {
if (!exclusions) {
exclusions = {};
if (this.jsonTargeting_['categoryExclusions']) {
this.jsonTargeting_['categoryExclusions'].forEach(exclusion => {
exclusions[exclusion] = true;
});
}
}
rtcResponse.response['categoryExclusions'].forEach(exclusion => {
exclusions[exclusion] = true;
});
}
}
});
if (exclusions) {
this.jsonTargeting_['categoryExclusions'] = Object.keys(exclusions);
}
return {'artc': artc.join() || null, 'ati': ati.join(), 'ard': ard.join()};
}
/** @override */
getCustomRealTimeConfigMacros_() {
/**
* This whitelist allow attributes on the amp-ad element to be used as
* macros for constructing the RTC URL. Add attributes here, in lowercase,
* to make them available.
*/
const whitelist = {
'height': true,
'width': true,
'data-slot': true,
'data-multi-size': true,
'data-multi-size-validation': true,
'data-override-width': true,
'data-override-height': true,
};
return {
PAGEVIEWID: () => Services.documentInfoForDoc(this.element).pageViewId,
HREF: () => this.win.location.href,
TGT: () =>
JSON.stringify(
(tryParseJson(
this.element.getAttribute('json')) || {})['targeting']),
ADCID: opt_timeout => getOrCreateAdCid(
this.getAmpDoc(), 'AMP_ECID_GOOGLE', '_ga',
parseInt(opt_timeout, 10)),
ATTR: name => {
if (!whitelist[name.toLowerCase()]) {
dev().warn('TAG', `Invalid attribute ${name}`);
} else {
return this.element.getAttribute(name);
}
},
CANONICAL_URL: () =>
Services.documentInfoForDoc(this.element).canonicalUrl,
};
}
/**
* Appends the callout value to the keys of response to prevent a collision
* case caused by multiple vendors returning the same keys.
* @param {!Object<string, string>} response
* @param {string} callout
* @return {!Object<string, string>}
* @private
*/
rewriteRtcKeys_(response, callout) {
// Only perform this substitution for vendor-defined URLs.
if (!RTC_VENDORS[callout] || RTC_VENDORS[callout].disableKeyAppend) {
return response;
}
const newResponse = {};
Object.keys(response).forEach(key => {
newResponse[`${key}_${callout}`] = response[key];
});
return newResponse;
}