@ethicly/react-native 0.2.0 → 0.2.1
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 +59 -1
- package/README.md +168 -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 +160 -64
- package/lib/commonjs/core/config.js +17 -2
- package/lib/commonjs/core/index.js +2 -1
- package/lib/commonjs/core/tracker.js +5 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
- 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 +160 -64
- package/lib/module/core/config.js +15 -1
- package/lib/module/core/index.js +1 -1
- package/lib/module/core/tracker.js +6 -1
- package/lib/module/react/EthiclyInterstitial.js +45 -13
- 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 +23 -3
- package/lib/typescript/core/config.d.ts +9 -0
- package/lib/typescript/core/index.d.ts +1 -1
- package/lib/typescript/core/types.d.ts +5 -0
- package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +1 -1
- 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 +186 -68
- package/src/core/config.ts +14 -1
- package/src/core/index.ts +1 -1
- package/src/core/tracker.ts +6 -1
- package/src/core/types.ts +5 -0
- package/src/react/EthiclyInterstitial.tsx +62 -16
- package/src/react/useEthiclyInterstitial.ts +1 -1
- package/src/version.ts +1 -1
package/src/core/client.ts
CHANGED
|
@@ -5,14 +5,15 @@ import {
|
|
|
5
5
|
createMemoryFileCache, createMemoryStorage, defaultAppState, isReleaseBuild, safeLogger, type AppStateLike,
|
|
6
6
|
} from './adapters';
|
|
7
7
|
import type { BeaconContext } from './beacons';
|
|
8
|
-
import { CreativeCache } from './cache';
|
|
9
|
-
import {
|
|
8
|
+
import { CreativeCache, type CachedMedia } from './cache';
|
|
9
|
+
import { isWebUrl } from './click';
|
|
10
|
+
import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
|
|
10
11
|
import { httpRequest, RouteGate } from './http';
|
|
11
12
|
import { outboxFor, replayRecord, type Outbox } from './outbox';
|
|
12
13
|
import { InterstitialTracker } from './tracker';
|
|
13
14
|
import { SDK_VERSION } from '../version';
|
|
14
15
|
import type {
|
|
15
|
-
EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
|
|
16
|
+
AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
|
|
16
17
|
Logger, NoFillReason, Platform, WireServe,
|
|
17
18
|
} from './types';
|
|
18
19
|
|
|
@@ -30,8 +31,26 @@ export interface EthiclyOptions {
|
|
|
30
31
|
* (`__DEV__` false), where the SDK serves and bills normally and logs an error.
|
|
31
32
|
*/
|
|
32
33
|
testMode?: boolean;
|
|
33
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Initial state of the ads switch, default true. Apps with a paid tier: pass
|
|
36
|
+
* false until you know the user's entitlement, then setAdsEnabled(true) for
|
|
37
|
+
* free users, so a subscriber never serves or downloads an ad.
|
|
38
|
+
*/
|
|
34
39
|
adsEnabled?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Sound for every ad, over the server's interstitial.audio: 'on' plays with
|
|
42
|
+
* sound, 'optional' starts muted with a sound toggle, 'none' plays muted with
|
|
43
|
+
* no toggle. Unset: the server's value, which defaults to 'on'. `ad.audio`
|
|
44
|
+
* is the effective value. EthiclyInterstitial's `audio` prop overrides it per screen.
|
|
45
|
+
*/
|
|
46
|
+
audio?: AudioPolicy;
|
|
47
|
+
/**
|
|
48
|
+
* The longest loadInterstitial() waits for the creative download when no
|
|
49
|
+
* preloaded ad is ready, in ms. Default 3000 (DEFAULT_LOAD_TIMEOUT_MS). After
|
|
50
|
+
* it the ad comes back with the remote URL, so the player streams, and the
|
|
51
|
+
* download carries on in the background for next time.
|
|
52
|
+
*/
|
|
53
|
+
loadTimeoutMs?: number;
|
|
35
54
|
storage?: KeyValueStorage;
|
|
36
55
|
fileCache?: FileCacheAdapter;
|
|
37
56
|
openUrl?: (url: string) => unknown;
|
|
@@ -57,7 +76,7 @@ export interface Ethicly {
|
|
|
57
76
|
* false until the stored frequency state has loaded (see `ready`).
|
|
58
77
|
*/
|
|
59
78
|
canShow(): boolean;
|
|
60
|
-
/** false for paid users: stops serves and
|
|
79
|
+
/** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
|
|
61
80
|
setAdsEnabled(enabled: boolean): void;
|
|
62
81
|
isAdsEnabled(): boolean;
|
|
63
82
|
getConfig(): EthiclyConfig;
|
|
@@ -68,6 +87,8 @@ export interface Ethicly {
|
|
|
68
87
|
readonly sdkVersion: string;
|
|
69
88
|
}
|
|
70
89
|
|
|
90
|
+
/** How long loadInterstitial() waits for a creative download by default. */
|
|
91
|
+
export const DEFAULT_LOAD_TIMEOUT_MS = 3000;
|
|
71
92
|
const CONFIG_TIMEOUT_MS = 5000;
|
|
72
93
|
const SERVE_TIMEOUT_MS = 8000;
|
|
73
94
|
const SIZE_PROBE_TIMEOUT_MS = 3000;
|
|
@@ -86,6 +107,22 @@ interface StoredFrequency { lastShownAt: number }
|
|
|
86
107
|
|
|
87
108
|
interface Preloaded { result: { ad: EthiclyAd; tracker: InterstitialTracker } }
|
|
88
109
|
|
|
110
|
+
/** A served ad whose creative is downloading. Built into an ad once, by preload() or loadInterstitial(). */
|
|
111
|
+
interface Served {
|
|
112
|
+
download: Promise<CachedMedia>;
|
|
113
|
+
build(uris: Record<string, string>): Preloaded['result'];
|
|
114
|
+
expiresAt: number;
|
|
115
|
+
/** Taken by loadInterstitial(): never stored as the preloaded ad. */
|
|
116
|
+
consumed: boolean;
|
|
117
|
+
result: Preloaded['result'] | null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
|
|
121
|
+
|
|
122
|
+
function audioPolicy(v: unknown): AudioPolicy | null {
|
|
123
|
+
return v === 'on' || v === 'optional' || v === 'none' ? v : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
89
126
|
export function createEthicly(options: EthiclyOptions): Ethicly {
|
|
90
127
|
return new EthiclyClient(options);
|
|
91
128
|
}
|
|
@@ -127,7 +164,12 @@ class EthiclyClient implements Ethicly {
|
|
|
127
164
|
private backgroundSince: number | null = null;
|
|
128
165
|
private outbox: Outbox;
|
|
129
166
|
private preloaded: Preloaded | null = null;
|
|
130
|
-
private serveInflight: Promise<
|
|
167
|
+
private serveInflight: Promise<ServeOutcome> | null = null;
|
|
168
|
+
/** Served, creative still downloading, not yet taken. */
|
|
169
|
+
private pendingServed: Served | null = null;
|
|
170
|
+
private loadTimeoutMs: number;
|
|
171
|
+
private audio: AudioPolicy | null;
|
|
172
|
+
private badDestinationLogged = false;
|
|
131
173
|
|
|
132
174
|
constructor(private o: EthiclyOptions) {
|
|
133
175
|
this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
|
|
@@ -145,6 +187,11 @@ class EthiclyClient implements Ethicly {
|
|
|
145
187
|
);
|
|
146
188
|
this.config = defaultConfig(this.bundled);
|
|
147
189
|
this.adsOn = o.adsEnabled !== false;
|
|
190
|
+
this.audio = audioPolicy(o.audio);
|
|
191
|
+
if (o.audio !== undefined && !this.audio) this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
|
|
192
|
+
this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
|
|
193
|
+
? o.loadTimeoutMs
|
|
194
|
+
: DEFAULT_LOAD_TIMEOUT_MS;
|
|
148
195
|
this.testMode = !!o.testMode && !isReleaseBuild();
|
|
149
196
|
if (o.testMode && !this.testMode) this.reportReleaseTestMode();
|
|
150
197
|
if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
|
|
@@ -379,7 +426,11 @@ class EthiclyClient implements Ethicly {
|
|
|
379
426
|
|
|
380
427
|
setAdsEnabled(enabled: boolean): void {
|
|
381
428
|
this.adsOn = !!enabled;
|
|
382
|
-
if (
|
|
429
|
+
if (this.adsOn) return;
|
|
430
|
+
this.preloaded = null;
|
|
431
|
+
this.pendingServed = null;
|
|
432
|
+
// A paid user downloads nothing: stop the creative download in flight.
|
|
433
|
+
this.cache.cancel();
|
|
383
434
|
}
|
|
384
435
|
|
|
385
436
|
isAdsEnabled(): boolean {
|
|
@@ -403,18 +454,46 @@ class EthiclyClient implements Ethicly {
|
|
|
403
454
|
return { ad: null, tracker: null, reason };
|
|
404
455
|
}
|
|
405
456
|
|
|
457
|
+
/** The served ad waiting for its download, or a new serve. One serve at a time. */
|
|
458
|
+
private serveOnce(): Promise<ServeOutcome> {
|
|
459
|
+
const p = this.pendingServed;
|
|
460
|
+
if (p && !p.consumed && this.now() < p.expiresAt) return Promise.resolve({ served: p });
|
|
461
|
+
this.pendingServed = null;
|
|
462
|
+
if (!this.serveInflight) {
|
|
463
|
+
this.serveInflight = this.serve()
|
|
464
|
+
.then((out) => {
|
|
465
|
+
if (out.served) this.pendingServed = out.served;
|
|
466
|
+
return out;
|
|
467
|
+
})
|
|
468
|
+
.finally(() => { this.serveInflight = null; });
|
|
469
|
+
}
|
|
470
|
+
return this.serveInflight;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** The ad and tracker of a served ad, built once, by whoever asks first. */
|
|
474
|
+
private claim(s: Served, uris: Record<string, string>): Preloaded['result'] {
|
|
475
|
+
if (!s.result) s.result = s.build(uris);
|
|
476
|
+
return s.result;
|
|
477
|
+
}
|
|
478
|
+
|
|
406
479
|
async preload(): Promise<InterstitialResult> {
|
|
407
480
|
try {
|
|
408
481
|
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
409
482
|
if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
|
|
410
483
|
this.preloaded = null;
|
|
411
484
|
if (this.shownCount >= this.config.interstitial.max_per_session) return this.noFill('frequency_capped');
|
|
412
|
-
|
|
413
|
-
|
|
485
|
+
const out = await this.serveOnce();
|
|
486
|
+
if (!out.served) return out.noFill;
|
|
487
|
+
const s = out.served;
|
|
488
|
+
// In the background: wait for the whole download, so the ad plays from disk.
|
|
489
|
+
const cached = await s.download;
|
|
490
|
+
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
491
|
+
const r = this.claim(s, cached.uris);
|
|
492
|
+
if (!s.consumed) {
|
|
493
|
+
this.preloaded = { result: r };
|
|
494
|
+
if (this.pendingServed === s) this.pendingServed = null;
|
|
414
495
|
}
|
|
415
|
-
|
|
416
|
-
if (r.ad && this.adsOn) this.preloaded = { result: r as Preloaded['result'] };
|
|
417
|
-
return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
|
|
496
|
+
return r;
|
|
418
497
|
} catch (e) {
|
|
419
498
|
this.log.error('preload failed', e);
|
|
420
499
|
return this.noFill('network_error');
|
|
@@ -429,8 +508,23 @@ class EthiclyClient implements Ethicly {
|
|
|
429
508
|
const blocked = this.blockedReason();
|
|
430
509
|
if (blocked) return this.noFill(blocked);
|
|
431
510
|
if (!this.canShow()) return this.noFill('frequency_capped');
|
|
432
|
-
const
|
|
511
|
+
const pre = this.preloaded;
|
|
433
512
|
this.preloaded = null;
|
|
513
|
+
if (pre && !pre.result.tracker.isExpired()) return pre.result;
|
|
514
|
+
|
|
515
|
+
const out = await this.serveOnce();
|
|
516
|
+
if (!out.served) return out.noFill;
|
|
517
|
+
const s = out.served;
|
|
518
|
+
// The user is waiting: give the download a short budget, then stream the
|
|
519
|
+
// remote file. The download carries on in the background for next time.
|
|
520
|
+
const cached = await this.within(s.download, this.loadTimeoutMs);
|
|
521
|
+
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
522
|
+
if (!cached) this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
|
|
523
|
+
const r = this.claim(s, cached ? cached.uris : {});
|
|
524
|
+
s.consumed = true;
|
|
525
|
+
if (this.pendingServed === s) this.pendingServed = null;
|
|
526
|
+
// A preload that finished meanwhile may have stored this same ad.
|
|
527
|
+
if ((this.preloaded as Preloaded | null)?.result === r) this.preloaded = null;
|
|
434
528
|
return r;
|
|
435
529
|
} catch (e) {
|
|
436
530
|
this.log.error('loadInterstitial failed', e);
|
|
@@ -438,12 +532,20 @@ class EthiclyClient implements Ethicly {
|
|
|
438
532
|
}
|
|
439
533
|
}
|
|
440
534
|
|
|
441
|
-
|
|
535
|
+
/** `p`, or null once `ms` have passed first. */
|
|
536
|
+
private within<T>(p: Promise<T>, ms: number): Promise<T | null> {
|
|
537
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
538
|
+
const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), ms); });
|
|
539
|
+
return Promise.race([p, timeout]).finally(() => { if (timer) clearTimeout(timer); });
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private async serve(): Promise<ServeOutcome> {
|
|
543
|
+
const noFill = (reason: NoFillReason): ServeOutcome => ({ noFill: this.noFill(reason) });
|
|
442
544
|
await this.ready;
|
|
443
545
|
if (this.configStale()) await this.refreshConfig();
|
|
444
546
|
const blocked = this.blockedReason();
|
|
445
|
-
if (blocked) return
|
|
446
|
-
if (this.gate.waitMs('serve') > 0) return
|
|
547
|
+
if (blocked) return noFill(blocked);
|
|
548
|
+
if (this.gate.waitMs('serve') > 0) return noFill('rate_limited');
|
|
447
549
|
|
|
448
550
|
const q = [
|
|
449
551
|
`key=${encodeURIComponent(this.o.apiKey)}`,
|
|
@@ -459,89 +561,105 @@ class EthiclyClient implements Ethicly {
|
|
|
459
561
|
const servedAt = this.now();
|
|
460
562
|
if (res.status === 429) {
|
|
461
563
|
this.gate.block('serve', res.retryAfterS);
|
|
462
|
-
return
|
|
564
|
+
return noFill('rate_limited');
|
|
463
565
|
}
|
|
464
566
|
if (res.status === 400 || res.status === 403) {
|
|
465
567
|
this.invalidKey = true;
|
|
466
568
|
this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
|
|
467
|
-
return
|
|
569
|
+
return noFill('invalid_key');
|
|
468
570
|
}
|
|
469
|
-
if (res.status === 0) return
|
|
470
|
-
if (res.status !== 200 || !res.body || typeof res.body !== 'object') return
|
|
571
|
+
if (res.status === 0) return noFill('network_error');
|
|
572
|
+
if (res.status !== 200 || !res.body || typeof res.body !== 'object') return noFill('server_error');
|
|
471
573
|
|
|
472
574
|
const body = res.body as WireServe;
|
|
473
575
|
if (!body.ad) {
|
|
474
576
|
const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
|
|
475
577
|
if (reason === 'app_disabled') this.appDisabled = true;
|
|
476
578
|
if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
|
|
477
|
-
return
|
|
579
|
+
return noFill(reason);
|
|
478
580
|
}
|
|
479
581
|
const ad = body.ad;
|
|
480
582
|
const m = ad.media;
|
|
481
583
|
if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
|
|
482
584
|
this.log.warn('serve answered an ad without media or destination', body.request_id);
|
|
483
|
-
return
|
|
585
|
+
return noFill('invalid_response');
|
|
586
|
+
}
|
|
587
|
+
if (!isWebUrl(ad.destination_url)) {
|
|
588
|
+
// Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
|
|
589
|
+
if (!this.badDestinationLogged) {
|
|
590
|
+
this.badDestinationLogged = true;
|
|
591
|
+
this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
|
|
592
|
+
}
|
|
593
|
+
return noFill('invalid_response');
|
|
484
594
|
}
|
|
485
595
|
if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
|
|
486
|
-
if (!this.adsOn) return
|
|
596
|
+
if (!this.adsOn) return noFill('ads_disabled');
|
|
487
597
|
|
|
488
598
|
const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
|
|
489
599
|
const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
|
|
490
600
|
const pf = this.config.prefetch;
|
|
491
|
-
|
|
601
|
+
// Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
|
|
602
|
+
const download = this.cache.ensure(
|
|
492
603
|
ad.id,
|
|
493
604
|
poster ? [m.url, poster] : [m.url],
|
|
494
605
|
{ maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
|
|
495
606
|
() => this.adsOn,
|
|
496
607
|
).catch(() => ({ uris: {} as Record<string, string> }));
|
|
497
|
-
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
498
|
-
|
|
499
|
-
const uri = cached.uris[m.url] || m.url;
|
|
500
608
|
const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
|
|
609
|
+
const expiresAt = servedAt + ttlS * 1000;
|
|
610
|
+
const adId = ad.id;
|
|
611
|
+
const mediaUrl = m.url;
|
|
612
|
+
const destinationUrl = ad.destination_url;
|
|
501
613
|
const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
|
|
502
614
|
const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
615
|
+
// The ad's value wins over /config, kept within the same 8 to 15 s range.
|
|
616
|
+
const skipAfterMs = clampSkipAfterMs(ad.skip_after_ms) ?? this.config.interstitial.skip_after_ms;
|
|
617
|
+
// The app's choice (options.audio) wins over the server's interstitial.audio.
|
|
618
|
+
const audio: AudioPolicy = this.audio ?? this.config.interstitial.audio;
|
|
619
|
+
const build = (uris: Record<string, string>): Preloaded['result'] => {
|
|
620
|
+
const uri = uris[mediaUrl] || mediaUrl;
|
|
621
|
+
const result: EthiclyAd = {
|
|
622
|
+
id: adId,
|
|
623
|
+
ctaLabel: label || 'Learn more',
|
|
624
|
+
destinationUrl,
|
|
625
|
+
skipAfterMs,
|
|
626
|
+
media: {
|
|
627
|
+
kind,
|
|
628
|
+
uri,
|
|
629
|
+
videoUri: kind === 'video' ? uri : null,
|
|
630
|
+
posterUri: poster ? uris[poster] || poster : null,
|
|
631
|
+
durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
|
|
632
|
+
mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
|
|
633
|
+
width: posInt(m.width, 720),
|
|
634
|
+
height: posInt(m.height, 1280),
|
|
635
|
+
cached: uri !== mediaUrl,
|
|
636
|
+
},
|
|
637
|
+
audio,
|
|
638
|
+
title: typeof ad.title === 'string' ? ad.title : null,
|
|
639
|
+
test: body.test === true,
|
|
640
|
+
servedAt,
|
|
641
|
+
expiresAt,
|
|
642
|
+
};
|
|
643
|
+
const tracker = new InterstitialTracker({
|
|
644
|
+
ctx: this.beaconCtx(),
|
|
645
|
+
ad: result,
|
|
646
|
+
serve: {
|
|
647
|
+
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
648
|
+
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
649
|
+
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
650
|
+
},
|
|
651
|
+
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
652
|
+
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
653
|
+
platform: this.o.platform,
|
|
654
|
+
sdkVersion: SDK_VERSION,
|
|
655
|
+
appVersion: this.o.appVersion,
|
|
656
|
+
openUrl: this.o.openUrl,
|
|
657
|
+
onShown: () => this.onShown(),
|
|
658
|
+
outbox: this.outbox,
|
|
659
|
+
});
|
|
660
|
+
return { ad: result, tracker };
|
|
526
661
|
};
|
|
527
|
-
const tracker = new InterstitialTracker({
|
|
528
|
-
ctx: this.beaconCtx(),
|
|
529
|
-
ad: result,
|
|
530
|
-
serve: {
|
|
531
|
-
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
532
|
-
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
533
|
-
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
534
|
-
},
|
|
535
|
-
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
536
|
-
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
537
|
-
platform: this.o.platform,
|
|
538
|
-
sdkVersion: SDK_VERSION,
|
|
539
|
-
appVersion: this.o.appVersion,
|
|
540
|
-
openUrl: this.o.openUrl,
|
|
541
|
-
onShown: () => this.onShown(),
|
|
542
|
-
outbox: this.outbox,
|
|
543
|
-
});
|
|
544
662
|
this.lastNoFillReason = null;
|
|
545
|
-
return {
|
|
663
|
+
return { served: { build, download, expiresAt, consumed: false, result: null } };
|
|
546
664
|
}
|
|
547
665
|
}
|
package/src/core/config.ts
CHANGED
|
@@ -5,6 +5,19 @@ import type { AudioPolicy, EthiclyConfig } from './types';
|
|
|
5
5
|
|
|
6
6
|
export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
|
|
7
7
|
export const DEFAULT_MAX_AGE_S = 300;
|
|
8
|
+
/**
|
|
9
|
+
* The skip delay is kept within these bounds, from /config and from the ad:
|
|
10
|
+
* the video is watched for at least 8 s before Skip appears (it still
|
|
11
|
+
* unlocks earlier when the video ends or after the call to action).
|
|
12
|
+
*/
|
|
13
|
+
export const MIN_SKIP_AFTER_MS = 8000;
|
|
14
|
+
export const MAX_SKIP_AFTER_MS = 15000;
|
|
15
|
+
|
|
16
|
+
/** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
|
|
17
|
+
export function clampSkipAfterMs(v: unknown): number | null {
|
|
18
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) return null;
|
|
19
|
+
return Math.min(MAX_SKIP_AFTER_MS, Math.max(MIN_SKIP_AFTER_MS, Math.round(v)));
|
|
20
|
+
}
|
|
8
21
|
|
|
9
22
|
/** The defaults shown in the doc. Used when no config was ever fetched. */
|
|
10
23
|
export function defaultConfig(serveBase: string): EthiclyConfig {
|
|
@@ -59,7 +72,7 @@ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig |
|
|
|
59
72
|
min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
|
|
60
73
|
formats: Array.isArray(b.formats) ? b.formats.filter((f): f is string => typeof f === 'string') : d.formats,
|
|
61
74
|
interstitial: {
|
|
62
|
-
skip_after_ms:
|
|
75
|
+
skip_after_ms: clampSkipAfterMs(it.skip_after_ms) ?? d.interstitial.skip_after_ms,
|
|
63
76
|
max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
|
|
64
77
|
min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
|
|
65
78
|
audio,
|
package/src/core/index.ts
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 type { Ethicly, EthiclyOptions } from './client';
|
|
4
4
|
export {
|
|
5
5
|
createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4,
|
package/src/core/tracker.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// method swallows its errors and reports them through the logger.
|
|
4
4
|
|
|
5
5
|
import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
|
|
6
|
-
import { appendClickToken, CLICK_TIMEOUT_MS } from './click';
|
|
6
|
+
import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
|
|
7
7
|
import { asImpressionId, httpRequest } from './http';
|
|
8
8
|
import type { Outbox } from './outbox';
|
|
9
9
|
import { uuidv4 } from './adapters';
|
|
@@ -319,6 +319,11 @@ export class InterstitialTracker implements Tracker {
|
|
|
319
319
|
clicked(): Promise<string> {
|
|
320
320
|
if (!this.clickUrl) this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
|
|
321
321
|
return this.clickUrl.then(async (url) => {
|
|
322
|
+
// The client already refuses such an ad; this guards a hand-built EthiclyAd.
|
|
323
|
+
if (!isWebUrl(url)) {
|
|
324
|
+
this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
|
|
325
|
+
return url;
|
|
326
|
+
}
|
|
322
327
|
try {
|
|
323
328
|
if (this.d.openUrl) await this.d.openUrl(url);
|
|
324
329
|
else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
|
package/src/core/types.ts
CHANGED
|
@@ -42,6 +42,11 @@ export interface FileCacheAdapter {
|
|
|
42
42
|
list?(): Promise<string[]>;
|
|
43
43
|
/** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
|
|
44
44
|
uriFor?(fileName: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* Abort every download in flight: each rejects and leaves no file. Optional;
|
|
47
|
+
* used by setAdsEnabled(false) and for a download that takes too long.
|
|
48
|
+
*/
|
|
49
|
+
cancel?(): void;
|
|
45
50
|
}
|
|
46
51
|
|
|
47
52
|
export interface Logger {
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Layout follows a typical in-app video player: 9:16 video, a skip control that counts
|
|
3
3
|
// down then reads "Skip Ad", a white call-to-action button, an optional
|
|
4
4
|
// "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
|
|
5
|
-
// Video starts with sound unless
|
|
5
|
+
// Video starts with sound unless the effective audio (the `audio` prop, else
|
|
6
|
+
// ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
|
|
6
7
|
// The controls keep clear of the notch, status bar and home indicator: see
|
|
7
8
|
// useSafeInsets below.
|
|
8
9
|
|
|
@@ -12,7 +13,7 @@ import {
|
|
|
12
13
|
type AppStateStatus, type StyleProp, type TextStyle, type ViewStyle,
|
|
13
14
|
} from 'react-native';
|
|
14
15
|
import { useVideoPlayer, VideoView } from 'expo-video';
|
|
15
|
-
import type { EthiclyAd, Tracker } from '../core/types';
|
|
16
|
+
import type { AudioPolicy, EthiclyAd, Tracker } from '../core/types';
|
|
16
17
|
|
|
17
18
|
/** Safe-area insets in points, as react-native-safe-area-context reports them. */
|
|
18
19
|
export interface EthiclyInsets { top: number; bottom: number; left: number; right: number }
|
|
@@ -44,6 +45,20 @@ export interface EthiclyInterstitialProps {
|
|
|
44
45
|
* only move them inward.
|
|
45
46
|
*/
|
|
46
47
|
insets?: EthiclyInsets;
|
|
48
|
+
/**
|
|
49
|
+
* Sound for this screen, over `ad.audio` (createEthicly's `audio` option,
|
|
50
|
+
* else the server's interstitial.audio, else 'on'). 'on' plays with sound,
|
|
51
|
+
* 'optional' starts muted with a sound toggle, 'none' plays muted with no toggle.
|
|
52
|
+
* With expo-video on iPhone, sound plays even with the silent switch on and
|
|
53
|
+
* pauses the user's own audio.
|
|
54
|
+
*/
|
|
55
|
+
audio?: AudioPolicy;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
|
|
59
|
+
export function effectiveAudio(prop: AudioPolicy | undefined, ad: { audio?: AudioPolicy }): AudioPolicy {
|
|
60
|
+
for (const v of [prop, ad.audio]) if (v === 'on' || v === 'optional' || v === 'none') return v;
|
|
61
|
+
return 'on';
|
|
47
62
|
}
|
|
48
63
|
|
|
49
64
|
const TICK_MS = 250;
|
|
@@ -145,8 +160,9 @@ interface BodyProps extends EthiclyInterstitialProps {
|
|
|
145
160
|
}
|
|
146
161
|
|
|
147
162
|
function InterstitialBody({
|
|
148
|
-
ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef,
|
|
163
|
+
ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp,
|
|
149
164
|
}: BodyProps) {
|
|
165
|
+
const audio = effectiveAudio(audioProp, ad);
|
|
150
166
|
const safe = useSafeInsets(insets);
|
|
151
167
|
const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
|
|
152
168
|
const appActive = useAppActive();
|
|
@@ -156,16 +172,22 @@ function InterstitialBody({
|
|
|
156
172
|
const [positionMs, setPositionMs] = useState(0);
|
|
157
173
|
const [ended, setEnded] = useState(false);
|
|
158
174
|
const [failed, setFailed] = useState(false);
|
|
159
|
-
const [muted, setMuted] = useState(
|
|
175
|
+
const [muted, setMuted] = useState(audio !== 'on');
|
|
176
|
+
/**
|
|
177
|
+
* A still image counts as visible only once it has loaded: an image that
|
|
178
|
+
* never arrives is never billed as viewable.
|
|
179
|
+
*/
|
|
180
|
+
const imageLoadedRef = useRef(false);
|
|
160
181
|
/** Wall-clock time on screen with the app in the foreground. */
|
|
161
182
|
const [onScreenMs, setOnScreenMs] = useState(0);
|
|
162
183
|
const [clicked, setClicked] = useState(false);
|
|
163
184
|
const positionRef = useRef(0);
|
|
164
185
|
const closedRef = useRef(false);
|
|
186
|
+
const failedRef = useRef(false);
|
|
165
187
|
|
|
166
188
|
const player = useVideoPlayer(isVideo ? ad.media.videoUri : null, (p) => {
|
|
167
189
|
p.loop = false;
|
|
168
|
-
p.muted =
|
|
190
|
+
p.muted = audio !== 'on';
|
|
169
191
|
p.timeUpdateEventInterval = TICK_MS / 1000;
|
|
170
192
|
p.play();
|
|
171
193
|
});
|
|
@@ -202,7 +224,8 @@ function InterstitialBody({
|
|
|
202
224
|
tracker.complete();
|
|
203
225
|
}),
|
|
204
226
|
player.addListener('statusChange', ({ status }) => {
|
|
205
|
-
if (status === 'error') {
|
|
227
|
+
if (status === 'error' && !failedRef.current) {
|
|
228
|
+
failedRef.current = true;
|
|
206
229
|
setFailed(true);
|
|
207
230
|
tracker.error();
|
|
208
231
|
}
|
|
@@ -211,22 +234,35 @@ function InterstitialBody({
|
|
|
211
234
|
return () => subs.forEach((s) => s.remove());
|
|
212
235
|
}, [isVideo, player, tracker]);
|
|
213
236
|
|
|
214
|
-
// Time on screen while the app is in the foreground
|
|
215
|
-
//
|
|
216
|
-
//
|
|
237
|
+
// Time on screen while the app is in the foreground: the skip countdown, so
|
|
238
|
+
// Skip appears after skipAfterMs even if the video stalls or the image never
|
|
239
|
+
// loads. For a still image, the time since it loaded is the playback position.
|
|
217
240
|
useEffect(() => {
|
|
218
241
|
let shownMs = 0;
|
|
242
|
+
let loadedMs = 0;
|
|
219
243
|
const id = setInterval(() => {
|
|
220
244
|
if (activeRef.current) shownMs += TICK_MS;
|
|
221
245
|
setOnScreenMs(shownMs);
|
|
222
|
-
if (isVideo) return;
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
246
|
+
if (isVideo || !imageLoadedRef.current || failedRef.current) return;
|
|
247
|
+
if (activeRef.current) loadedMs += TICK_MS;
|
|
248
|
+
positionRef.current = loadedMs;
|
|
249
|
+
setPositionMs(loadedMs);
|
|
250
|
+
tracker.progress(loadedMs, { visible: activeRef.current });
|
|
226
251
|
}, TICK_MS);
|
|
227
252
|
return () => clearInterval(id);
|
|
228
253
|
}, [isVideo, tracker]);
|
|
229
254
|
|
|
255
|
+
const onImageLoad = useCallback(() => {
|
|
256
|
+
imageLoadedRef.current = true;
|
|
257
|
+
}, []);
|
|
258
|
+
|
|
259
|
+
const onImageError = useCallback(() => {
|
|
260
|
+
if (failedRef.current) return;
|
|
261
|
+
failedRef.current = true;
|
|
262
|
+
setFailed(true);
|
|
263
|
+
tracker.error();
|
|
264
|
+
}, [tracker]);
|
|
265
|
+
|
|
230
266
|
useEffect(() => {
|
|
231
267
|
if (!isVideo) return;
|
|
232
268
|
if (appActive && !ended) player.play();
|
|
@@ -237,6 +273,7 @@ function InterstitialBody({
|
|
|
237
273
|
// waiting for the next player tick (which may never come while paused).
|
|
238
274
|
useEffect(() => {
|
|
239
275
|
if (appActive) return;
|
|
276
|
+
if (!isVideo && (!imageLoadedRef.current || failedRef.current)) return;
|
|
240
277
|
const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
|
|
241
278
|
tracker.progress(positionRef.current, { visible: false, durationMs });
|
|
242
279
|
}, [appActive, isVideo, player, tracker]);
|
|
@@ -277,10 +314,17 @@ function InterstitialBody({
|
|
|
277
314
|
{isVideo ? (
|
|
278
315
|
<>
|
|
279
316
|
{ad.media.posterUri ? <Image source={{ uri: ad.media.posterUri }} style={StyleSheet.absoluteFill} resizeMode="cover" /> : null}
|
|
280
|
-
|
|
317
|
+
{/* No native controls, so no fullscreen button: no fullscreen prop is needed (allowsFullscreen is deprecated). */}
|
|
318
|
+
<VideoView player={player} style={StyleSheet.absoluteFill} contentFit="cover" nativeControls={false} allowsPictureInPicture={false} />
|
|
281
319
|
</>
|
|
282
320
|
) : (
|
|
283
|
-
<Image
|
|
321
|
+
<Image
|
|
322
|
+
source={{ uri: ad.media.uri }}
|
|
323
|
+
style={StyleSheet.absoluteFill}
|
|
324
|
+
resizeMode="cover"
|
|
325
|
+
onLoad={onImageLoad}
|
|
326
|
+
onError={onImageError}
|
|
327
|
+
/>
|
|
284
328
|
)}
|
|
285
329
|
|
|
286
330
|
<View
|
|
@@ -289,7 +333,8 @@ function InterstitialBody({
|
|
|
289
333
|
>
|
|
290
334
|
<View style={styles.leftGroup}>
|
|
291
335
|
<Text style={styles.adLabel} accessibilityRole="text">Ad</Text>
|
|
292
|
-
{
|
|
336
|
+
{ad.test ? <Text style={[styles.adLabel, styles.testLabel]} accessibilityRole="text">Test ad</Text> : null}
|
|
337
|
+
{isVideo && audio !== 'none' ? (
|
|
293
338
|
<Pressable onPress={toggleSound} style={styles.soundButton} accessibilityRole="button" accessibilityLabel={muted ? 'Turn sound on' : 'Mute'} hitSlop={8}>
|
|
294
339
|
<Text style={styles.soundText}>{muted ? 'Sound off' : 'Sound on'}</Text>
|
|
295
340
|
</Pressable>
|
|
@@ -355,6 +400,7 @@ const styles = StyleSheet.create({
|
|
|
355
400
|
color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
|
|
356
401
|
backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
|
|
357
402
|
},
|
|
403
|
+
testLabel: { marginLeft: 8, backgroundColor: 'rgba(196,120,0,0.85)' },
|
|
358
404
|
soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
|
|
359
405
|
soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
|
|
360
406
|
// Solid black, no blur or translucency. The faint hairline keeps the edge
|
|
@@ -14,7 +14,7 @@ export interface EthiclyInterstitialState {
|
|
|
14
14
|
/** The ad to render, set by a successful show(). */
|
|
15
15
|
ad: EthiclyAd | null;
|
|
16
16
|
tracker: Tracker | null;
|
|
17
|
-
/** Why the last show() found no ad
|
|
17
|
+
/** Why the last show() found no ad: show your house ad, except for 'ads_disabled' (a paid user). */
|
|
18
18
|
reason: NoFillReason | null;
|
|
19
19
|
loading: boolean;
|
|
20
20
|
/** Load the ad to show now. Resolves true when `ad` is set, false on no fill. */
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
|
|
2
|
-
export const SDK_VERSION = '0.2.
|
|
2
|
+
export const SDK_VERSION = '0.2.1';
|