@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
|
@@ -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
|
package/lib/module/version.js
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';
|
|
@@ -108,7 +108,8 @@ export declare function safeCacheSubdirectory(subdirectory: unknown): string;
|
|
|
108
108
|
* A file cache over either expo-file-system API: the object API of SDK 54+
|
|
109
109
|
* (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
|
|
110
110
|
* `downloadAsync`, ...). Anything else gets the streaming cache, which writes
|
|
111
|
-
* nothing to disk, and one warning through `logger` (default `console`
|
|
111
|
+
* nothing to disk, and one warning through `logger` (default `console` in
|
|
112
|
+
* development, nothing in a release build).
|
|
112
113
|
*/
|
|
113
114
|
export declare function createExpoFileCache(fs: ExpoFileSystemLike | ExpoFileSystemModernLike, subdirectory?: string, logger?: Logger): FileCacheAdapter;
|
|
114
115
|
/**
|
|
@@ -7,6 +7,13 @@ export interface CachedMedia {
|
|
|
7
7
|
/** remote URL -> local uri, for the files that are cached. */
|
|
8
8
|
uris: Record<string, string>;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* The longest one creative file may take to download. A slower (trickling)
|
|
12
|
+
* download is cancelled when the adapter supports it, else abandoned: the
|
|
13
|
+
* creative streams and later downloads are not held up behind it. A file it
|
|
14
|
+
* still writes afterwards is not indexed, so the next launch's sweep deletes it.
|
|
15
|
+
*/
|
|
16
|
+
export declare const DOWNLOAD_TIMEOUT_MS = 60000;
|
|
10
17
|
/** Content-Length of a URL, or null when unknown. */
|
|
11
18
|
export type SizeProbe = (url: string) => Promise<number | null>;
|
|
12
19
|
export declare class CreativeCache {
|
|
@@ -16,12 +23,22 @@ export declare class CreativeCache {
|
|
|
16
23
|
private now;
|
|
17
24
|
private log;
|
|
18
25
|
private probeSize;
|
|
26
|
+
private downloadTimeoutMs;
|
|
19
27
|
private entries;
|
|
20
28
|
/** File names whose download has started but not landed. */
|
|
21
29
|
private pending;
|
|
22
30
|
private loaded;
|
|
23
31
|
private chain;
|
|
24
|
-
|
|
32
|
+
/** Bumped by cancel(): a download started before it no longer counts. */
|
|
33
|
+
private generation;
|
|
34
|
+
constructor(files: FileCacheAdapter, storage: KeyValueStorage, storageKey: string, now: () => number, log: Required<Logger>, probeSize?: SizeProbe, downloadTimeoutMs?: number);
|
|
35
|
+
/**
|
|
36
|
+
* Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
|
|
37
|
+
* and skip the files not started yet. For setAdsEnabled(false).
|
|
38
|
+
*/
|
|
39
|
+
cancel(): void;
|
|
40
|
+
/** The adapter's download, given up on after downloadTimeoutMs. */
|
|
41
|
+
private downloadWithin;
|
|
25
42
|
private load;
|
|
26
43
|
private loadNow;
|
|
27
44
|
/**
|
|
@@ -40,7 +57,8 @@ export declare class CreativeCache {
|
|
|
40
57
|
* Make sure the files of one creative are on disk. Never throws: a file that
|
|
41
58
|
* cannot be cached is simply left out of the result and streamed instead.
|
|
42
59
|
* `allowed()` is checked before every download so setAdsEnabled(false)
|
|
43
|
-
* stops a download that has not started yet
|
|
60
|
+
* stops a download that has not started yet; cancel() also stops the one in
|
|
61
|
+
* flight when the adapter supports it.
|
|
44
62
|
*/
|
|
45
63
|
ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
|
|
46
64
|
private ensureNow;
|
|
@@ -6,3 +6,8 @@
|
|
|
6
6
|
export declare function appendClickToken(destinationUrl: string, clickToken: string | null | undefined): string;
|
|
7
7
|
/** The /click budget: the website snippet aborts at exactly 500 ms. */
|
|
8
8
|
export declare const CLICK_TIMEOUT_MS = 500;
|
|
9
|
+
/**
|
|
10
|
+
* True for an absolute http: or https: URL with a host. Anything else (tel:,
|
|
11
|
+
* intent:, javascript:, a custom app scheme, a relative path) is never opened.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isWebUrl(url: unknown): url is string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AppStateLike } from './adapters';
|
|
2
|
-
import type { EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform } from './types';
|
|
2
|
+
import type { AudioPolicy, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform } from './types';
|
|
3
3
|
export interface EthiclyOptions {
|
|
4
4
|
/** Publisher API key (UUID). */
|
|
5
5
|
apiKey: string;
|
|
@@ -14,8 +14,26 @@ export interface EthiclyOptions {
|
|
|
14
14
|
* (`__DEV__` false), where the SDK serves and bills normally and logs an error.
|
|
15
15
|
*/
|
|
16
16
|
testMode?: boolean;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Initial state of the ads switch, default true. Apps with a paid tier: pass
|
|
19
|
+
* false until you know the user's entitlement, then setAdsEnabled(true) for
|
|
20
|
+
* free users, so a subscriber never serves or downloads an ad.
|
|
21
|
+
*/
|
|
18
22
|
adsEnabled?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Sound for every ad, over the server's interstitial.audio: 'on' plays with
|
|
25
|
+
* sound, 'optional' starts muted with a sound toggle, 'none' plays muted with
|
|
26
|
+
* no toggle. Unset: the server's value, which defaults to 'on'. `ad.audio`
|
|
27
|
+
* is the effective value. EthiclyInterstitial's `audio` prop overrides it per screen.
|
|
28
|
+
*/
|
|
29
|
+
audio?: AudioPolicy;
|
|
30
|
+
/**
|
|
31
|
+
* The longest loadInterstitial() waits for the creative download when no
|
|
32
|
+
* preloaded ad is ready, in ms. Default 3000 (DEFAULT_LOAD_TIMEOUT_MS). After
|
|
33
|
+
* it the ad comes back with the remote URL, so the player streams, and the
|
|
34
|
+
* download carries on in the background for next time.
|
|
35
|
+
*/
|
|
36
|
+
loadTimeoutMs?: number;
|
|
19
37
|
storage?: KeyValueStorage;
|
|
20
38
|
fileCache?: FileCacheAdapter;
|
|
21
39
|
openUrl?: (url: string) => unknown;
|
|
@@ -40,7 +58,7 @@ export interface Ethicly {
|
|
|
40
58
|
* false until the stored frequency state has loaded (see `ready`).
|
|
41
59
|
*/
|
|
42
60
|
canShow(): boolean;
|
|
43
|
-
/** false for paid users: stops serves and
|
|
61
|
+
/** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
|
|
44
62
|
setAdsEnabled(enabled: boolean): void;
|
|
45
63
|
isAdsEnabled(): boolean;
|
|
46
64
|
getConfig(): EthiclyConfig;
|
|
@@ -50,6 +68,8 @@ export interface Ethicly {
|
|
|
50
68
|
readonly lastNoFillReason: NoFillReason | null;
|
|
51
69
|
readonly sdkVersion: string;
|
|
52
70
|
}
|
|
71
|
+
/** How long loadInterstitial() waits for a creative download by default. */
|
|
72
|
+
export declare const DEFAULT_LOAD_TIMEOUT_MS = 3000;
|
|
53
73
|
/**
|
|
54
74
|
* A new session (interstitial.max_per_session counts from zero again) starts
|
|
55
75
|
* when the app comes back after at least this long in the background.
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { EthiclyConfig } from './types';
|
|
2
2
|
export declare const BUNDLED_BASE_URL = "https://ads.ethicly.ch/functions/v1/get-ad-with-geo";
|
|
3
3
|
export declare const DEFAULT_MAX_AGE_S = 300;
|
|
4
|
+
/**
|
|
5
|
+
* The skip delay is kept within these bounds, from /config and from the ad:
|
|
6
|
+
* the video is watched for at least 8 s before Skip appears (it still
|
|
7
|
+
* unlocks earlier when the video ends or after the call to action).
|
|
8
|
+
*/
|
|
9
|
+
export declare const MIN_SKIP_AFTER_MS = 8000;
|
|
10
|
+
export declare const MAX_SKIP_AFTER_MS = 15000;
|
|
11
|
+
/** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
|
|
12
|
+
export declare function clampSkipAfterMs(v: unknown): number | null;
|
|
4
13
|
/** The defaults shown in the doc. Used when no config was ever fetched. */
|
|
5
14
|
export declare function defaultConfig(serveBase: string): EthiclyConfig;
|
|
6
15
|
/** An https URL, without a trailing slash, or null. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createEthicly, SESSION_TIMEOUT_MS } from './client';
|
|
1
|
+
export { createEthicly, DEFAULT_LOAD_TIMEOUT_MS, SESSION_TIMEOUT_MS } from './client';
|
|
2
2
|
export type { Ethicly, EthiclyOptions } from './client';
|
|
3
3
|
export { createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4, } from './adapters';
|
|
4
4
|
export type { AppStateLike, ExpoFileSystemLike, ExpoFileSystemModernLike } from './adapters';
|
|
@@ -52,6 +52,11 @@ export interface FileCacheAdapter {
|
|
|
52
52
|
list?(): Promise<string[]>;
|
|
53
53
|
/** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
|
|
54
54
|
uriFor?(fileName: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Abort every download in flight: each rejects and leaves no file. Optional;
|
|
57
|
+
* used by setAdsEnabled(false) and for a download that takes too long.
|
|
58
|
+
*/
|
|
59
|
+
cancel?(): void;
|
|
55
60
|
}
|
|
56
61
|
export interface Logger {
|
|
57
62
|
debug?(message: string, ...rest: unknown[]): void;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { type StyleProp, type TextStyle, type ViewStyle } from 'react-native';
|
|
3
|
-
import type { EthiclyAd, Tracker } from '../core/types';
|
|
3
|
+
import type { AudioPolicy, EthiclyAd, Tracker } from '../core/types';
|
|
4
4
|
/** Safe-area insets in points, as react-native-safe-area-context reports them. */
|
|
5
5
|
export interface EthiclyInsets {
|
|
6
6
|
top: number;
|
|
@@ -35,5 +35,17 @@ export interface EthiclyInterstitialProps {
|
|
|
35
35
|
* only move them inward.
|
|
36
36
|
*/
|
|
37
37
|
insets?: EthiclyInsets;
|
|
38
|
+
/**
|
|
39
|
+
* Sound for this screen, over `ad.audio` (createEthicly's `audio` option,
|
|
40
|
+
* else the server's interstitial.audio, else 'on'). 'on' plays with sound,
|
|
41
|
+
* 'optional' starts muted with a sound toggle, 'none' plays muted with no toggle.
|
|
42
|
+
* With expo-video on iPhone, sound plays even with the silent switch on and
|
|
43
|
+
* pauses the user's own audio.
|
|
44
|
+
*/
|
|
45
|
+
audio?: AudioPolicy;
|
|
38
46
|
}
|
|
47
|
+
/** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
|
|
48
|
+
export declare function effectiveAudio(prop: AudioPolicy | undefined, ad: {
|
|
49
|
+
audio?: AudioPolicy;
|
|
50
|
+
}): AudioPolicy;
|
|
39
51
|
export declare function EthiclyInterstitial(props: EthiclyInterstitialProps): React.ReactElement;
|
|
@@ -8,7 +8,7 @@ export interface EthiclyInterstitialState {
|
|
|
8
8
|
/** The ad to render, set by a successful show(). */
|
|
9
9
|
ad: EthiclyAd | null;
|
|
10
10
|
tracker: Tracker | null;
|
|
11
|
-
/** Why the last show() found no ad
|
|
11
|
+
/** Why the last show() found no ad: show your house ad, except for 'ads_disabled' (a paid user). */
|
|
12
12
|
reason: NoFillReason | null;
|
|
13
13
|
loading: boolean;
|
|
14
14
|
/** Load the ad to show now. Resolves true when `ad` is set, false on no fill. */
|
|
@@ -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 declare const SDK_VERSION = "0.2.
|
|
2
|
+
export declare const SDK_VERSION = "0.2.1";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ethicly/react-native",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Ethicly fullscreen video ads for React Native and Expo. Headless core plus an optional ready-made screen.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://ethicly.ch",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
49
49
|
"test": "jest",
|
|
50
50
|
"test:live": "npm run build && node scripts/live-test.mjs",
|
|
51
|
-
"
|
|
51
|
+
"prepack": "npm run build",
|
|
52
52
|
"build": "node scripts/clean.mjs && tsc -p tsconfig.build.json --module commonjs --outDir lib/commonjs && tsc -p tsconfig.build.json --module es2020 --outDir lib/module && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --outDir lib/typescript"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
package/src/core/adapters.ts
CHANGED
|
@@ -130,7 +130,8 @@ function isLegacyFs(fs: unknown): fs is ExpoFileSystemLike {
|
|
|
130
130
|
* A file cache over either expo-file-system API: the object API of SDK 54+
|
|
131
131
|
* (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
|
|
132
132
|
* `downloadAsync`, ...). Anything else gets the streaming cache, which writes
|
|
133
|
-
* nothing to disk, and one warning through `logger` (default `console`
|
|
133
|
+
* nothing to disk, and one warning through `logger` (default `console` in
|
|
134
|
+
* development, nothing in a release build).
|
|
134
135
|
*/
|
|
135
136
|
export function createExpoFileCache(
|
|
136
137
|
fs: ExpoFileSystemLike | ExpoFileSystemModernLike,
|
|
@@ -140,7 +141,8 @@ export function createExpoFileCache(
|
|
|
140
141
|
const sub = safeCacheSubdirectory(subdirectory);
|
|
141
142
|
if (isModernFs(fs)) return modernFileCache(fs, sub);
|
|
142
143
|
if (isLegacyFs(fs)) return legacyFileCache(fs, sub);
|
|
143
|
-
|
|
144
|
+
// console only in development: a release build stays quiet unless the app passes a logger.
|
|
145
|
+
safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn(
|
|
144
146
|
'createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream',
|
|
145
147
|
);
|
|
146
148
|
return createMemoryFileCache();
|
|
@@ -154,6 +156,8 @@ function consoleLogger(): Logger {
|
|
|
154
156
|
function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter {
|
|
155
157
|
const dir = `${fs.cacheDirectory}${sub}`;
|
|
156
158
|
let made: Promise<void> | null = null;
|
|
159
|
+
/** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
|
|
160
|
+
const inflight = new Set<() => void>();
|
|
157
161
|
const sizeOf = async (uri: string): Promise<number> => {
|
|
158
162
|
const info = await fs.getInfoAsync(uri, { size: true });
|
|
159
163
|
return info.exists && typeof info.size === 'number' ? info.size : 0;
|
|
@@ -168,14 +172,20 @@ function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter
|
|
|
168
172
|
let tooBig = false;
|
|
169
173
|
if (max !== undefined && fs.createDownloadResumable) {
|
|
170
174
|
// Stop as soon as the server announces, or we have written, more than the budget.
|
|
175
|
+
const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
|
|
171
176
|
const dl = fs.createDownloadResumable(url, target, {}, (p) => {
|
|
172
177
|
if (tooBig) return;
|
|
173
178
|
if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
|
|
174
179
|
tooBig = true;
|
|
175
|
-
|
|
180
|
+
stop();
|
|
176
181
|
}
|
|
177
182
|
});
|
|
178
|
-
|
|
183
|
+
inflight.add(stop);
|
|
184
|
+
try {
|
|
185
|
+
res = await dl.downloadAsync().catch(() => undefined);
|
|
186
|
+
} finally {
|
|
187
|
+
inflight.delete(stop);
|
|
188
|
+
}
|
|
179
189
|
} else {
|
|
180
190
|
res = await fs.downloadAsync(url, target);
|
|
181
191
|
}
|
|
@@ -189,6 +199,9 @@ function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter
|
|
|
189
199
|
async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
|
|
190
200
|
size: sizeOf,
|
|
191
201
|
uriFor: (fileName) => dir + fileName,
|
|
202
|
+
cancel() {
|
|
203
|
+
inflight.forEach((stop) => { try { stop(); } catch { /* already settled */ } });
|
|
204
|
+
},
|
|
192
205
|
async list() {
|
|
193
206
|
if (!fs.readDirectoryAsync) return [];
|
|
194
207
|
const names = await fs.readDirectoryAsync(dir).catch(() => [] as string[]);
|
|
@@ -222,6 +235,7 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
222
235
|
return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
|
|
223
236
|
};
|
|
224
237
|
let made = false;
|
|
238
|
+
const inflight = new Set<{ cancel(): void }>();
|
|
225
239
|
return {
|
|
226
240
|
async download(url, fileName, opts) {
|
|
227
241
|
if (!made) {
|
|
@@ -232,6 +246,7 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
232
246
|
const target = dir() + fileName;
|
|
233
247
|
const max = opts?.maxBytes;
|
|
234
248
|
let tooBig = false;
|
|
249
|
+
let cancelled = false;
|
|
235
250
|
try {
|
|
236
251
|
remove(target);
|
|
237
252
|
const createTask = fs.File.createDownloadTask;
|
|
@@ -244,7 +259,13 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
244
259
|
try { task.cancel(); } catch { /* already settled */ }
|
|
245
260
|
},
|
|
246
261
|
});
|
|
247
|
-
|
|
262
|
+
const handle = { cancel: () => { cancelled = true; task.cancel(); } };
|
|
263
|
+
inflight.add(handle);
|
|
264
|
+
try {
|
|
265
|
+
await task.downloadAsync();
|
|
266
|
+
} finally {
|
|
267
|
+
inflight.delete(handle);
|
|
268
|
+
}
|
|
248
269
|
} else {
|
|
249
270
|
await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
|
|
250
271
|
}
|
|
@@ -255,6 +276,10 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
255
276
|
// Without a progress callback the whole file lands first: check it now
|
|
256
277
|
// and delete it if it is over the budget.
|
|
257
278
|
const bytes = await sizeOf(target);
|
|
279
|
+
if (cancelled) {
|
|
280
|
+
try { remove(target); } catch { /* ignore */ }
|
|
281
|
+
throw new Error('download cancelled');
|
|
282
|
+
}
|
|
258
283
|
if (tooBig || (max !== undefined && bytes > max)) {
|
|
259
284
|
try { remove(target); } catch { /* ignore */ }
|
|
260
285
|
throw new Error('creative over the cache budget');
|
|
@@ -265,6 +290,9 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
265
290
|
async delete(uri) { remove(uri); },
|
|
266
291
|
size: sizeOf,
|
|
267
292
|
uriFor: (fileName) => dir() + fileName,
|
|
293
|
+
cancel() {
|
|
294
|
+
inflight.forEach((t) => { try { t.cancel(); } catch { /* already settled */ } });
|
|
295
|
+
},
|
|
268
296
|
async list() {
|
|
269
297
|
const d = new fs.Directory(dir());
|
|
270
298
|
if (!d.exists) return [];
|
package/src/core/cache.ts
CHANGED
|
@@ -24,6 +24,14 @@ export interface CachedMedia {
|
|
|
24
24
|
uris: Record<string, string>;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* The longest one creative file may take to download. A slower (trickling)
|
|
29
|
+
* download is cancelled when the adapter supports it, else abandoned: the
|
|
30
|
+
* creative streams and later downloads are not held up behind it. A file it
|
|
31
|
+
* still writes afterwards is not indexed, so the next launch's sweep deletes it.
|
|
32
|
+
*/
|
|
33
|
+
export const DOWNLOAD_TIMEOUT_MS = 60000;
|
|
34
|
+
|
|
27
35
|
/** Content-Length of a URL, or null when unknown. */
|
|
28
36
|
export type SizeProbe = (url: string) => Promise<number | null>;
|
|
29
37
|
|
|
@@ -48,6 +56,8 @@ export class CreativeCache {
|
|
|
48
56
|
private pending: string[] = [];
|
|
49
57
|
private loaded: Promise<void> | null = null;
|
|
50
58
|
private chain: Promise<unknown> = Promise.resolve();
|
|
59
|
+
/** Bumped by cancel(): a download started before it no longer counts. */
|
|
60
|
+
private generation = 0;
|
|
51
61
|
|
|
52
62
|
constructor(
|
|
53
63
|
private files: FileCacheAdapter,
|
|
@@ -56,8 +66,37 @@ export class CreativeCache {
|
|
|
56
66
|
private now: () => number,
|
|
57
67
|
private log: Required<Logger>,
|
|
58
68
|
private probeSize: SizeProbe = async () => null,
|
|
69
|
+
private downloadTimeoutMs: number = DOWNLOAD_TIMEOUT_MS,
|
|
59
70
|
) {}
|
|
60
71
|
|
|
72
|
+
/**
|
|
73
|
+
* Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
|
|
74
|
+
* and skip the files not started yet. For setAdsEnabled(false).
|
|
75
|
+
*/
|
|
76
|
+
cancel(): void {
|
|
77
|
+
this.generation += 1;
|
|
78
|
+
try { this.files.cancel?.(); } catch (e) { this.log.warn('could not cancel the creative download', e); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The adapter's download, given up on after downloadTimeoutMs. */
|
|
82
|
+
private async downloadWithin(url: string, name: string, maxBytes: number): Promise<{ uri: string; bytes?: number }> {
|
|
83
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
84
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
85
|
+
timer = setTimeout(() => {
|
|
86
|
+
try { this.files.cancel?.(); } catch { /* best effort */ }
|
|
87
|
+
reject(new Error(`download took longer than ${this.downloadTimeoutMs} ms`));
|
|
88
|
+
}, this.downloadTimeoutMs);
|
|
89
|
+
});
|
|
90
|
+
const dl = this.files.download(url, name, { maxBytes });
|
|
91
|
+
// A late rejection of an abandoned download must not go unhandled.
|
|
92
|
+
dl.catch(() => undefined);
|
|
93
|
+
try {
|
|
94
|
+
return await Promise.race([dl, timeout]);
|
|
95
|
+
} finally {
|
|
96
|
+
if (timer) clearTimeout(timer);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
61
100
|
private load(): Promise<void> {
|
|
62
101
|
if (!this.loaded) this.loaded = this.loadNow();
|
|
63
102
|
return this.loaded;
|
|
@@ -127,7 +166,8 @@ export class CreativeCache {
|
|
|
127
166
|
* Make sure the files of one creative are on disk. Never throws: a file that
|
|
128
167
|
* cannot be cached is simply left out of the result and streamed instead.
|
|
129
168
|
* `allowed()` is checked before every download so setAdsEnabled(false)
|
|
130
|
-
* stops a download that has not started yet
|
|
169
|
+
* stops a download that has not started yet; cancel() also stops the one in
|
|
170
|
+
* flight when the adapter supports it.
|
|
131
171
|
*/
|
|
132
172
|
ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
|
|
133
173
|
const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
|
|
@@ -149,10 +189,12 @@ export class CreativeCache {
|
|
|
149
189
|
this.entries.push(entry);
|
|
150
190
|
}
|
|
151
191
|
entry.lastUsed = this.now();
|
|
192
|
+
const generation = this.generation;
|
|
193
|
+
const go = () => allowed() && generation === this.generation;
|
|
152
194
|
|
|
153
195
|
for (const url of urls) {
|
|
154
196
|
if (entry.files.some((f) => f.url === url)) continue;
|
|
155
|
-
if (!
|
|
197
|
+
if (!go()) break;
|
|
156
198
|
// One creative may use the whole budget (older ones are evicted), never more.
|
|
157
199
|
const budget = limits.maxBytes - this.size(entry);
|
|
158
200
|
const known = await this.probeSize(url).catch(() => null);
|
|
@@ -166,11 +208,14 @@ export class CreativeCache {
|
|
|
166
208
|
this.pending = [name];
|
|
167
209
|
await this.persist();
|
|
168
210
|
try {
|
|
169
|
-
const res = await this.
|
|
211
|
+
const res = await this.downloadWithin(url, name, budget);
|
|
170
212
|
const bytes = typeof res.bytes === 'number' && res.bytes > 0 ? res.bytes : await this.files.size(res.uri).catch(() => 0);
|
|
171
213
|
if (bytes > budget) {
|
|
172
214
|
await this.files.delete(res.uri).catch(() => undefined);
|
|
173
215
|
this.log.info(`${url} is over the cache budget: it will stream`);
|
|
216
|
+
} else if (!go()) {
|
|
217
|
+
// Cancelled while it was landing: keep nothing for a paid user.
|
|
218
|
+
await this.files.delete(res.uri).catch(() => undefined);
|
|
174
219
|
} else {
|
|
175
220
|
entry.files.push({ url, uri: res.uri, bytes });
|
|
176
221
|
}
|
package/src/core/click.ts
CHANGED
|
@@ -14,3 +14,13 @@ export function appendClickToken(destinationUrl: string, clickToken: string | nu
|
|
|
14
14
|
|
|
15
15
|
/** The /click budget: the website snippet aborts at exactly 500 ms. */
|
|
16
16
|
export const CLICK_TIMEOUT_MS = 500;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True for an absolute http: or https: URL with a host. Anything else (tel:,
|
|
20
|
+
* intent:, javascript:, a custom app scheme, a relative path) is never opened.
|
|
21
|
+
*/
|
|
22
|
+
export function isWebUrl(url: unknown): url is string {
|
|
23
|
+
return typeof url === 'string'
|
|
24
|
+
&& /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
|
|
25
|
+
&& !/[\s\u0000-\u001f\u007f]/.test(url);
|
|
26
|
+
}
|