forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadRewards.js
More file actions
376 lines (338 loc) · 9.3 KB
/
Copy pathadRewards.js
File metadata and controls
376 lines (338 loc) · 9.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import toast from "components/toast";
import {
createRewardStateLifecycle,
isRewardPassActive,
} from "./adRewardBannerPolicy.mjs";
import auth from "./auth";
import config from "./config";
import secureAdRewardState from "./secureAdRewardState";
import { adUnitIdRewarded, setBannerSuppressed } from "./startAd";
const ONE_HOUR = 60 * 60 * 1000;
const REWARDED_RESULT_TIMEOUT_MS = 90 * 1000;
const OFFERS = [
{
id: "quick",
title: "Quick pass",
description: "Watch 1 rewarded ad and pause ads for 1 hour.",
adsRequired: 1,
durationMs: ONE_HOUR,
accentClass: "is-quick",
},
{
id: "focus",
title: "Focus block",
description:
"Watch 2 rewarded ads and pause ads for a random 4, 5, or 6 hours.",
adsRequired: 2,
minDurationMs: 4 * ONE_HOUR,
maxDurationMs: 6 * ONE_HOUR,
accentClass: "is-focus",
},
];
let state = getDefaultState();
let activeWatchPromise = null;
const listeners = new Set();
function getDefaultState() {
return {
adFreeUntil: 0,
lastExpiredRewardUntil: 0,
isActive: false,
remainingMs: 0,
redemptionsToday: 0,
remainingRedemptions: 3,
maxRedemptionsPerDay: 3,
maxActivePassMs: 10 * ONE_HOUR,
hasPendingExpiryNotice: false,
expiryNoticePendingUntil: 0,
canRedeem: true,
redeemDisabledReason: "",
};
}
function formatDuration(durationMs) {
const totalHours = Math.round(durationMs / ONE_HOUR);
if (totalHours < 1) return "less than 1 hour";
if (totalHours === 1) return "1 hour";
return `${totalHours} hours`;
}
function formatDurationRange(minDurationMs, maxDurationMs) {
if (!minDurationMs || !maxDurationMs || minDurationMs === maxDurationMs) {
return formatDuration(minDurationMs || maxDurationMs || 0);
}
const minHours = Math.round(minDurationMs / ONE_HOUR);
const maxHours = Math.round(maxDurationMs / ONE_HOUR);
return `${minHours}-${maxHours} hours`;
}
function getExpiryDate() {
return state.adFreeUntil ? new Date(state.adFreeUntil) : null;
}
function emitChange() {
const snapshot = {
...state,
expiryDate: getExpiryDate(),
};
listeners.forEach((listener) => {
try {
listener(snapshot);
} catch (error) {
console.error("Reward state listener failed.", error);
}
});
}
function notify(title, message, type = "info") {
toast(message, 4000);
window.acode?.pushNotification?.(title, message, {
icon: type === "success" ? "verified" : "notifications",
type,
});
}
function normalizeStatus(status) {
const fallback = getDefaultState();
if (!status || typeof status !== "object") return fallback;
const adFreeUntil = Number(status.adFreeUntil) || 0;
const remainingMs = Math.max(0, Number(status.remainingMs) || 0);
return {
...fallback,
...status,
adFreeUntil,
lastExpiredRewardUntil: Number(status.lastExpiredRewardUntil) || 0,
remainingMs,
redemptionsToday: Number(status.redemptionsToday) || 0,
remainingRedemptions: Number(status.remainingRedemptions) || 0,
maxRedemptionsPerDay:
Number(status.maxRedemptionsPerDay) || fallback.maxRedemptionsPerDay,
maxActivePassMs: Number(status.maxActivePassMs) || fallback.maxActivePassMs,
expiryNoticePendingUntil: Number(status.expiryNoticePendingUntil) || 0,
isActive: Boolean(status.isActive && adFreeUntil > Date.now()),
hasPendingExpiryNotice: Boolean(status.hasPendingExpiryNotice),
canRedeem: Boolean(status.canRedeem),
redeemDisabledReason: String(status.redeemDisabledReason || ""),
};
}
const rewardLifecycle = createRewardStateLifecycle({
loadStatus: () => secureAdRewardState.getStatus(),
normalizeStatus,
getCurrentState: () => state,
setCurrentState: (nextState) => {
state = nextState;
},
setBannerSuppressed,
emitChange,
onRefreshError: (error) =>
console.warn("Failed to refresh rewarded ad state.", error),
onListenerError: (error) =>
console.error("Reward lifecycle listener failed.", error),
onExpiryNotice: () => {
notify(
"Ad-free pass ended",
"Your rewarded ad-free time has expired. You can watch another rewarded ad anytime.",
"warning",
);
},
});
async function getRewardIdentity() {
try {
return String(user?.id || "Guest");
} catch (error) {
console.warn("Failed to resolve rewarded ad user identity.", error);
return String(device?.uuid || "guest");
}
}
async function createRewardedAd(offer, step, sessionId) {
if (!admob?.RewardedAd) {
throw new Error("Rewarded ads are not available in this build.");
}
const userId = await getRewardIdentity();
const customData = [
`session=${sessionId}`,
`offer=${offer.id}`,
`step=${step}`,
`ads=${offer.adsRequired}`,
].join("&");
return new admob.RewardedAd({
adUnitId: adUnitIdRewarded,
serverSideVerification: {
userId,
customData,
},
});
}
function waitForRewardedResult(ad) {
return new Promise((resolve, reject) => {
let earned = false;
let settled = false;
const timeoutId = setTimeout(() => {
fail(
new Error("Rewarded ad timed out before completion. Please try again."),
);
}, REWARDED_RESULT_TIMEOUT_MS);
const finish = (result) => {
if (settled) return;
settled = true;
clearTimeout(timeoutId);
resolve(result);
};
const fail = (error) => {
if (settled) return;
settled = true;
clearTimeout(timeoutId);
reject(
error instanceof Error
? error
: new Error(error?.message || "Rewarded ad failed."),
);
};
ad.on("reward", () => {
earned = true;
});
ad.on("dismiss", () => {
finish({ earned });
});
ad.on("showfail", fail);
ad.on("loadfail", fail);
});
}
async function showRewardedStep(offer, step, sessionId) {
const rewardedAd = await createRewardedAd(offer, step, sessionId);
const resultPromise = waitForRewardedResult(rewardedAd);
await rewardedAd.load();
await rewardedAd.show();
const result = await resultPromise;
if (!result.earned) {
throw new Error("Reward not earned. The ad was closed before completion.");
}
}
export default {
async init() {
await rewardLifecycle.initialize();
},
onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
async handleResume() {
await rewardLifecycle.resume();
},
getState() {
return {
...state,
expiryDate: getExpiryDate(),
};
},
getOffers() {
return OFFERS.map((offer) => ({
...offer,
durationLabel: formatDurationRange(
offer.minDurationMs || offer.durationMs,
offer.maxDurationMs || offer.durationMs,
),
}));
},
getRemainingMs() {
return Math.max(0, state.remainingMs || state.adFreeUntil - Date.now());
},
getRemainingLabel() {
const remainingMs = this.getRemainingMs();
if (!remainingMs) return "No active ad-free pass";
const minutes = Math.ceil(remainingMs / (60 * 1000));
if (minutes < 60) {
return `${minutes} minute${minutes === 1 ? "" : "s"} remaining`;
}
const hours = Math.floor(minutes / 60);
const remMinutes = minutes % 60;
if (!remMinutes) {
return `${hours} hour${hours === 1 ? "" : "s"} remaining`;
}
return `${hours}h ${remMinutes}m remaining`;
},
getExpiryLabel() {
const expiryDate = getExpiryDate();
if (!expiryDate) return "No active pass";
return expiryDate.toLocaleString();
},
isAdFreeActive() {
return isRewardPassActive(state);
},
canShowAds() {
return Boolean(!config.HAS_PRO && !this.isAdFreeActive());
},
isRewardedSupported() {
return Boolean(!config.HAS_PRO && admob?.RewardedAd && adUnitIdRewarded);
},
getRewardedUnavailableReason() {
if (config.HAS_PRO) {
return "Ads are already disabled on this build.";
}
if (!admob?.RewardedAd) {
return "Rewarded ads are unavailable on this device.";
}
return "";
},
canRedeemNow() {
return {
ok: Boolean(state.canRedeem),
reason: state.redeemDisabledReason || "",
};
},
isWatchingReward() {
return Boolean(activeWatchPromise);
},
async watchOffer(offerId, { onStep } = {}) {
if (activeWatchPromise) {
return activeWatchPromise;
}
const offer = OFFERS.find((item) => item.id === offerId);
if (!offer) {
throw new Error("Reward offer not found.");
}
if (!this.isRewardedSupported()) {
throw new Error(this.getRewardedUnavailableReason());
}
await rewardLifecycle.refresh({ notifyExpiry: false });
const redemptionStatus = this.canRedeemNow();
if (!redemptionStatus.ok) {
throw new Error(redemptionStatus.reason);
}
const sessionId =
typeof crypto?.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
activeWatchPromise = (async () => {
for (let step = 1; step <= offer.adsRequired; step += 1) {
onStep?.({
step,
totalSteps: offer.adsRequired,
offer,
});
await showRewardedStep(offer, step, sessionId);
if (step < offer.adsRequired) {
toast(
`Reward ${step}/${offer.adsRequired} complete. Loading the next ad...`,
2500,
);
}
}
const redeemedState = rewardLifecycle.applyStatus(
await secureAdRewardState.redeem(offer.id),
);
const grantedDurationMs =
Number(redeemedState.appliedDurationMs) ||
Number(redeemedState.grantedDurationMs) ||
0;
notify(
"Ad-free pass started",
`${formatDuration(grantedDurationMs)} unlocked. Ads will stay hidden until ${new Date(redeemedState.adFreeUntil).toLocaleString()}.`,
"success",
);
return {
offer,
expiresAt: redeemedState.adFreeUntil,
grantedDurationMs,
};
})().finally(() => {
activeWatchPromise = null;
emitChange();
});
emitChange();
return activeWatchPromise;
},
};