@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
|
@@ -23,18 +23,27 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.effectiveAudio = effectiveAudio;
|
|
26
27
|
exports.EthiclyInterstitial = EthiclyInterstitial;
|
|
27
28
|
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
28
29
|
// Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
|
|
29
30
|
// Layout follows a typical in-app video player: 9:16 video, a skip control that counts
|
|
30
31
|
// down then reads "Skip Ad", a white call-to-action button, an optional
|
|
31
32
|
// "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
|
|
32
|
-
// Video starts with sound unless
|
|
33
|
+
// Video starts with sound unless the effective audio (the `audio` prop, else
|
|
34
|
+
// ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
|
|
33
35
|
// The controls keep clear of the notch, status bar and home indicator: see
|
|
34
36
|
// useSafeInsets below.
|
|
35
37
|
const react_1 = __importStar(require("react"));
|
|
36
38
|
const react_native_1 = require("react-native");
|
|
37
39
|
const expo_video_1 = require("expo-video");
|
|
40
|
+
/** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
|
|
41
|
+
function effectiveAudio(prop, ad) {
|
|
42
|
+
for (const v of [prop, ad.audio])
|
|
43
|
+
if (v === 'on' || v === 'optional' || v === 'none')
|
|
44
|
+
return v;
|
|
45
|
+
return 'on';
|
|
46
|
+
}
|
|
38
47
|
const TICK_MS = 250;
|
|
39
48
|
/** Space between the safe area and the controls. */
|
|
40
49
|
const TOP_GAP = 12;
|
|
@@ -114,7 +123,8 @@ function useAppActive() {
|
|
|
114
123
|
}, []);
|
|
115
124
|
return active;
|
|
116
125
|
}
|
|
117
|
-
function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, }) {
|
|
126
|
+
function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
|
|
127
|
+
const audio = effectiveAudio(audioProp, ad);
|
|
118
128
|
const safe = useSafeInsets(insets);
|
|
119
129
|
const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
|
|
120
130
|
const appActive = useAppActive();
|
|
@@ -123,15 +133,21 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
123
133
|
const [positionMs, setPositionMs] = (0, react_1.useState)(0);
|
|
124
134
|
const [ended, setEnded] = (0, react_1.useState)(false);
|
|
125
135
|
const [failed, setFailed] = (0, react_1.useState)(false);
|
|
126
|
-
const [muted, setMuted] = (0, react_1.useState)(
|
|
136
|
+
const [muted, setMuted] = (0, react_1.useState)(audio !== 'on');
|
|
137
|
+
/**
|
|
138
|
+
* A still image counts as visible only once it has loaded: an image that
|
|
139
|
+
* never arrives is never billed as viewable.
|
|
140
|
+
*/
|
|
141
|
+
const imageLoadedRef = (0, react_1.useRef)(false);
|
|
127
142
|
/** Wall-clock time on screen with the app in the foreground. */
|
|
128
143
|
const [onScreenMs, setOnScreenMs] = (0, react_1.useState)(0);
|
|
129
144
|
const [clicked, setClicked] = (0, react_1.useState)(false);
|
|
130
145
|
const positionRef = (0, react_1.useRef)(0);
|
|
131
146
|
const closedRef = (0, react_1.useRef)(false);
|
|
147
|
+
const failedRef = (0, react_1.useRef)(false);
|
|
132
148
|
const player = (0, expo_video_1.useVideoPlayer)(isVideo ? ad.media.videoUri : null, (p) => {
|
|
133
149
|
p.loop = false;
|
|
134
|
-
p.muted =
|
|
150
|
+
p.muted = audio !== 'on';
|
|
135
151
|
p.timeUpdateEventInterval = TICK_MS / 1000;
|
|
136
152
|
p.play();
|
|
137
153
|
});
|
|
@@ -166,7 +182,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
166
182
|
tracker.complete();
|
|
167
183
|
}),
|
|
168
184
|
player.addListener('statusChange', ({ status }) => {
|
|
169
|
-
if (status === 'error') {
|
|
185
|
+
if (status === 'error' && !failedRef.current) {
|
|
186
|
+
failedRef.current = true;
|
|
170
187
|
setFailed(true);
|
|
171
188
|
tracker.error();
|
|
172
189
|
}
|
|
@@ -174,23 +191,36 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
174
191
|
];
|
|
175
192
|
return () => subs.forEach((s) => s.remove());
|
|
176
193
|
}, [isVideo, player, tracker]);
|
|
177
|
-
// Time on screen while the app is in the foreground
|
|
178
|
-
//
|
|
179
|
-
//
|
|
194
|
+
// Time on screen while the app is in the foreground: the skip countdown, so
|
|
195
|
+
// Skip appears after skipAfterMs even if the video stalls or the image never
|
|
196
|
+
// loads. For a still image, the time since it loaded is the playback position.
|
|
180
197
|
(0, react_1.useEffect)(() => {
|
|
181
198
|
let shownMs = 0;
|
|
199
|
+
let loadedMs = 0;
|
|
182
200
|
const id = setInterval(() => {
|
|
183
201
|
if (activeRef.current)
|
|
184
202
|
shownMs += TICK_MS;
|
|
185
203
|
setOnScreenMs(shownMs);
|
|
186
|
-
if (isVideo)
|
|
204
|
+
if (isVideo || !imageLoadedRef.current || failedRef.current)
|
|
187
205
|
return;
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
206
|
+
if (activeRef.current)
|
|
207
|
+
loadedMs += TICK_MS;
|
|
208
|
+
positionRef.current = loadedMs;
|
|
209
|
+
setPositionMs(loadedMs);
|
|
210
|
+
tracker.progress(loadedMs, { visible: activeRef.current });
|
|
191
211
|
}, TICK_MS);
|
|
192
212
|
return () => clearInterval(id);
|
|
193
213
|
}, [isVideo, tracker]);
|
|
214
|
+
const onImageLoad = (0, react_1.useCallback)(() => {
|
|
215
|
+
imageLoadedRef.current = true;
|
|
216
|
+
}, []);
|
|
217
|
+
const onImageError = (0, react_1.useCallback)(() => {
|
|
218
|
+
if (failedRef.current)
|
|
219
|
+
return;
|
|
220
|
+
failedRef.current = true;
|
|
221
|
+
setFailed(true);
|
|
222
|
+
tracker.error();
|
|
223
|
+
}, [tracker]);
|
|
194
224
|
(0, react_1.useEffect)(() => {
|
|
195
225
|
if (!isVideo)
|
|
196
226
|
return;
|
|
@@ -204,6 +234,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
204
234
|
(0, react_1.useEffect)(() => {
|
|
205
235
|
if (appActive)
|
|
206
236
|
return;
|
|
237
|
+
if (!isVideo && (!imageLoadedRef.current || failedRef.current))
|
|
238
|
+
return;
|
|
207
239
|
const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
|
|
208
240
|
tracker.progress(positionRef.current, { visible: false, durationMs });
|
|
209
241
|
}, [appActive, isVideo, player, tracker]);
|
|
@@ -236,7 +268,7 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
|
|
|
236
268
|
const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
|
|
237
269
|
const canSkip = remainingS === 0 || ended || failed || clicked;
|
|
238
270
|
backRef.current = canSkip ? close : null;
|
|
239
|
-
return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [isVideo ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [ad.media.posterUri ? (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.posterUri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" }) : null, (0, jsx_runtime_1.jsx)(expo_video_1.VideoView, { player: player, style: react_native_1.StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false,
|
|
271
|
+
return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [isVideo ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [ad.media.posterUri ? (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.posterUri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" }) : null, (0, jsx_runtime_1.jsx)(expo_video_1.VideoView, { player: player, style: react_native_1.StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsPictureInPicture: false })] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.uri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover", onLoad: onImageLoad, onError: onImageError })), (0, jsx_runtime_1.jsxs)(react_native_1.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: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.leftGroup, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), ad.test ? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.adLabel, styles.testLabel], accessibilityRole: "text", children: "Test ad" }) : null, isVideo && audio !== 'none' ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), (0, jsx_runtime_1.jsx)(react_native_1.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 ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.skipRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), (0, jsx_runtime_1.jsx)(SkipIcon, {})] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bottom, {
|
|
240
272
|
bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
|
|
241
273
|
}], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" })] })] }));
|
|
242
274
|
}
|
|
@@ -255,6 +287,7 @@ const styles = react_native_1.StyleSheet.create({
|
|
|
255
287
|
color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
|
|
256
288
|
backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
|
|
257
289
|
},
|
|
290
|
+
testLabel: { marginLeft: 8, backgroundColor: 'rgba(196,120,0,0.85)' },
|
|
258
291
|
soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
|
|
259
292
|
soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
|
|
260
293
|
// Solid black, no blur or translucency. The faint hairline keeps the edge
|
|
@@ -50,5 +50,8 @@ function useEthiclyInterstitial(ethicly, options = {}) {
|
|
|
50
50
|
void ethicly.preload();
|
|
51
51
|
}, [ethicly, preload]);
|
|
52
52
|
const canShow = (0, react_1.useCallback)(() => ethicly.canShow(), [ethicly]);
|
|
53
|
-
|
|
53
|
+
const nextAdStatus = (0, react_1.useCallback)(() => ethicly.nextAdStatus(), [ethicly]);
|
|
54
|
+
return {
|
|
55
|
+
ad: (_a = current === null || current === void 0 ? void 0 : current.ad) !== null && _a !== void 0 ? _a : null, tracker: (_b = current === null || current === void 0 ? void 0 : current.tracker) !== null && _b !== void 0 ? _b : null, reason, loading, show, dismiss, canShow, nextAdStatus,
|
|
56
|
+
};
|
|
54
57
|
}
|
package/lib/commonjs/version.js
CHANGED
|
@@ -62,7 +62,8 @@ function isLegacyFs(fs) {
|
|
|
62
62
|
* A file cache over either expo-file-system API: the object API of SDK 54+
|
|
63
63
|
* (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
|
|
64
64
|
* `downloadAsync`, ...). Anything else gets the streaming cache, which writes
|
|
65
|
-
* nothing to disk, and one warning through `logger` (default `console`
|
|
65
|
+
* nothing to disk, and one warning through `logger` (default `console` in
|
|
66
|
+
* development, nothing in a release build).
|
|
66
67
|
*/
|
|
67
68
|
export function createExpoFileCache(fs, subdirectory = DEFAULT_CACHE_SUBDIRECTORY, logger) {
|
|
68
69
|
const sub = safeCacheSubdirectory(subdirectory);
|
|
@@ -70,7 +71,8 @@ export function createExpoFileCache(fs, subdirectory = DEFAULT_CACHE_SUBDIRECTOR
|
|
|
70
71
|
return modernFileCache(fs, sub);
|
|
71
72
|
if (isLegacyFs(fs))
|
|
72
73
|
return legacyFileCache(fs, sub);
|
|
73
|
-
|
|
74
|
+
// console only in development: a release build stays quiet unless the app passes a logger.
|
|
75
|
+
safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn('createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream');
|
|
74
76
|
return createMemoryFileCache();
|
|
75
77
|
}
|
|
76
78
|
function consoleLogger() {
|
|
@@ -80,6 +82,8 @@ function consoleLogger() {
|
|
|
80
82
|
function legacyFileCache(fs, sub) {
|
|
81
83
|
const dir = `${fs.cacheDirectory}${sub}`;
|
|
82
84
|
let made = null;
|
|
85
|
+
/** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
|
|
86
|
+
const inflight = new Set();
|
|
83
87
|
const sizeOf = async (uri) => {
|
|
84
88
|
const info = await fs.getInfoAsync(uri, { size: true });
|
|
85
89
|
return info.exists && typeof info.size === 'number' ? info.size : 0;
|
|
@@ -95,15 +99,22 @@ function legacyFileCache(fs, sub) {
|
|
|
95
99
|
let tooBig = false;
|
|
96
100
|
if (max !== undefined && fs.createDownloadResumable) {
|
|
97
101
|
// Stop as soon as the server announces, or we have written, more than the budget.
|
|
102
|
+
const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
|
|
98
103
|
const dl = fs.createDownloadResumable(url, target, {}, (p) => {
|
|
99
104
|
if (tooBig)
|
|
100
105
|
return;
|
|
101
106
|
if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
|
|
102
107
|
tooBig = true;
|
|
103
|
-
|
|
108
|
+
stop();
|
|
104
109
|
}
|
|
105
110
|
});
|
|
106
|
-
|
|
111
|
+
inflight.add(stop);
|
|
112
|
+
try {
|
|
113
|
+
res = await dl.downloadAsync().catch(() => undefined);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
inflight.delete(stop);
|
|
117
|
+
}
|
|
107
118
|
}
|
|
108
119
|
else {
|
|
109
120
|
res = await fs.downloadAsync(url, target);
|
|
@@ -118,6 +129,12 @@ function legacyFileCache(fs, sub) {
|
|
|
118
129
|
async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
|
|
119
130
|
size: sizeOf,
|
|
120
131
|
uriFor: (fileName) => dir + fileName,
|
|
132
|
+
cancel() {
|
|
133
|
+
inflight.forEach((stop) => { try {
|
|
134
|
+
stop();
|
|
135
|
+
}
|
|
136
|
+
catch { /* already settled */ } });
|
|
137
|
+
},
|
|
121
138
|
async list() {
|
|
122
139
|
if (!fs.readDirectoryAsync)
|
|
123
140
|
return [];
|
|
@@ -152,6 +169,7 @@ function modernFileCache(fs, sub) {
|
|
|
152
169
|
return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
|
|
153
170
|
};
|
|
154
171
|
let made = false;
|
|
172
|
+
const inflight = new Set();
|
|
155
173
|
return {
|
|
156
174
|
async download(url, fileName, opts) {
|
|
157
175
|
if (!made) {
|
|
@@ -163,6 +181,7 @@ function modernFileCache(fs, sub) {
|
|
|
163
181
|
const target = dir() + fileName;
|
|
164
182
|
const max = opts === null || opts === void 0 ? void 0 : opts.maxBytes;
|
|
165
183
|
let tooBig = false;
|
|
184
|
+
let cancelled = false;
|
|
166
185
|
try {
|
|
167
186
|
remove(target);
|
|
168
187
|
const createTask = fs.File.createDownloadTask;
|
|
@@ -179,7 +198,14 @@ function modernFileCache(fs, sub) {
|
|
|
179
198
|
catch { /* already settled */ }
|
|
180
199
|
},
|
|
181
200
|
});
|
|
182
|
-
|
|
201
|
+
const handle = { cancel: () => { cancelled = true; task.cancel(); } };
|
|
202
|
+
inflight.add(handle);
|
|
203
|
+
try {
|
|
204
|
+
await task.downloadAsync();
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
inflight.delete(handle);
|
|
208
|
+
}
|
|
183
209
|
}
|
|
184
210
|
else {
|
|
185
211
|
await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
|
|
@@ -195,6 +221,13 @@ function modernFileCache(fs, sub) {
|
|
|
195
221
|
// Without a progress callback the whole file lands first: check it now
|
|
196
222
|
// and delete it if it is over the budget.
|
|
197
223
|
const bytes = await sizeOf(target);
|
|
224
|
+
if (cancelled) {
|
|
225
|
+
try {
|
|
226
|
+
remove(target);
|
|
227
|
+
}
|
|
228
|
+
catch { /* ignore */ }
|
|
229
|
+
throw new Error('download cancelled');
|
|
230
|
+
}
|
|
198
231
|
if (tooBig || (max !== undefined && bytes > max)) {
|
|
199
232
|
try {
|
|
200
233
|
remove(target);
|
|
@@ -208,6 +241,12 @@ function modernFileCache(fs, sub) {
|
|
|
208
241
|
async delete(uri) { remove(uri); },
|
|
209
242
|
size: sizeOf,
|
|
210
243
|
uriFor: (fileName) => dir() + fileName,
|
|
244
|
+
cancel() {
|
|
245
|
+
inflight.forEach((t) => { try {
|
|
246
|
+
t.cancel();
|
|
247
|
+
}
|
|
248
|
+
catch { /* already settled */ } });
|
|
249
|
+
},
|
|
211
250
|
async list() {
|
|
212
251
|
const d = new fs.Directory(dir());
|
|
213
252
|
if (!d.exists)
|
package/lib/module/core/cache.js
CHANGED
|
@@ -10,6 +10,13 @@
|
|
|
10
10
|
// and is written again as soon as the download lands;
|
|
11
11
|
// - on first use every pending file, and every file in the SDK's cache
|
|
12
12
|
// directory that the index does not list, is deleted.
|
|
13
|
+
/**
|
|
14
|
+
* The longest one creative file may take to download. A slower (trickling)
|
|
15
|
+
* download is cancelled when the adapter supports it, else abandoned: the
|
|
16
|
+
* creative streams and later downloads are not held up behind it. A file it
|
|
17
|
+
* still writes afterwards is not indexed, so the next launch's sweep deletes it.
|
|
18
|
+
*/
|
|
19
|
+
export const DOWNLOAD_TIMEOUT_MS = 60000;
|
|
13
20
|
function hash(s) {
|
|
14
21
|
let h = 5381;
|
|
15
22
|
for (let i = 0; i < s.length; i++)
|
|
@@ -24,18 +31,59 @@ function baseName(uri) {
|
|
|
24
31
|
return uri.replace(/[?#].*$/, '').split('/').pop() || uri;
|
|
25
32
|
}
|
|
26
33
|
export class CreativeCache {
|
|
27
|
-
constructor(files, storage, storageKey, now, log, probeSize = async () => null) {
|
|
34
|
+
constructor(files, storage, storageKey, now, log, probeSize = async () => null, downloadTimeoutMs = DOWNLOAD_TIMEOUT_MS) {
|
|
28
35
|
this.files = files;
|
|
29
36
|
this.storage = storage;
|
|
30
37
|
this.storageKey = storageKey;
|
|
31
38
|
this.now = now;
|
|
32
39
|
this.log = log;
|
|
33
40
|
this.probeSize = probeSize;
|
|
41
|
+
this.downloadTimeoutMs = downloadTimeoutMs;
|
|
34
42
|
this.entries = [];
|
|
35
43
|
/** File names whose download has started but not landed. */
|
|
36
44
|
this.pending = [];
|
|
37
45
|
this.loaded = null;
|
|
38
46
|
this.chain = Promise.resolve();
|
|
47
|
+
/** Bumped by cancel(): a download started before it no longer counts. */
|
|
48
|
+
this.generation = 0;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
|
|
52
|
+
* and skip the files not started yet. For setAdsEnabled(false).
|
|
53
|
+
*/
|
|
54
|
+
cancel() {
|
|
55
|
+
var _a, _b;
|
|
56
|
+
this.generation += 1;
|
|
57
|
+
try {
|
|
58
|
+
(_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
this.log.warn('could not cancel the creative download', e);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** The adapter's download, given up on after downloadTimeoutMs. */
|
|
65
|
+
async downloadWithin(url, name, maxBytes) {
|
|
66
|
+
let timer;
|
|
67
|
+
const timeout = new Promise((_, reject) => {
|
|
68
|
+
timer = setTimeout(() => {
|
|
69
|
+
var _a, _b;
|
|
70
|
+
try {
|
|
71
|
+
(_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
72
|
+
}
|
|
73
|
+
catch { /* best effort */ }
|
|
74
|
+
reject(new Error(`download took longer than ${this.downloadTimeoutMs} ms`));
|
|
75
|
+
}, this.downloadTimeoutMs);
|
|
76
|
+
});
|
|
77
|
+
const dl = this.files.download(url, name, { maxBytes });
|
|
78
|
+
// A late rejection of an abandoned download must not go unhandled.
|
|
79
|
+
dl.catch(() => undefined);
|
|
80
|
+
try {
|
|
81
|
+
return await Promise.race([dl, timeout]);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
if (timer)
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
}
|
|
39
87
|
}
|
|
40
88
|
load() {
|
|
41
89
|
if (!this.loaded)
|
|
@@ -108,7 +156,8 @@ export class CreativeCache {
|
|
|
108
156
|
* Make sure the files of one creative are on disk. Never throws: a file that
|
|
109
157
|
* cannot be cached is simply left out of the result and streamed instead.
|
|
110
158
|
* `allowed()` is checked before every download so setAdsEnabled(false)
|
|
111
|
-
* stops a download that has not started yet
|
|
159
|
+
* stops a download that has not started yet; cancel() also stops the one in
|
|
160
|
+
* flight when the adapter supports it.
|
|
112
161
|
*/
|
|
113
162
|
ensure(adId, urls, limits, allowed) {
|
|
114
163
|
const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
|
|
@@ -130,10 +179,12 @@ export class CreativeCache {
|
|
|
130
179
|
this.entries.push(entry);
|
|
131
180
|
}
|
|
132
181
|
entry.lastUsed = this.now();
|
|
182
|
+
const generation = this.generation;
|
|
183
|
+
const go = () => allowed() && generation === this.generation;
|
|
133
184
|
for (const url of urls) {
|
|
134
185
|
if (entry.files.some((f) => f.url === url))
|
|
135
186
|
continue;
|
|
136
|
-
if (!
|
|
187
|
+
if (!go())
|
|
137
188
|
break;
|
|
138
189
|
// One creative may use the whole budget (older ones are evicted), never more.
|
|
139
190
|
const budget = limits.maxBytes - this.size(entry);
|
|
@@ -149,12 +200,16 @@ export class CreativeCache {
|
|
|
149
200
|
this.pending = [name];
|
|
150
201
|
await this.persist();
|
|
151
202
|
try {
|
|
152
|
-
const res = await this.
|
|
203
|
+
const res = await this.downloadWithin(url, name, budget);
|
|
153
204
|
const bytes = typeof res.bytes === 'number' && res.bytes > 0 ? res.bytes : await this.files.size(res.uri).catch(() => 0);
|
|
154
205
|
if (bytes > budget) {
|
|
155
206
|
await this.files.delete(res.uri).catch(() => undefined);
|
|
156
207
|
this.log.info(`${url} is over the cache budget: it will stream`);
|
|
157
208
|
}
|
|
209
|
+
else if (!go()) {
|
|
210
|
+
// Cancelled while it was landing: keep nothing for a paid user.
|
|
211
|
+
await this.files.delete(res.uri).catch(() => undefined);
|
|
212
|
+
}
|
|
158
213
|
else {
|
|
159
214
|
entry.files.push({ url, uri: res.uri, bytes });
|
|
160
215
|
}
|
package/lib/module/core/click.js
CHANGED
|
@@ -13,3 +13,12 @@ export function appendClickToken(destinationUrl, clickToken) {
|
|
|
13
13
|
}
|
|
14
14
|
/** The /click budget: the website snippet aborts at exactly 500 ms. */
|
|
15
15
|
export const CLICK_TIMEOUT_MS = 500;
|
|
16
|
+
/**
|
|
17
|
+
* True for an absolute http: or https: URL with a host. Anything else (tel:,
|
|
18
|
+
* intent:, javascript:, a custom app scheme, a relative path) is never opened.
|
|
19
|
+
*/
|
|
20
|
+
export function isWebUrl(url) {
|
|
21
|
+
return typeof url === 'string'
|
|
22
|
+
&& /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
|
|
23
|
+
&& !/[\s\u0000-\u001f\u007f]/.test(url);
|
|
24
|
+
}
|