1import { Actor, log } from 'apify';
2
3const ALL_COUNTRIES = ('ae ag ai al am ao ar at au az bb be bf bg bh bj bm bn bo br bs bt bw by bz ca cg ch cl cn co cr cv cy cz de dk dm do dz ec ee eg es fi fj fm fr gb gd gh gm gr gt gw gy hk hn hr hu id ie il in is it jm jo jp ke kg kh kn kr kw ky kz la lb lc lk lr lt lu lv md mg mk ml mn mo mr ms mt mu mw mx my mz na ne ng ni nl no np nz om pa pe pg ph pk pl pt pw py qa ro ru sa sb sc se sg si sk sl sn sr st sv sz tc td th tj tm tn tr tt tw tz ua ug us uy uz vc ve vg vn ye za zw').split(' ');
4const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5const lbl = (x) => x?.label ?? null;
6
7function parseApp(raw) {
8 const s = String(raw).trim();
9 const m = s.match(/id(\d{5,})/) ?? s.match(/^(\d{5,})$/);
10 return m ? m[1] : null;
11}
12
13async function fetchPage(country, appId, page, sortBy) {
14 const url = `https://itunes.apple.com/${country}/rss/customerreviews/page=${page}/id=${appId}/sortby=${sortBy}/json`;
15 for (let attempt = 0; attempt < 5; attempt++) {
16 try {
17 const res = await fetch(url, { signal: AbortSignal.timeout(20000), headers: { 'user-agent': 'Mozilla/5.0 (compatible; apify-appstore-reviews/1.0)' } });
18 if (res.status === 400 || res.status === 404) return [];
19 if (res.status === 403 || res.status === 429 || res.status >= 500) { await sleep(1500 * 2 ** attempt); continue; }
20 if (!res.ok) return [];
21 const text = await res.text();
22 if (!text.trim()) return [];
23 const entry = JSON.parse(text)?.feed?.entry;
24 if (!entry) return [];
25 return (Array.isArray(entry) ? entry : [entry]).filter((e) => e['im:rating']);
26 } catch (err) {
27 if (attempt === 4) throw err;
28 await sleep(1000 * 2 ** attempt);
29 }
30 }
31 return [];
32}
33
34await Actor.init();
35try {
36 const input = (await Actor.getInput()) ?? {};
37 const { apps = [], maxReviewsPerCountry = 500, sortBy = 'mostrecent', sinceDate, minRating = 1, maxRating = 5 } = input;
38 let countries = (input.countries?.length ? input.countries : ['us']).map((c) => String(c).trim().toLowerCase());
39 if (countries.includes('all')) countries = ALL_COUNTRIES;
40 countries = [...new Set(countries.filter((c) => /^[a-z]{2}$/.test(c)))];
41
42 const appIds = [...new Set(apps.map(parseApp).filter(Boolean))];
43 if (!appIds.length) throw new Error('No valid app IDs found in "apps". Use an App Store URL or a numeric ID.');
44 const since = sinceDate ? new Date(sinceDate) : null;
45 const seen = new Set();
46 let total = 0;
47 let stop = false;
48
49 const jobs = [];
50 for (const appId of appIds) for (const country of countries) jobs.push({ appId, country });
51 log.info(`Apps: ${appIds.length}, countries: ${countries.length}, jobs: ${jobs.length}`);
52
53 const worker = async () => {
54 while (jobs.length && !stop) {
55 const { appId, country } = jobs.shift();
56 let count = 0;
57 try {
58 for (let page = 1; page <= 10 && count < maxReviewsPerCountry && !stop; page++) {
59 const entries = await fetchPage(country, appId, page, sortBy);
60 if (!entries.length) break;
61 let tooOld = 0;
62 const items = [];
63 for (const e of entries) {
64 if (count + items.length >= maxReviewsPerCountry) break;
65 const reviewId = lbl(e.id);
66 if (!reviewId || seen.has(reviewId)) continue;
67 const date = lbl(e.updated);
68 const rating = Number(lbl(e['im:rating']));
69 if (since && date && new Date(date) < since) { tooOld++; continue; }
70 if (rating < minRating || rating > maxRating) continue;
71 seen.add(reviewId);
72 items.push({
73 appId, country, reviewId, rating,
74 title: lbl(e.title),
75 text: lbl(e.content),
76 version: lbl(e['im:version']),
77 date: date ? new Date(date).toISOString() : null,
78 author: lbl(e.author?.name),
79 authorUrl: lbl(e.author?.uri),
80 helpfulVotes: Number(lbl(e['im:voteSum']) ?? 0),
81 totalVotes: Number(lbl(e['im:voteCount']) ?? 0),
82 appUrl: `https://apps.apple.com/${country}/app/id${appId}`,
83 scrapedAt: new Date().toISOString(),
84 });
85 }
86 if (items.length) {
87 const res = await Actor.pushData(items);
88 count += items.length; total += items.length;
89 if (res?.eventChargeLimitReached) { stop = true; log.warning('Max charge limit reached, stopping.'); }
90 }
91 if (since && sortBy === 'mostrecent' && tooOld === entries.length) break;
92 if (entries.length < 50) break;
93 await sleep(150);
94 }
95 } catch (err) {
96 log.warning(`Failed ${appId}/${country}: ${err.message}`);
97 }
98 if (count) log.info(`App ${appId} [${country}]: ${count} reviews`);
99 }
100 };
101 await Promise.all(Array.from({ length: Math.min(5, jobs.length) }, worker));
102 log.info(`Finished. ${total} reviews saved.`);
103} catch (err) {
104 await Actor.fail(String(err?.message ?? err));
105}
106await Actor.exit();