1import { Actor, log } from 'apify';
2import { PlaywrightCrawler } from 'crawlee';
3
4import { buildLexicon } from './sentiment.js';
5import { findVideoObjects, findCommentObjects, findUserObjects, normalizeVideo, normalizeComment, normalizeUser } from './extract.js';
6import { detectSponsorship, buildCampaigns } from './sponsor.js';
7import { analyzeCreator, scoreCreator, relevanceOf, OBJECTIVES } from './metrics.js';
8import { createAi } from './ai.js';
9import { renderReport } from './report.js';
10import { sendWebhook } from './webhook.js';
11
12const EVENTS = { influencer: 'influencer-analyzed', comments: 'comment-sample', ai: 'ai-insight', discovery: 'creator-discovery' };
13const BASE = (process.env.TIKTOK_BASE_URL || 'https://www.tiktok.com').replace(/\/$/, '');
14const API_PATTERNS = ['/api/challenge/item_list', '/api/search/general/full', '/api/search/item/full', '/api/search/video/full', '/api/post/item_list',
15 '/api/recommend/item_list', '/api/related/item_list', '/api/comment/list', '/api/item/detail', '/api/user/detail'];
16
17const clean = (arr) => [...new Set((arr ?? []).map((s) => String(s ?? '').trim()).filter(Boolean))];
18const clamp = (n, lo, hi, def) => Math.max(lo, Math.min(hi, Number.isFinite(+n) ? +n : def));
19const uniqueById = (arr, idFn) => { const m = new Map(); for (const a of arr) { const id = idFn(a); if (id && !m.has(id)) m.set(id, a); } return [...m.values()]; };
20
21
22const captured = new WeakMap();
23async function readRehydration(page) {
24 try {
25 const raw = await page.evaluate(() => document.querySelector('#__UNIVERSAL_DATA_FOR_REHYDRATION__')?.textContent ?? null);
26 return raw ? JSON.parse(raw) : null;
27 } catch { return null; }
28}
29async function isBlocked(page) {
30 try {
31 return await page.evaluate(() => {
32 const visible = (el) => { const r = el.getBoundingClientRect(); const st = getComputedStyle(el); return r.width > 50 && r.height > 50 && st.visibility !== 'hidden' && st.display !== 'none'; };
33 const t = (document.body?.innerText ?? '').slice(0, 3000).toLowerCase();
34 const captcha = [...document.querySelectorAll('#captcha-verify-container, .captcha-verify-container, [class*="captcha_verify"]')].some(visible);
35 return captcha || t.includes('verify to continue') || t.includes('access denied');
36 });
37 } catch { return false; }
38}
39async function dismissConsent(page) {
40 for (const sel of ['button:has-text("Accept all")', 'button:has-text("Allow all")', 'button:has-text("Decline optional cookies")']) {
41 try { await page.locator(sel).first().click({ timeout: 1200 }); break; } catch { }
42 }
43}
44async function scrollUntil(page, { count, target, maxRounds }) {
45 let last = -1;
46 let stagnant = 0;
47 for (let i = 0; i < maxRounds; i++) {
48 const n = count();
49 if (n >= target) return;
50 if (n === last) { if (++stagnant >= 3) return; } else { stagnant = 0; last = n; }
51 await page.mouse.wheel(0, 2200);
52 await page.waitForTimeout(Number(process.env.SCROLL_WAIT_MS || 1400) + Math.random() * 600);
53 }
54}
55
56function makeCrawler({ proxyConfiguration, handler, maxConcurrency = 2, maxRequestRetries = 3 }) {
57 return new PlaywrightCrawler({
58 proxyConfiguration,
59 useSessionPool: true,
60 persistCookiesPerSession: true,
61 maxConcurrency,
62 maxRequestRetries,
63 navigationTimeoutSecs: 60,
64 requestHandlerTimeoutSecs: 240,
65 launchContext: { launchOptions: { headless: process.env.TSI_HEADFUL !== '1', args: ['--disable-blink-features=AutomationControlled'] } },
66 browserPoolOptions: { useFingerprints: !process.env.TIKTOK_BASE_URL },
67 preNavigationHooks: [
68 async ({ page }) => {
69 const bucket = [];
70 captured.set(page, bucket);
71 page.on('response', async (res) => {
72 if (!API_PATTERNS.some((p) => res.url().includes(p))) return;
73 try { bucket.push(await res.json()); } catch { }
74 });
75
76 await page.route('**/*', (route) => (['image', 'media', 'font'].includes(route.request().resourceType()) ? route.abort() : route.continue()));
77 },
78 ],
79 async requestHandler(ctx) {
80 const { page, session } = ctx;
81 await page.waitForLoadState('domcontentloaded');
82 await page.waitForTimeout(Number(process.env.PAGE_WAIT_MS || 2500));
83 if (await isBlocked(page)) { session?.retire(); throw new Error('Blocked or captcha challenge; retrying with a new session/IP.'); }
84 await dismissConsent(page);
85 await handler({ ...ctx, bucket: captured.get(page) ?? [] });
86 },
87 failedRequestHandler({ request }, error) {
88 log.warning(`Failed after retries: ${request.url} :: ${error?.message ?? 'unknown error'}`);
89 request.userData.onFail?.(error);
90 },
91 });
92}
93
94
95await Actor.init();
96try {
97 const startedAt = new Date().toISOString();
98 const input = (await Actor.getInput()) ?? {};
99 const hashtags = clean(input.hashtags).map((h) => h.replace(/^#/, '').toLowerCase());
100 const keywords = clean(input.keywords);
101 const explicit = clean(input.influencers).map((u) => u.replace(/^@/, '').replace(/^https?:\/\/(www\.)?tiktok\.com\/@/i, '').split(/[/?]/)[0].toLowerCase());
102 const exclude = new Set(clean(input.excludeInfluencers).map((u) => u.replace(/^@/, '').toLowerCase()));
103 const brands = clean(input.brands).map((b) => b.replace(/^[@#]/, '').toLowerCase());
104 if (!hashtags.length && !keywords.length && !explicit.length) throw new Error('Add at least one hashtag, keyword or influencer handle.');
105 const objective = OBJECTIVES[input.objective] ? input.objective : 'balanced';
106 const videosPerQuery = clamp(input.videosPerQuery, 5, 300, 40);
107 const maxInfluencers = clamp(input.maxInfluencers, 1, 200, 15);
108 const minFollowers = clamp(input.minFollowers, 0, 1e9, 1000);
109 const maxFollowers = clamp(input.maxFollowers, 0, 1e10, 0);
110 const recentVideos = clamp(input.recentVideosPerInfluencer, 5, 60, 20);
111 const commentVideos = clamp(input.commentVideosPerInfluencer, 0, 10, 2);
112 const commentsPerVideo = clamp(input.commentsPerVideo, 5, 200, 30);
113 const cpm = [clamp(input.cpmLowUsd, 0, 1000, 2), clamp(input.cpmHighUsd, 0, 1000, 10)].sort((a, b) => a - b);
114 const terms = [...hashtags.map((h) => `#${h}`), ...hashtags, ...keywords];
115 const lexicon = buildLexicon(clean(input.customPositiveWords), clean(input.customNegativeWords));
116
117
118 const charging = Actor.getChargingManager();
119 const isPPE = Boolean(charging.getPricingInfo?.().isPayPerEvent);
120 const affordable = (e) => { if (!isPPE) return Infinity; try { return charging.calculateMaxEventChargeCountWithinLimit(e); } catch { return Infinity; } };
121 const charge = async (eventName, count = 1) => { if (isPPE && count) await Actor.charge({ eventName, count }).catch((e) => log.debug(e.message)); };
122
123 const chargedCreators = new Set();
124 let budgetHit = false;
125 let chargeQueue = Promise.resolve();
126 const serial = (fn) => { const p = chargeQueue.then(fn); chargeQueue = p.catch(() => {}); return p; };
127
128 const chargeCreator = (username) => serial(async () => {
129 if (!isPPE || chargedCreators.has(username)) return true;
130 if (affordable(EVENTS.influencer) < 1) { budgetHit = true; return false; }
131 chargedCreators.add(username);
132 await charge(EVENTS.influencer);
133 return true;
134 });
135 const chargeComment = () => serial(async () => {
136 if (!isPPE) return true;
137 if (affordable(EVENTS.comments) < 1) { budgetHit = true; return false; }
138 await charge(EVENTS.comments);
139 return true;
140 });
141
142
143 const timeoutAt = Date.parse(process.env.ACTOR_TIMEOUT_AT || process.env.APIFY_TIMEOUT_AT || '') || null;
144 const reserveMs = timeoutAt ? Math.max(60e3, Math.min(180e3, (timeoutAt - Date.now()) * 0.12)) : 0;
145 const timeLeft = () => (timeoutAt ? timeoutAt - Date.now() - reserveMs : Infinity);
146 let stoppedEarly = null;
147 const stopCrawler = (crawler, reason) => {
148 if (!stoppedEarly) { stoppedEarly = reason; log.warning(`Stopping early: ${reason}. Results collected so far will be ranked and saved.`); }
149 try { if (typeof crawler.stop === 'function') crawler.stop(reason); else crawler.autoscaledPool?.abort(); } catch { }
150 };
151 const guard = (crawler, deadline, label) => setInterval(() => {
152 if (Date.now() >= deadline() || timeLeft() <= 0) stopCrawler(crawler, `time limit reached during ${label}`);
153 else if (budgetHit) stopCrawler(crawler, 'maximum cost per run reached');
154 }, 3000);
155
156 const proxyConfiguration = await Actor.createProxyConfiguration(input.proxyConfiguration ?? { useApifyProxy: true, apifyProxyGroups: ['RESIDENTIAL'] });
157 if (!proxyConfiguration) log.warning('No proxy configured: TikTok will likely block this run. Residential proxies are recommended.');
158
159
160 const candidates = new Map();
161 const discoveryStats = { videos: 0, queries: {} };
162 if (hashtags.length || keywords.length) {
163 await Actor.setStatusMessage(`Discovering creators for ${[...hashtags.map((h) => `#${h}`), ...keywords].join(', ')}…`);
164 const crawler = makeCrawler({
165 proxyConfiguration,
166 maxConcurrency: 2,
167 maxRequestRetries: 2,
168 async handler({ page, request, bucket }) {
169 const gather = async () => uniqueById([...findVideoObjects(await readRehydration(page)), ...bucket.flatMap(findVideoObjects)].map(normalizeVideo).filter(Boolean), (v) => v.id);
170 let found = await gather();
171 if (found.length < videosPerQuery) {
172 await scrollUntil(page, { count: () => uniqueById(bucket.flatMap(findVideoObjects).map(normalizeVideo).filter(Boolean), (v) => v.id).length || found.length,
173 target: videosPerQuery, maxRounds: Math.min(40, Math.ceil(videosPerQuery / 5) + 4) });
174 found = await gather();
175 }
176 found = found.slice(0, videosPerQuery);
177 discoveryStats.queries[request.userData.query] = found.length;
178 if (found.length) await charge(EVENTS.discovery);
179 discoveryStats.videos += found.length;
180 for (const v of found) {
181 if (!v.username) continue;
182 const c = candidates.get(v.username) || { username: v.username, nicheVideos: [], author: v.author, queries: new Set() };
183 if (!c.nicheVideos.some((x) => x.id === v.id)) c.nicheVideos.push(v);
184 c.author = { ...c.author, ...Object.fromEntries(Object.entries(v.author || {}).filter(([, x]) => x !== null)) };
185 c.queries.add(request.userData.query);
186 candidates.set(v.username, c);
187 }
188 log.info(`${request.userData.query}: ${found.length} videos, ${candidates.size} creators so far.`);
189 },
190 });
191
192 const discoveryDeadline = timeoutAt ? Date.now() + (timeoutAt - Date.now() - reserveMs) * 0.4 : Infinity;
193 const t1 = guard(crawler, () => discoveryDeadline, 'creator discovery');
194 await crawler.run([
195 ...hashtags.map((h) => ({ url: `${BASE}/tag/${encodeURIComponent(h)}`, uniqueKey: `tag:${h}`, userData: { query: `#${h}` } })),
196 ...keywords.map((q) => ({ url: `${BASE}/search/video?q=${encodeURIComponent(q)}`, uniqueKey: `kw:${q}`, userData: { query: q } })),
197 ]);
198 clearInterval(t1);
199 }
200
201
202 const filteredOut = { followers: 0, excluded: 0 };
203 const ranked = [...candidates.values()].filter((c) => {
204 if (exclude.has(c.username) || explicit.includes(c.username)) { if (exclude.has(c.username)) filteredOut.excluded++; return false; }
205 const f = c.author?.followers;
206 if (f !== null && f !== undefined && (f < minFollowers || (maxFollowers && f > maxFollowers))) { filteredOut.followers++; return false; }
207 return true;
208 }).sort((a, b) => (b.nicheVideos.length - a.nicheVideos.length) || (b.nicheVideos.reduce((s, v) => s + v.plays, 0) - a.nicheVideos.reduce((s, v) => s + v.plays, 0)));
209 const budget = Math.min(maxInfluencers, affordable(EVENTS.influencer));
210 const selected = [...explicit.filter((u) => !exclude.has(u)), ...ranked.map((c) => c.username)].slice(0, budget);
211 if (!selected.length) throw new Error(`No creators found to analyse (${discoveryStats.videos} videos discovered; ${filteredOut.followers} creators outside the follower range). Try other hashtags or widen the follower range.`);
212 log.info(`Analysing ${selected.length} creators: ${selected.map((u) => `@${u}`).join(', ')}`);
213
214
215 const data = new Map(selected.map((u) => [u, { username: u, profile: null, videos: [], comments: [], nicheVideos: candidates.get(u)?.nicheVideos || [], fallbackFollowers: candidates.get(u)?.author?.followers ?? null, commentVideos: 0, status: 'pending' }]));
216 await Actor.setStatusMessage(`Analysing ${selected.length} creator profiles…`);
217 const crawler2 = makeCrawler({
218 proxyConfiguration,
219 maxConcurrency: 3,
220 async handler({ page, request, bucket, crawler: c }) {
221 const d = data.get(request.userData.username);
222 if (request.userData.label === 'PROFILE') {
223 if (isPPE && affordable(EVENTS.influencer) < 1) { budgetHit = true; d.status = 'skipped_budget'; return; }
224 const readAll = async () => {
225 const re = await readRehydration(page);
226 const users = [...findUserObjects(re), ...bucket.flatMap(findUserObjects)].map(normalizeUser).filter(Boolean);
227 const vids = uniqueById([...findVideoObjects(re), ...bucket.flatMap(findVideoObjects)].map(normalizeVideo).filter(Boolean), (v) => v.id);
228 return { user: users.find((u) => u.username === d.username) || null, vids: vids.filter((v) => !v.username || v.username === d.username) };
229 };
230 let { user, vids } = await readAll();
231 if (vids.length < recentVideos) {
232 await scrollUntil(page, { count: () => uniqueById(bucket.flatMap(findVideoObjects), (v) => v.id ?? v.aweme_id).length || vids.length, target: recentVideos, maxRounds: Math.ceil(recentVideos / 6) + 3 });
233 ({ user, vids } = await readAll());
234 }
235 if (!user && !vids.length) throw new Error('Profile page contained no data');
236 d.profile = user;
237 d.videos = vids.map((v) => ({ ...v, username: d.username })).slice(0, recentVideos);
238 d.status = user ? 'ok' : 'videos_only';
239
240 if (!(await chargeCreator(d.username))) { d.status = 'skipped_budget'; return; }
241
242 if (commentVideos > 0 && affordable(EVENTS.comments) >= 1) {
243 const ordered = [...d.videos].sort((a, b) => Number(detectSponsorship(b, brands).sponsored) - Number(detectSponsorship(a, brands).sponsored) || (b.createdAt || '').localeCompare(a.createdAt || ''));
244 await c.addRequests(ordered.filter((v) => v.comments > 0).slice(0, commentVideos).map((v) => ({
245 url: `${BASE}/@${d.username}/video/${v.id}`, uniqueKey: `video:${v.id}`, userData: { label: 'VIDEO', username: d.username, video: v },
246 })));
247 }
248 log.info(`@${d.username}: ${user ? `${user.followers.toLocaleString('en')} followers, ` : ''}${d.videos.length} recent videos.`);
249 return;
250 }
251
252 const video = request.userData.video;
253 try { await page.locator('[data-e2e="comment-icon"]').first().click({ timeout: 3000 }); } catch { }
254 const read = async () => uniqueById([...findCommentObjects(await readRehydration(page)), ...bucket.flatMap(findCommentObjects)].map((r) => normalizeComment(r, video)).filter(Boolean), (x) => x.id);
255 await scrollUntil(page, { count: () => uniqueById(bucket.flatMap(findCommentObjects), (x) => x.cid).length, target: commentsPerVideo, maxRounds: Math.ceil(commentsPerVideo / 8) + 3 });
256 const got = (await read()).filter((x) => x.username !== d.username).slice(0, commentsPerVideo);
257 if (got.length && (await chargeComment())) {
258 d.comments.push(...got);
259 d.commentVideos++;
260 }
261 log.info(`@${d.username} video ${video.id}: ${got.length} comments.`);
262 },
263 });
264 const t2 = guard(crawler2, () => Infinity, 'profile analysis');
265 await crawler2.run(selected.map((u) => ({ url: `${BASE}/@${u}`, uniqueKey: `profile:${u}`, userData: { label: 'PROFILE', username: u } })));
266 clearInterval(t2);
267
268
269 const results = [];
270 for (const d of data.values()) {
271 if (d.status === 'skipped_budget') continue;
272 if (!d.profile && !d.videos.length && !d.nicheVideos.length) { d.status = 'failed'; continue; }
273 if (d.status === 'pending') d.status = 'discovery_only';
274 if (!(await chargeCreator(d.username))) { d.status = 'skipped_budget'; continue; }
275 const m = analyzeCreator(d, { terms, brands, lexicon, cpmRangeUsd: cpm });
276 Object.assign(m, scoreCreator(m, objective), { profile_status: d.status, comment_videos_sampled: d.commentVideos });
277 results.push(m);
278 }
279 results.sort((a, b) => b.influencer_score - a.influencer_score);
280 results.forEach((m, i) => { m.rank = i + 1; });
281 const allPosts = results.flatMap((m) => m._posts);
282 const campaigns = buildCampaigns(allPosts.filter((p) => p.sponsorship.sponsored || p.sponsorship.brands.some((b) => brands.includes(b))));
283
284
285 let comparison = null;
286 const aiStats = { enabled: Boolean(input.enableAi), insights: 0, failures: 0 };
287 if (input.enableAi) {
288 if (!input.aiApiKey && !/localhost|127\.0\.0\.1/.test(input.aiBaseUrl || '')) {
289 log.warning('AI insights skipped: add your API key in "AI API key".');
290 aiStats.skipped = 'no API key';
291 } else {
292 await Actor.setStatusMessage('Writing AI insights…');
293 const ai = createAi({ baseUrl: input.aiBaseUrl, apiKey: input.aiApiKey, model: input.aiModel || 'gpt-4o-mini', log });
294 const top = results.slice(0, Math.min(clamp(input.aiMaxInfluencers, 1, 50, 10), affordable(EVENTS.ai)));
295 try {
296 for (const m of top) {
297 const insight = await ai.influencerInsight(m, { brief: input.campaignBrief, brandName: input.brandName });
298 if (insight) { m.ai_insight = insight; aiStats.insights++; }
299 }
300 comparison = await ai.comparison(results, { brief: input.campaignBrief });
301 } catch (e) {
302 log.warning(`AI disabled for this run: ${e.message}`);
303 aiStats.error = e.message;
304 }
305 aiStats.failures = ai.failures;
306 }
307 }
308
309
310 const finishedAt = new Date().toISOString();
311 const rows = results.map(({ _posts, ...m }) => ({
312 ...m,
313 recent_posts: _posts.slice(0, 10).map((p) => ({ url: p.url, created_at: p.createdAt, views: p.plays, likes: p.likes, comments: p.comments, shares: p.shares,
314 sponsored: p.sponsorship.sponsored, sponsor_signals: p.sponsorship.signals, brands: p.sponsorship.brands, outperformed: p.outperformed, caption: String(p.text).slice(0, 160) })),
315 objective,
316 discovered_via: [...(candidates.get(m.username)?.queries || [])],
317 analyzed_at: finishedAt,
318 }));
319 await Actor.pushData(rows);
320 await charge(EVENTS.ai, aiStats.insights);
321
322 await Actor.setValue('CAMPAIGNS', campaigns);
323 await Actor.setValue('POSTS', allPosts.map((p) => ({ username: p.username, id: p.id, url: p.url, created_at: p.createdAt, views: p.plays, likes: p.likes, comments: p.comments, shares: p.shares, saves: p.saves,
324 engagement_rate: p.plays ? Math.round(((p.likes + p.comments + p.shares + p.saves) / p.plays) * 10000) / 10000 : null, hashtags: p.hashtags, on_topic: Boolean(relevanceOf(p, terms)),
325 sponsored: p.sponsorship.sponsored, sponsor_confidence: p.sponsorship.confidence, sponsor_signals: p.sponsorship.signals, brands: p.sponsorship.brands, outperformed: p.outperformed,
326 audience_sentiment: p.audienceSentiment, caption: p.text })));
327 if (comparison) await Actor.setValue('AI_RECOMMENDATION', comparison);
328 const meta = { queries: [...hashtags.map((h) => `#${h}`), ...keywords, ...explicit.map((u) => `@${u}`)].join(', '), objective, finishedAt };
329 await Actor.setValue('REPORT', renderReport({ ranked: results, campaigns, comparison, meta }), { contentType: 'text/html; charset=utf-8' });
330 const summary = {
331 startedAt, finishedAt, objective, discovery: { ...discoveryStats, creatorsFound: candidates.size, filteredOut }, analysed: results.length,
332 failedProfiles: [...data.values()].filter((d) => d.status === 'failed').map((d) => d.username),
333 top: results.slice(0, 10).map((m) => ({ rank: m.rank, username: m.username, score: m.influencer_score, tier: m.tier, followers: m.followers })),
334 campaigns: campaigns.slice(0, 10).map((c) => ({ brand: c.brand, creators: c.creators, posts: c.posts, total_views: c.total_views, success_rate: c.success_rate })),
335 ai: aiStats,
336 stoppedEarly,
337 skippedForBudget: [...data.values()].filter((d) => d.status === 'skipped_budget').map((d) => d.username),
338 };
339 await Actor.setValue('SUMMARY', summary);
340
341 if (input.webhookUrl) {
342 const env = Actor.getEnv();
343 const links = { report: `https://api.apify.com/v2/key-value-stores/${env.defaultKeyValueStoreId}/records/REPORT`, dataset: `https://api.apify.com/v2/datasets/${env.defaultDatasetId}/items?format=json` };
344 const res = await sendWebhook({ url: input.webhookUrl, secret: input.webhookSecret, log, links, summary: {
345 event: 'tiktok-influencer-scout.run.finished',
346 headline: `TikTok influencer shortlist for ${meta.queries}: ${results.length} creators ranked (${objective}).`,
347 lines: results.slice(0, 5).map((m) => `#${m.rank} @${m.username}: score ${m.influencer_score}, ${m.followers?.toLocaleString('en') ?? '?'} followers, ${m.estimated_response_speed}`),
348 data: summary } });
349 await Actor.setValue('WEBHOOK_RESULT', res);
350 }
351 await Actor.setStatusMessage(`Done: ${results.length} creators ranked. Top: ${results.slice(0, 3).map((m) => `@${m.username} (${m.influencer_score})`).join(', ')}. ${campaigns.length} brand campaigns detected.`);
352 await Actor.exit();
353} catch (err) {
354 log.exception(err, 'Run failed');
355 await Actor.fail(err.message);
356}