File size: 6,887 Bytes
b1876f7
 
 
 
4a58e48
daa9f5e
 
4a58e48
 
 
daa9f5e
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
 
 
4a58e48
b1876f7
 
4a58e48
b1876f7
 
4a58e48
 
 
b1876f7
4a58e48
 
b1876f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a58e48
 
 
 
 
 
b1876f7
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// "Pro" unlock: the access code from the Gumroad receipt (a Gumroad license key), checked from the browser and
// remembered on this device.
// Free: FREE_MINUTES of listening on this device, any voice, any book (the built-in sample does not count).
// Pro: unlimited listening.
//
// SWITCHED ON since 2026-11-20 (Gumroad product published). Tests and previews can turn it off with
// localStorage['earshelf.pro'] = 'off' (or on with 'on'). Nothing here runs a server; any check in the browser can be
// bypassed by a technical user, which is accepted: paying must be easier than cracking.

export const PRO = {
  enabled: true,
  // Gumroad product "EarShelf Pro" (license keys on), published 2026-11-20
  productId: 'ZWjOGDzBDsua-Kv6BhBvaA==',
  checkoutUrl: 'https://webixtech.gumroad.com/l/earshelf-pro',
  price: 'US$29',
  guaranteeDays: 30,
  recheckDays: 30, // re-verify a saved key this often (offline keeps working until it can)
};

const VERIFY_URL = 'https://api.gumroad.com/v2/licenses/verify';
const KEY = 'earshelf.license';

export interface License {
  key: string;
  email: string;
  verifiedAt: number;
  /** definite "no" answers in a row (Pro is removed at the second) */
  fails?: number;
}

export function paywallOn(): boolean {
  try {
    const v = localStorage.getItem('earshelf.pro');
    if (v === 'on') return true;
    if (v === 'off') return false;
  } catch {
    /* storage blocked */
  }
  return PRO.enabled;
}

export function savedLicense(): License | null {
  try {
    const raw = localStorage.getItem(KEY);
    const l = raw ? (JSON.parse(raw) as License) : null;
    return l && typeof l.key === 'string' ? l : null;
  } catch {
    return null;
  }
}

export function isPro(): boolean {
  return !!savedLicense();
}

/** Free listening on this device before the paywall: minutes of real playback, any voice, any book. */
export const FREE_MINUTES = 7;
const TRIAL = 'earshelf.trial';

/** Seconds of free listening (tests shrink it with localStorage['earshelf.freeSec']). */
export function freeSeconds(): number {
  try {
    const t = Number(localStorage.getItem('earshelf.freeSec'));
    if (t > 0) return t;
  } catch {
    /* storage blocked */
  }
  return FREE_MINUTES * 60;
}

/** Seconds already listened for free on this device. */
export function trialUsed(): number {
  try {
    const n = Number(localStorage.getItem(TRIAL));
    return Number.isFinite(n) && n > 0 ? n : 0;
  } catch {
    return 0;
  }
}

/** Add listening time (seconds). Never goes down; the larger of two stores wins (see main.ts). */
export function addTrial(sec: number, floor = 0) {
  const v = Math.max(trialUsed() + Math.max(0, sec), floor);
  try {
    localStorage.setItem(TRIAL, String(Math.round(v * 10) / 10));
  } catch {
    /* storage blocked */
  }
  return v;
}

export function trialLeft(): number {
  return Math.max(0, freeSeconds() + bonusSeconds() - trialUsed());
}

/* A one-time surprise: a day after the free minutes ran out, 2 more minutes ("the next page is on us"). */
const GATE_AT = 'earshelf.gateAt';
const BONUS = 'earshelf.bonus';
export const BONUS_SECONDS = 120;
function bonusSeconds(): number {
  try {
    return Number(localStorage.getItem(BONUS)) || 0;
  } catch {
    return 0;
  }
}
/** Remember when the paywall first stopped playback. */
export function noteGate(now = Date.now()) {
  try {
    if (!localStorage.getItem(GATE_AT)) localStorage.setItem(GATE_AT, String(now));
  } catch {
    /* storage blocked */
  }
}
/** Gives the bonus once, 24 h or more after the first stop. True when it was just given. */
export function grantBonus(now = Date.now()): boolean {
  try {
    const at = Number(localStorage.getItem(GATE_AT)) || 0;
    if (!at || localStorage.getItem(BONUS) || isPro() || !paywallOn() || now - at < 86_400_000) return false;
    localStorage.setItem(BONUS, String(trialUsed() - freeSeconds() + BONUS_SECONDS)); // 2 minutes from wherever the count is
    return true;
  } catch {
    return false;
  }
}

/** Does this book count against the free minutes? (the built-in sample never does) */
export function counts(book: { format: string } | null): boolean {
  return !!book && book.format !== 'sample' && paywallOn() && !isPro();
}

/** May playback go on? False only when the free minutes are used up on a metered book. */
export function mayListen(book: { format: string } | null): boolean {
  return !counts(book) || trialLeft() > 0;
}

export type VerifyResult = { ok: true; license: License } | { ok: false; reason: 'invalid' | 'refunded' | 'network' };

/** Ask Gumroad whether a key is valid for this product. Does not count as a new use of the key. */
export async function verifyKey(key: string, fetcher: typeof fetch = fetch): Promise<VerifyResult> {
  const k = key.replace(/\s+/g, ''); // pasted from an email: stray spaces and line breaks
  if (!k) return { ok: false, reason: 'invalid' };
  let res: Response;
  try {
    res = await fetcher(VERIFY_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ product_id: PRO.productId, license_key: k, increment_uses_count: 'false' }),
    });
  } catch {
    return { ok: false, reason: 'network' };
  }
  let data: any = null;
  try {
    data = await res.json();
  } catch {
    /* not JSON */
  }
  // a Wi-Fi login page, proxy or rate limit is not an answer about the key
  if (!data || typeof data !== 'object' || res.status === 408 || res.status === 429 || res.status >= 500) return { ok: false, reason: 'network' };
  if (!data.success) return { ok: false, reason: 'invalid' };
  const p = data.purchase || {};
  if (p.refunded || p.chargebacked || p.disputed) return { ok: false, reason: 'refunded' };
  return { ok: true, license: { key: k, email: String(p.email || ''), verifiedAt: Date.now() } };
}

export function storeLicense(l: License | null) {
  try {
    if (l) localStorage.setItem(KEY, JSON.stringify(l));
    else localStorage.removeItem(KEY);
  } catch {
    /* storage blocked */
  }
}

/**
 * Re-check a saved key now and then. A network failure keeps Pro (offline use must keep working);
 * only a definite "invalid" or "refunded" answer removes it.
 */
export async function recheck(now = Date.now(), fetcher: typeof fetch = fetch): Promise<'kept' | 'removed' | 'skipped'> {
  const l = savedLicense();
  if (!l) return 'skipped';
  if (now - l.verifiedAt < PRO.recheckDays * 86_400_000) return 'skipped';
  const r = await verifyKey(l.key, fetcher);
  if (r.ok) {
    storeLicense({ ...r.license, verifiedAt: now, fails: 0 });
    return 'kept';
  }
  if (r.reason === 'network') return 'kept';
  if (r.reason === 'invalid' && !l.fails) {
    storeLicense({ ...l, fails: 1, verifiedAt: now - PRO.recheckDays * 86_400_000 + 86_400_000 }); // ask again tomorrow
    return 'kept';
  }
  storeLicense(null);
  return 'removed';
}