@ethicly/react-native 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -1
- package/README.md +246 -53
- package/lib/commonjs/core/adapters.js +44 -5
- package/lib/commonjs/core/cache.js +60 -5
- package/lib/commonjs/core/click.js +10 -0
- package/lib/commonjs/core/client.js +237 -73
- package/lib/commonjs/core/config.js +17 -2
- package/lib/commonjs/core/index.js +2 -1
- package/lib/commonjs/core/tracker.js +8 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
- package/lib/commonjs/react/useEthiclyInterstitial.js +4 -1
- package/lib/commonjs/version.js +1 -1
- package/lib/module/core/adapters.js +44 -5
- package/lib/module/core/cache.js +59 -4
- package/lib/module/core/click.js +9 -0
- package/lib/module/core/client.js +237 -73
- package/lib/module/core/config.js +15 -1
- package/lib/module/core/index.js +1 -1
- package/lib/module/core/tracker.js +9 -1
- package/lib/module/react/EthiclyInterstitial.js +45 -13
- package/lib/module/react/useEthiclyInterstitial.js +4 -1
- package/lib/module/version.js +1 -1
- package/lib/typescript/core/adapters.d.ts +2 -1
- package/lib/typescript/core/cache.d.ts +20 -2
- package/lib/typescript/core/click.d.ts +5 -0
- package/lib/typescript/core/client.d.ts +42 -3
- package/lib/typescript/core/config.d.ts +9 -0
- package/lib/typescript/core/index.d.ts +2 -2
- package/lib/typescript/core/types.d.ts +48 -0
- package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +4 -2
- package/lib/typescript/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/core/adapters.ts +33 -5
- package/src/core/cache.ts +48 -3
- package/src/core/click.ts +10 -0
- package/src/core/client.ts +278 -76
- package/src/core/config.ts +14 -1
- package/src/core/index.ts +4 -3
- package/src/core/tracker.ts +8 -1
- package/src/core/types.ts +57 -0
- package/src/react/EthiclyInterstitial.tsx +62 -16
- package/src/react/useEthiclyInterstitial.ts +8 -3
- package/src/version.ts +1 -1
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
// Pure TypeScript; every native capability comes in through an adapter.
|
|
3
3
|
import { createMemoryFileCache, createMemoryStorage, defaultAppState, isReleaseBuild, safeLogger, } from './adapters';
|
|
4
4
|
import { CreativeCache } from './cache';
|
|
5
|
-
import {
|
|
5
|
+
import { isWebUrl } from './click';
|
|
6
|
+
import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
|
|
6
7
|
import { httpRequest, RouteGate } from './http';
|
|
7
8
|
import { outboxFor, replayRecord } from './outbox';
|
|
8
9
|
import { InterstitialTracker } from './tracker';
|
|
9
10
|
import { SDK_VERSION } from '../version';
|
|
11
|
+
/** How long loadInterstitial() waits for a creative download by default. */
|
|
12
|
+
export const DEFAULT_LOAD_TIMEOUT_MS = 3000;
|
|
10
13
|
const CONFIG_TIMEOUT_MS = 5000;
|
|
11
14
|
const SERVE_TIMEOUT_MS = 8000;
|
|
12
15
|
const SIZE_PROBE_TIMEOUT_MS = 3000;
|
|
@@ -18,6 +21,26 @@ const DEFAULT_TTL_S = 3600;
|
|
|
18
21
|
*/
|
|
19
22
|
export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
20
23
|
let releaseTestModeLogged = false;
|
|
24
|
+
/** Same ceiling as the dashboard's gap between ads (24 hours). */
|
|
25
|
+
const MAX_MIN_GAP_S = 86400;
|
|
26
|
+
/**
|
|
27
|
+
* A frequency value from code: undefined when not a usable number, else >= 0.
|
|
28
|
+
* Infinity only where `allowInfinity`.
|
|
29
|
+
*/
|
|
30
|
+
function frequencyValue(v, name, allowInfinity, log) {
|
|
31
|
+
if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
|
|
32
|
+
log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
if (v < 0) {
|
|
36
|
+
log.warn(`frequency.${name} below 0: using 0`);
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
return v;
|
|
40
|
+
}
|
|
41
|
+
function audioPolicy(v) {
|
|
42
|
+
return v === 'on' || v === 'optional' || v === 'none' ? v : null;
|
|
43
|
+
}
|
|
21
44
|
export function createEthicly(options) {
|
|
22
45
|
return new EthiclyClient(options);
|
|
23
46
|
}
|
|
@@ -42,10 +65,16 @@ class EthiclyClient {
|
|
|
42
65
|
this.shownCount = 0;
|
|
43
66
|
this.lastShownAt = null;
|
|
44
67
|
this.frequencyLoaded = false;
|
|
68
|
+
/** Frequency set in code, null where /config decides. */
|
|
69
|
+
this.maxPerSessionOverride = null;
|
|
70
|
+
this.minGapSOverride = null;
|
|
45
71
|
/** When the app left the foreground, null while it is in it. */
|
|
46
72
|
this.backgroundSince = null;
|
|
47
73
|
this.preloaded = null;
|
|
48
74
|
this.serveInflight = null;
|
|
75
|
+
/** Served, creative still downloading, not yet taken. */
|
|
76
|
+
this.pendingServed = null;
|
|
77
|
+
this.badDestinationLogged = false;
|
|
49
78
|
this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
|
|
50
79
|
const f = o.fetch || globalThis.fetch;
|
|
51
80
|
if (!f)
|
|
@@ -59,6 +88,14 @@ class EthiclyClient {
|
|
|
59
88
|
this.cache = new CreativeCache(o.fileCache || createMemoryFileCache(), this.storage, 'ethicly:v1:cache', this.now, this.log, o.fileCache ? (url) => this.contentLength(url) : undefined);
|
|
60
89
|
this.config = defaultConfig(this.bundled);
|
|
61
90
|
this.adsOn = o.adsEnabled !== false;
|
|
91
|
+
this.audio = audioPolicy(o.audio);
|
|
92
|
+
if (o.audio !== undefined && !this.audio)
|
|
93
|
+
this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
|
|
94
|
+
this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
|
|
95
|
+
? o.loadTimeoutMs
|
|
96
|
+
: DEFAULT_LOAD_TIMEOUT_MS;
|
|
97
|
+
if (o.frequency)
|
|
98
|
+
this.setFrequency(o.frequency);
|
|
62
99
|
this.testMode = !!o.testMode && !isReleaseBuild();
|
|
63
100
|
if (o.testMode && !this.testMode)
|
|
64
101
|
this.reportReleaseTestMode();
|
|
@@ -285,15 +322,61 @@ class EthiclyClient {
|
|
|
285
322
|
this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
|
|
286
323
|
}
|
|
287
324
|
// ------------------------------------------------------------- frequency
|
|
288
|
-
|
|
325
|
+
getFrequency() {
|
|
326
|
+
var _a, _b;
|
|
289
327
|
const it = this.config.interstitial;
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
328
|
+
return {
|
|
329
|
+
maxPerSession: (_a = this.maxPerSessionOverride) !== null && _a !== void 0 ? _a : it.max_per_session,
|
|
330
|
+
minGapSeconds: (_b = this.minGapSOverride) !== null && _b !== void 0 ? _b : it.min_gap_s,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
setFrequency(update) {
|
|
334
|
+
if (!update || typeof update !== 'object')
|
|
335
|
+
return;
|
|
336
|
+
if (update.maxPerSession === null)
|
|
337
|
+
this.maxPerSessionOverride = null;
|
|
338
|
+
else if (update.maxPerSession !== undefined) {
|
|
339
|
+
const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
|
|
340
|
+
if (v !== undefined) {
|
|
341
|
+
const whole = Math.floor(v);
|
|
342
|
+
if (whole !== v)
|
|
343
|
+
this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
|
|
344
|
+
this.maxPerSessionOverride = whole;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (update.minGapSeconds === null)
|
|
348
|
+
this.minGapSOverride = null;
|
|
349
|
+
else if (update.minGapSeconds !== undefined) {
|
|
350
|
+
const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
|
|
351
|
+
if (v !== undefined) {
|
|
352
|
+
if (v > MAX_MIN_GAP_S)
|
|
353
|
+
this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
|
|
354
|
+
this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
nextAdStatus() {
|
|
359
|
+
const { maxPerSession, minGapSeconds } = this.getFrequency();
|
|
360
|
+
const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
|
|
361
|
+
const no = (reason, retryAt) => (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
|
|
362
|
+
if (!this.adsOn)
|
|
363
|
+
return no('ads_disabled');
|
|
364
|
+
if (!this.frequencyLoaded)
|
|
365
|
+
return no('not_ready');
|
|
366
|
+
const blocked = this.blockedReason();
|
|
367
|
+
if (blocked)
|
|
368
|
+
return no(blocked);
|
|
369
|
+
if (this.shownCount >= maxPerSession)
|
|
370
|
+
return no('session_cap');
|
|
371
|
+
if (this.lastShownAt !== null) {
|
|
372
|
+
const retryAt = this.lastShownAt + minGapSeconds * 1000;
|
|
373
|
+
if (this.now() < retryAt)
|
|
374
|
+
return no('frequency_capped', retryAt);
|
|
375
|
+
}
|
|
376
|
+
return { ...base, allowed: true };
|
|
377
|
+
}
|
|
378
|
+
canShow() {
|
|
379
|
+
return this.nextAdStatus().allowed;
|
|
297
380
|
}
|
|
298
381
|
onShown() {
|
|
299
382
|
this.shownCount += 1;
|
|
@@ -306,8 +389,12 @@ class EthiclyClient {
|
|
|
306
389
|
}
|
|
307
390
|
setAdsEnabled(enabled) {
|
|
308
391
|
this.adsOn = !!enabled;
|
|
309
|
-
if (
|
|
310
|
-
|
|
392
|
+
if (this.adsOn)
|
|
393
|
+
return;
|
|
394
|
+
this.preloaded = null;
|
|
395
|
+
this.pendingServed = null;
|
|
396
|
+
// A paid user downloads nothing: stop the creative download in flight.
|
|
397
|
+
this.cache.cancel();
|
|
311
398
|
}
|
|
312
399
|
isAdsEnabled() {
|
|
313
400
|
return this.adsOn;
|
|
@@ -331,6 +418,29 @@ class EthiclyClient {
|
|
|
331
418
|
this.log.info(`no ad: ${reason}`);
|
|
332
419
|
return { ad: null, tracker: null, reason };
|
|
333
420
|
}
|
|
421
|
+
/** The served ad waiting for its download, or a new serve. One serve at a time. */
|
|
422
|
+
serveOnce() {
|
|
423
|
+
const p = this.pendingServed;
|
|
424
|
+
if (p && !p.consumed && this.now() < p.expiresAt)
|
|
425
|
+
return Promise.resolve({ served: p });
|
|
426
|
+
this.pendingServed = null;
|
|
427
|
+
if (!this.serveInflight) {
|
|
428
|
+
this.serveInflight = this.serve()
|
|
429
|
+
.then((out) => {
|
|
430
|
+
if (out.served)
|
|
431
|
+
this.pendingServed = out.served;
|
|
432
|
+
return out;
|
|
433
|
+
})
|
|
434
|
+
.finally(() => { this.serveInflight = null; });
|
|
435
|
+
}
|
|
436
|
+
return this.serveInflight;
|
|
437
|
+
}
|
|
438
|
+
/** The ad and tracker of a served ad, built once, by whoever asks first. */
|
|
439
|
+
claim(s, uris) {
|
|
440
|
+
if (!s.result)
|
|
441
|
+
s.result = s.build(uris);
|
|
442
|
+
return s.result;
|
|
443
|
+
}
|
|
334
444
|
async preload() {
|
|
335
445
|
try {
|
|
336
446
|
if (!this.adsOn)
|
|
@@ -338,15 +448,23 @@ class EthiclyClient {
|
|
|
338
448
|
if (this.preloaded && !this.preloaded.result.tracker.isExpired())
|
|
339
449
|
return this.preloaded.result;
|
|
340
450
|
this.preloaded = null;
|
|
341
|
-
if (this.shownCount >= this.
|
|
451
|
+
if (this.shownCount >= this.getFrequency().maxPerSession)
|
|
342
452
|
return this.noFill('frequency_capped');
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
const
|
|
347
|
-
|
|
453
|
+
const out = await this.serveOnce();
|
|
454
|
+
if (!out.served)
|
|
455
|
+
return out.noFill;
|
|
456
|
+
const s = out.served;
|
|
457
|
+
// In the background: wait for the whole download, so the ad plays from disk.
|
|
458
|
+
const cached = await s.download;
|
|
459
|
+
if (!this.adsOn)
|
|
460
|
+
return this.noFill('ads_disabled');
|
|
461
|
+
const r = this.claim(s, cached.uris);
|
|
462
|
+
if (!s.consumed) {
|
|
348
463
|
this.preloaded = { result: r };
|
|
349
|
-
|
|
464
|
+
if (this.pendingServed === s)
|
|
465
|
+
this.pendingServed = null;
|
|
466
|
+
}
|
|
467
|
+
return r;
|
|
350
468
|
}
|
|
351
469
|
catch (e) {
|
|
352
470
|
this.log.error('preload failed', e);
|
|
@@ -354,6 +472,7 @@ class EthiclyClient {
|
|
|
354
472
|
}
|
|
355
473
|
}
|
|
356
474
|
async loadInterstitial() {
|
|
475
|
+
var _a;
|
|
357
476
|
try {
|
|
358
477
|
await this.ready;
|
|
359
478
|
if (!this.adsOn)
|
|
@@ -365,8 +484,28 @@ class EthiclyClient {
|
|
|
365
484
|
return this.noFill(blocked);
|
|
366
485
|
if (!this.canShow())
|
|
367
486
|
return this.noFill('frequency_capped');
|
|
368
|
-
const
|
|
487
|
+
const pre = this.preloaded;
|
|
369
488
|
this.preloaded = null;
|
|
489
|
+
if (pre && !pre.result.tracker.isExpired())
|
|
490
|
+
return pre.result;
|
|
491
|
+
const out = await this.serveOnce();
|
|
492
|
+
if (!out.served)
|
|
493
|
+
return out.noFill;
|
|
494
|
+
const s = out.served;
|
|
495
|
+
// The user is waiting: give the download a short budget, then stream the
|
|
496
|
+
// remote file. The download carries on in the background for next time.
|
|
497
|
+
const cached = await this.within(s.download, this.loadTimeoutMs);
|
|
498
|
+
if (!this.adsOn)
|
|
499
|
+
return this.noFill('ads_disabled');
|
|
500
|
+
if (!cached)
|
|
501
|
+
this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
|
|
502
|
+
const r = this.claim(s, cached ? cached.uris : {});
|
|
503
|
+
s.consumed = true;
|
|
504
|
+
if (this.pendingServed === s)
|
|
505
|
+
this.pendingServed = null;
|
|
506
|
+
// A preload that finished meanwhile may have stored this same ad.
|
|
507
|
+
if (((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result) === r)
|
|
508
|
+
this.preloaded = null;
|
|
370
509
|
return r;
|
|
371
510
|
}
|
|
372
511
|
catch (e) {
|
|
@@ -374,15 +513,24 @@ class EthiclyClient {
|
|
|
374
513
|
return this.noFill('network_error');
|
|
375
514
|
}
|
|
376
515
|
}
|
|
516
|
+
/** `p`, or null once `ms` have passed first. */
|
|
517
|
+
within(p, ms) {
|
|
518
|
+
let timer;
|
|
519
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
|
|
520
|
+
return Promise.race([p, timeout]).finally(() => { if (timer)
|
|
521
|
+
clearTimeout(timer); });
|
|
522
|
+
}
|
|
377
523
|
async serve() {
|
|
524
|
+
var _a, _b;
|
|
525
|
+
const noFill = (reason) => ({ noFill: this.noFill(reason) });
|
|
378
526
|
await this.ready;
|
|
379
527
|
if (this.configStale())
|
|
380
528
|
await this.refreshConfig();
|
|
381
529
|
const blocked = this.blockedReason();
|
|
382
530
|
if (blocked)
|
|
383
|
-
return
|
|
531
|
+
return noFill(blocked);
|
|
384
532
|
if (this.gate.waitMs('serve') > 0)
|
|
385
|
-
return
|
|
533
|
+
return noFill('rate_limited');
|
|
386
534
|
const q = [
|
|
387
535
|
`key=${encodeURIComponent(this.o.apiKey)}`,
|
|
388
536
|
'format=interstitial',
|
|
@@ -398,17 +546,17 @@ class EthiclyClient {
|
|
|
398
546
|
const servedAt = this.now();
|
|
399
547
|
if (res.status === 429) {
|
|
400
548
|
this.gate.block('serve', res.retryAfterS);
|
|
401
|
-
return
|
|
549
|
+
return noFill('rate_limited');
|
|
402
550
|
}
|
|
403
551
|
if (res.status === 400 || res.status === 403) {
|
|
404
552
|
this.invalidKey = true;
|
|
405
553
|
this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
|
|
406
|
-
return
|
|
554
|
+
return noFill('invalid_key');
|
|
407
555
|
}
|
|
408
556
|
if (res.status === 0)
|
|
409
|
-
return
|
|
557
|
+
return noFill('network_error');
|
|
410
558
|
if (res.status !== 200 || !res.body || typeof res.body !== 'object')
|
|
411
|
-
return
|
|
559
|
+
return noFill('server_error');
|
|
412
560
|
const body = res.body;
|
|
413
561
|
if (!body.ad) {
|
|
414
562
|
const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
|
|
@@ -416,70 +564,86 @@ class EthiclyClient {
|
|
|
416
564
|
this.appDisabled = true;
|
|
417
565
|
if (reason === 'sdk_unsupported')
|
|
418
566
|
this.sdkUnsupported = true;
|
|
419
|
-
return
|
|
567
|
+
return noFill(reason);
|
|
420
568
|
}
|
|
421
569
|
const ad = body.ad;
|
|
422
570
|
const m = ad.media;
|
|
423
571
|
if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
|
|
424
572
|
this.log.warn('serve answered an ad without media or destination', body.request_id);
|
|
425
|
-
return
|
|
573
|
+
return noFill('invalid_response');
|
|
574
|
+
}
|
|
575
|
+
if (!isWebUrl(ad.destination_url)) {
|
|
576
|
+
// Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
|
|
577
|
+
if (!this.badDestinationLogged) {
|
|
578
|
+
this.badDestinationLogged = true;
|
|
579
|
+
this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
|
|
580
|
+
}
|
|
581
|
+
return noFill('invalid_response');
|
|
426
582
|
}
|
|
427
583
|
if (body.test === true)
|
|
428
584
|
this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
|
|
429
585
|
if (!this.adsOn)
|
|
430
|
-
return
|
|
586
|
+
return noFill('ads_disabled');
|
|
431
587
|
const kind = m.kind === 'video' ? 'video' : 'image';
|
|
432
588
|
const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
|
|
433
589
|
const pf = this.config.prefetch;
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
return this.noFill('ads_disabled');
|
|
437
|
-
const uri = cached.uris[m.url] || m.url;
|
|
590
|
+
// Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
|
|
591
|
+
const download = this.cache.ensure(ad.id, poster ? [m.url, poster] : [m.url], { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 }, () => this.adsOn).catch(() => ({ uris: {} }));
|
|
438
592
|
const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
|
|
593
|
+
const expiresAt = servedAt + ttlS * 1000;
|
|
594
|
+
const adId = ad.id;
|
|
595
|
+
const mediaUrl = m.url;
|
|
596
|
+
const destinationUrl = ad.destination_url;
|
|
439
597
|
const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
|
|
440
598
|
const posInt = (v, d) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
599
|
+
// The ad's value wins over /config, kept within the same 8 to 15 s range.
|
|
600
|
+
const skipAfterMs = (_a = clampSkipAfterMs(ad.skip_after_ms)) !== null && _a !== void 0 ? _a : this.config.interstitial.skip_after_ms;
|
|
601
|
+
// The app's choice (options.audio) wins over the server's interstitial.audio.
|
|
602
|
+
const audio = (_b = this.audio) !== null && _b !== void 0 ? _b : this.config.interstitial.audio;
|
|
603
|
+
const build = (uris) => {
|
|
604
|
+
const uri = uris[mediaUrl] || mediaUrl;
|
|
605
|
+
const result = {
|
|
606
|
+
id: adId,
|
|
607
|
+
ctaLabel: label || 'Learn more',
|
|
608
|
+
destinationUrl,
|
|
609
|
+
skipAfterMs,
|
|
610
|
+
media: {
|
|
611
|
+
kind,
|
|
612
|
+
uri,
|
|
613
|
+
videoUri: kind === 'video' ? uri : null,
|
|
614
|
+
posterUri: poster ? uris[poster] || poster : null,
|
|
615
|
+
durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
|
|
616
|
+
mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
|
|
617
|
+
width: posInt(m.width, 720),
|
|
618
|
+
height: posInt(m.height, 1280),
|
|
619
|
+
cached: uri !== mediaUrl,
|
|
620
|
+
},
|
|
621
|
+
audio,
|
|
622
|
+
title: typeof ad.title === 'string' ? ad.title : null,
|
|
623
|
+
test: body.test === true,
|
|
624
|
+
servedAt,
|
|
625
|
+
expiresAt,
|
|
626
|
+
};
|
|
627
|
+
const tracker = new InterstitialTracker({
|
|
628
|
+
ctx: this.beaconCtx(),
|
|
629
|
+
ad: result,
|
|
630
|
+
serve: {
|
|
631
|
+
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
632
|
+
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
633
|
+
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
634
|
+
},
|
|
635
|
+
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
636
|
+
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
637
|
+
platform: this.o.platform,
|
|
638
|
+
sdkVersion: SDK_VERSION,
|
|
639
|
+
appVersion: this.o.appVersion,
|
|
640
|
+
openUrl: this.o.openUrl,
|
|
641
|
+
onShown: () => this.onShown(),
|
|
642
|
+
outbox: this.outbox,
|
|
643
|
+
});
|
|
644
|
+
return { ad: result, tracker };
|
|
464
645
|
};
|
|
465
|
-
const tracker = new InterstitialTracker({
|
|
466
|
-
ctx: this.beaconCtx(),
|
|
467
|
-
ad: result,
|
|
468
|
-
serve: {
|
|
469
|
-
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
470
|
-
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
471
|
-
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
472
|
-
},
|
|
473
|
-
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
474
|
-
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
475
|
-
platform: this.o.platform,
|
|
476
|
-
sdkVersion: SDK_VERSION,
|
|
477
|
-
appVersion: this.o.appVersion,
|
|
478
|
-
openUrl: this.o.openUrl,
|
|
479
|
-
onShown: () => this.onShown(),
|
|
480
|
-
outbox: this.outbox,
|
|
481
|
-
});
|
|
482
646
|
this.lastNoFillReason = null;
|
|
483
|
-
return {
|
|
647
|
+
return { served: { build, download, expiresAt, consumed: false, result: null } };
|
|
484
648
|
}
|
|
485
649
|
}
|
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
// "Versioning").
|
|
3
3
|
export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
|
|
4
4
|
export const DEFAULT_MAX_AGE_S = 300;
|
|
5
|
+
/**
|
|
6
|
+
* The skip delay is kept within these bounds, from /config and from the ad:
|
|
7
|
+
* the video is watched for at least 8 s before Skip appears (it still
|
|
8
|
+
* unlocks earlier when the video ends or after the call to action).
|
|
9
|
+
*/
|
|
10
|
+
export const MIN_SKIP_AFTER_MS = 8000;
|
|
11
|
+
export const MAX_SKIP_AFTER_MS = 15000;
|
|
12
|
+
/** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
|
|
13
|
+
export function clampSkipAfterMs(v) {
|
|
14
|
+
if (typeof v !== 'number' || !Number.isFinite(v))
|
|
15
|
+
return null;
|
|
16
|
+
return Math.min(MAX_SKIP_AFTER_MS, Math.max(MIN_SKIP_AFTER_MS, Math.round(v)));
|
|
17
|
+
}
|
|
5
18
|
/** The defaults shown in the doc. Used when no config was ever fetched. */
|
|
6
19
|
export function defaultConfig(serveBase) {
|
|
7
20
|
return {
|
|
@@ -36,6 +49,7 @@ export function cleanServeBase(v) {
|
|
|
36
49
|
* config at all.
|
|
37
50
|
*/
|
|
38
51
|
export function parseConfig(body, bundledBase) {
|
|
52
|
+
var _a;
|
|
39
53
|
const b = obj(body);
|
|
40
54
|
if (typeof b.enabled !== 'boolean')
|
|
41
55
|
return null;
|
|
@@ -52,7 +66,7 @@ export function parseConfig(body, bundledBase) {
|
|
|
52
66
|
min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
|
|
53
67
|
formats: Array.isArray(b.formats) ? b.formats.filter((f) => typeof f === 'string') : d.formats,
|
|
54
68
|
interstitial: {
|
|
55
|
-
skip_after_ms:
|
|
69
|
+
skip_after_ms: (_a = clampSkipAfterMs(it.skip_after_ms)) !== null && _a !== void 0 ? _a : d.interstitial.skip_after_ms,
|
|
56
70
|
max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
|
|
57
71
|
min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
|
|
58
72
|
audio,
|
package/lib/module/core/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
|
|
2
|
-
export { createEthicly, SESSION_TIMEOUT_MS } from './client';
|
|
2
|
+
export { createEthicly, DEFAULT_LOAD_TIMEOUT_MS, SESSION_TIMEOUT_MS } from './client';
|
|
3
3
|
export { createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4, } from './adapters';
|
|
4
4
|
export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
|
|
5
5
|
export { compareVersions, BUNDLED_BASE_URL } from './config';
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// "Lifecycle and timing" steps 4 to 8 and "Click handling". Every public
|
|
3
3
|
// method swallows its errors and reports them through the logger.
|
|
4
4
|
import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry } from './beacons';
|
|
5
|
-
import { appendClickToken, CLICK_TIMEOUT_MS } from './click';
|
|
5
|
+
import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
|
|
6
6
|
import { asImpressionId, httpRequest } from './http';
|
|
7
7
|
import { uuidv4 } from './adapters';
|
|
8
8
|
/** Doc "Still-image interstitials": /viewable after 1000 ms on screen. */
|
|
@@ -308,6 +308,11 @@ export class InterstitialTracker {
|
|
|
308
308
|
if (!this.clickUrl)
|
|
309
309
|
this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
|
|
310
310
|
return this.clickUrl.then(async (url) => {
|
|
311
|
+
// The client already refuses such an ad; this guards a hand-built EthiclyAd.
|
|
312
|
+
if (!isWebUrl(url)) {
|
|
313
|
+
this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
|
|
314
|
+
return url;
|
|
315
|
+
}
|
|
311
316
|
try {
|
|
312
317
|
if (this.d.openUrl)
|
|
313
318
|
await this.d.openUrl(url);
|
|
@@ -344,6 +349,9 @@ export class InterstitialTracker {
|
|
|
344
349
|
body.publisher_site_id = serve.publisherSiteId;
|
|
345
350
|
if (serve.countryCode)
|
|
346
351
|
body.country_code = serve.countryCode;
|
|
352
|
+
// Proof the view was served: lets the server bill a tap made before /viewable.
|
|
353
|
+
if (imp.viewableToken)
|
|
354
|
+
body.viewable_token = imp.viewableToken;
|
|
347
355
|
// Never retried: one request, whatever happens.
|
|
348
356
|
const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
|
|
349
357
|
method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
|
|
@@ -3,12 +3,20 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
|
|
|
3
3
|
// Layout follows a typical in-app video player: 9:16 video, a skip control that counts
|
|
4
4
|
// down then reads "Skip Ad", a white call-to-action button, an optional
|
|
5
5
|
// "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
|
|
6
|
-
// Video starts with sound unless
|
|
6
|
+
// Video starts with sound unless the effective audio (the `audio` prop, else
|
|
7
|
+
// ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
|
|
7
8
|
// The controls keep clear of the notch, status bar and home indicator: see
|
|
8
9
|
// useSafeInsets below.
|
|
9
10
|
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
|
|
10
11
|
import { AppState, BackHandler, Image, Modal, Platform, Pressable, StatusBar, StyleSheet, Text, View, } from 'react-native';
|
|
11
12
|
import { useVideoPlayer, VideoView } from 'expo-video';
|
|
13
|
+
/** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
|
|
14
|
+
export function effectiveAudio(prop, ad) {
|
|
15
|
+
for (const v of [prop, ad.audio])
|
|
16
|
+
if (v === 'on' || v === 'optional' || v === 'none')
|
|
17
|
+
return v;
|
|
18
|
+
return 'on';
|
|
19
|
+
}
|
|
12
20
|
const TICK_MS = 250;
|
|
13
21
|
/** Space between the safe area and the controls. */
|
|
14
22
|
const TOP_GAP = 12;
|
|
@@ -88,7 +96,8 @@ function useAppActive() {
|
|
|
88
96
|
}, []);
|
|
89
97
|
return active;
|
|
90
98
|
}
|
|
91
|
-
function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, }) {
|
|
99
|
+
function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
|
|
100
|
+
const audio = effectiveAudio(audioProp, ad);
|
|
92
101
|
const safe = useSafeInsets(insets);
|
|
93
102
|
const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
|
|
94
103
|
const appActive = useAppActive();
|
|
@@ -97,15 +106,21 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
97
106
|
const [positionMs, setPositionMs] = useState(0);
|
|
98
107
|
const [ended, setEnded] = useState(false);
|
|
99
108
|
const [failed, setFailed] = useState(false);
|
|
100
|
-
const [muted, setMuted] = useState(
|
|
109
|
+
const [muted, setMuted] = useState(audio !== 'on');
|
|
110
|
+
/**
|
|
111
|
+
* A still image counts as visible only once it has loaded: an image that
|
|
112
|
+
* never arrives is never billed as viewable.
|
|
113
|
+
*/
|
|
114
|
+
const imageLoadedRef = useRef(false);
|
|
101
115
|
/** Wall-clock time on screen with the app in the foreground. */
|
|
102
116
|
const [onScreenMs, setOnScreenMs] = useState(0);
|
|
103
117
|
const [clicked, setClicked] = useState(false);
|
|
104
118
|
const positionRef = useRef(0);
|
|
105
119
|
const closedRef = useRef(false);
|
|
120
|
+
const failedRef = useRef(false);
|
|
106
121
|
const player = useVideoPlayer(isVideo ? ad.media.videoUri : null, (p) => {
|
|
107
122
|
p.loop = false;
|
|
108
|
-
p.muted =
|
|
123
|
+
p.muted = audio !== 'on';
|
|
109
124
|
p.timeUpdateEventInterval = TICK_MS / 1000;
|
|
110
125
|
p.play();
|
|
111
126
|
});
|
|
@@ -140,7 +155,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
140
155
|
tracker.complete();
|
|
141
156
|
}),
|
|
142
157
|
player.addListener('statusChange', ({ status }) => {
|
|
143
|
-
if (status === 'error') {
|
|
158
|
+
if (status === 'error' && !failedRef.current) {
|
|
159
|
+
failedRef.current = true;
|
|
144
160
|
setFailed(true);
|
|
145
161
|
tracker.error();
|
|
146
162
|
}
|
|
@@ -148,23 +164,36 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
148
164
|
];
|
|
149
165
|
return () => subs.forEach((s) => s.remove());
|
|
150
166
|
}, [isVideo, player, tracker]);
|
|
151
|
-
// Time on screen while the app is in the foreground
|
|
152
|
-
//
|
|
153
|
-
//
|
|
167
|
+
// Time on screen while the app is in the foreground: the skip countdown, so
|
|
168
|
+
// Skip appears after skipAfterMs even if the video stalls or the image never
|
|
169
|
+
// loads. For a still image, the time since it loaded is the playback position.
|
|
154
170
|
useEffect(() => {
|
|
155
171
|
let shownMs = 0;
|
|
172
|
+
let loadedMs = 0;
|
|
156
173
|
const id = setInterval(() => {
|
|
157
174
|
if (activeRef.current)
|
|
158
175
|
shownMs += TICK_MS;
|
|
159
176
|
setOnScreenMs(shownMs);
|
|
160
|
-
if (isVideo)
|
|
177
|
+
if (isVideo || !imageLoadedRef.current || failedRef.current)
|
|
161
178
|
return;
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
179
|
+
if (activeRef.current)
|
|
180
|
+
loadedMs += TICK_MS;
|
|
181
|
+
positionRef.current = loadedMs;
|
|
182
|
+
setPositionMs(loadedMs);
|
|
183
|
+
tracker.progress(loadedMs, { visible: activeRef.current });
|
|
165
184
|
}, TICK_MS);
|
|
166
185
|
return () => clearInterval(id);
|
|
167
186
|
}, [isVideo, tracker]);
|
|
187
|
+
const onImageLoad = useCallback(() => {
|
|
188
|
+
imageLoadedRef.current = true;
|
|
189
|
+
}, []);
|
|
190
|
+
const onImageError = useCallback(() => {
|
|
191
|
+
if (failedRef.current)
|
|
192
|
+
return;
|
|
193
|
+
failedRef.current = true;
|
|
194
|
+
setFailed(true);
|
|
195
|
+
tracker.error();
|
|
196
|
+
}, [tracker]);
|
|
168
197
|
useEffect(() => {
|
|
169
198
|
if (!isVideo)
|
|
170
199
|
return;
|
|
@@ -178,6 +207,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
178
207
|
useEffect(() => {
|
|
179
208
|
if (appActive)
|
|
180
209
|
return;
|
|
210
|
+
if (!isVideo && (!imageLoadedRef.current || failedRef.current))
|
|
211
|
+
return;
|
|
181
212
|
const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
|
|
182
213
|
tracker.progress(positionRef.current, { visible: false, durationMs });
|
|
183
214
|
}, [appActive, isVideo, player, tracker]);
|
|
@@ -210,7 +241,7 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
210
241
|
const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
|
|
211
242
|
const canSkip = remainingS === 0 || ended || failed || clicked;
|
|
212
243
|
backRef.current = canSkip ? close : null;
|
|
213
|
-
return (_jsxs(View, { style: styles.root, children: [isVideo ? (_jsxs(_Fragment, { children: [ad.media.posterUri ? _jsx(Image, { source: { uri: ad.media.posterUri }, style: StyleSheet.absoluteFill, resizeMode: "cover" }) : null, _jsx(VideoView, { player: player, style: StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false,
|
|
244
|
+
return (_jsxs(View, { style: styles.root, children: [isVideo ? (_jsxs(_Fragment, { children: [ad.media.posterUri ? _jsx(Image, { source: { uri: ad.media.posterUri }, style: StyleSheet.absoluteFill, resizeMode: "cover" }) : null, _jsx(VideoView, { player: player, style: StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsPictureInPicture: false })] })) : (_jsx(Image, { source: { uri: ad.media.uri }, style: StyleSheet.absoluteFill, resizeMode: "cover", onLoad: onImageLoad, onError: onImageError })), _jsxs(View, { style: [styles.topRow, { top: Math.max(safe.top + TOP_GAP, MIN_TOP), left: safe.left + SIDE_GAP_TOP, right: safe.right + SIDE_GAP_TOP }], pointerEvents: "box-none", children: [_jsxs(View, { style: styles.leftGroup, children: [_jsx(Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), ad.test ? _jsx(Text, { style: [styles.adLabel, styles.testLabel], accessibilityRole: "text", children: "Test ad" }) : null, isVideo && audio !== 'none' ? (_jsx(Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: _jsx(Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), _jsx(Pressable, { onPress: canSkip ? close : undefined, disabled: !canSkip, style: [styles.skip, skipStyle], accessibilityRole: "button", accessibilityLabel: canSkip ? 'Skip ad' : `Skip in ${remainingS} seconds`, hitSlop: 8, children: canSkip ? (_jsxs(View, { style: styles.skipRow, children: [_jsx(Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), _jsx(SkipIcon, {})] })) : (_jsx(Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), _jsxs(View, { style: [styles.bottom, {
|
|
214
245
|
bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
|
|
215
246
|
}], pointerEvents: "box-none", children: [_jsx(Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: _jsx(Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? (_jsx(Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: _jsx(Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, _jsx(Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" })] })] }));
|
|
216
247
|
}
|
|
@@ -229,6 +260,7 @@ const styles = StyleSheet.create({
|
|
|
229
260
|
color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
|
|
230
261
|
backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
|
|
231
262
|
},
|
|
263
|
+
testLabel: { marginLeft: 8, backgroundColor: 'rgba(196,120,0,0.85)' },
|
|
232
264
|
soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
|
|
233
265
|
soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
|
|
234
266
|
// Solid black, no blur or translucency. The faint hairline keeps the edge
|