-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathfetch_apify_actors.js
More file actions
277 lines (231 loc) · 8.88 KB
/
fetch_apify_actors.js
File metadata and controls
277 lines (231 loc) · 8.88 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
/**
* Script to fetch all Apify Actors from the API and compile them into a list
* with affiliate links.
*/
const https = require('https');
const fs = require('fs');
const path = require('path');
const API_BASE_URL = 'api.apify.com';
const AFFILIATE_PARAM = '?fpr=p2hrc6';
/**
* Make HTTP GET request
*/
function makeRequest(url, path) {
return new Promise((resolve, reject) => {
const options = {
hostname: url,
path: path,
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const jsonData = JSON.parse(data);
resolve(jsonData);
} catch (e) {
reject(new Error(`Failed to parse JSON: ${e.message}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
req.end();
});
}
/**
* Fetch all actors from Apify Store API with pagination
*/
async function fetchAllActors(limit = 100) {
const allActors = [];
let offset = 0;
let totalFetched = 0;
console.log('Starting to fetch Apify Actors...');
console.log('='.repeat(60));
while (true) {
try {
const path = `/v2/store?limit=${limit}&offset=${offset}`;
console.log(`Fetching actors at offset ${offset}...`);
const data = await makeRequest(API_BASE_URL, path);
// Extract actors from response
const actors = data?.data?.items || [];
if (!actors || actors.length === 0) {
console.log(`No more actors found at offset ${offset}`);
break;
}
// Process each actor
for (const actor of actors) {
const actorInfo = {
name: actor.name || 'Unknown',
username: actor.username || '',
title: actor.title || actor.name || 'Unknown',
description: actor.description || '',
url: actor.url || '',
affiliate_url: '',
stats: actor.stats || {},
categories: actor.categories || [],
createdAt: actor.createdAt || '',
modifiedAt: actor.modifiedAt || ''
};
// Create affiliate URL
if (actorInfo.url) {
// Check if URL already has query parameters
const separator = actorInfo.url.includes('?') ? '&' : '?';
actorInfo.affiliate_url = `${actorInfo.url}${separator}fpr=p2hrc6`;
} else {
// Construct URL from username and name if URL is missing
if (actorInfo.username && actorInfo.name) {
actorInfo.url = `https://apify.com/${actorInfo.username}/${actorInfo.name}`;
actorInfo.affiliate_url = `${actorInfo.url}?fpr=p2hrc6`;
}
}
allActors.push(actorInfo);
}
totalFetched += actors.length;
const totalCount = data?.data?.total || 0;
console.log(`Fetched ${totalFetched} actors so far... (Total available: ${totalCount})`);
// Check if we've reached the end
if (offset + actors.length >= totalCount) {
console.log(`Reached end. Total actors: ${totalCount}`);
break;
}
offset += limit;
// Be respectful with API rate limits
await new Promise(resolve => setTimeout(resolve, 500));
} catch (error) {
console.error(`Error fetching actors at offset ${offset}: ${error.message}`);
console.log('Retrying in 5 seconds...');
await new Promise(resolve => setTimeout(resolve, 5000));
continue;
}
}
console.log(`\nTotal actors fetched: ${allActors.length}`);
return allActors;
}
/**
* Save actors data to JSON file
*/
function saveToJSON(actors, filename = 'apify_actors.json') {
const filePath = path.join(__dirname, '..', filename);
fs.writeFileSync(filePath, JSON.stringify(actors, null, 2), 'utf-8');
console.log(`Saved ${actors.length} actors to ${filename}`);
}
/**
* Generate a markdown file with all actors and affiliate links
*/
function generateMarkdownList(actors, filename = 'APIFY_ACTORS.md') {
let content = `# Apify Actors List\n\n`;
content += `Complete list of ${actors.length} Apify Actors (APIs) available on the Apify platform.\n\n`;
content += `---\n\n`;
// Group by category if available
const actorsByCategory = {};
const uncategorized = [];
for (const actor of actors) {
const categories = actor.categories || [];
if (categories.length > 0) {
for (const category of categories) {
if (!actorsByCategory[category]) {
actorsByCategory[category] = [];
}
actorsByCategory[category].push(actor);
}
} else {
uncategorized.push(actor);
}
}
// Write categorized actors
const sortedCategories = Object.keys(actorsByCategory).sort();
for (const category of sortedCategories) {
content += `## ${category}\n\n`;
const sortedActors = actorsByCategory[category].sort((a, b) =>
(a.title || '').localeCompare(b.title || '')
);
for (const actor of sortedActors) {
const title = actor.title || actor.name || 'Unknown';
const affiliateUrl = actor.affiliate_url || actor.url || '';
const description = actor.description || '';
if (description) {
content += `- **[${title}](${affiliateUrl})** - ${description}\n`;
} else {
content += `- **[${title}](${affiliateUrl})**\n`;
}
}
content += '\n';
}
// Write uncategorized actors
if (uncategorized.length > 0) {
content += `## Uncategorized\n\n`;
const sortedUncategorized = uncategorized.sort((a, b) =>
(a.title || '').localeCompare(b.title || '')
);
for (const actor of sortedUncategorized) {
const title = actor.title || actor.name || 'Unknown';
const affiliateUrl = actor.affiliate_url || actor.url || '';
const description = actor.description || '';
if (description) {
content += `- **[${title}](${affiliateUrl})** - ${description}\n`;
} else {
content += `- **[${title}](${affiliateUrl})**\n`;
}
}
content += '\n';
}
content += `---\n\n`;
content += `*Total: ${actors.length} Actors*\n`;
content += `*Last updated: ${new Date().toISOString().split('T')[0]} ${new Date().toTimeString().split(' ')[0]}*\n`;
const filePath = path.join(__dirname, '..', filename);
fs.writeFileSync(filePath, content, 'utf-8');
console.log(`Generated markdown list: ${filename}`);
}
/**
* Generate a simple text file with just names and affiliate URLs
*/
function generateSimpleList(actors, filename = 'apify_actors_simple.txt') {
const sortedActors = actors.sort((a, b) =>
(a.title || '').localeCompare(b.title || '')
);
const lines = sortedActors.map(actor => {
const title = actor.title || actor.name || 'Unknown';
const affiliateUrl = actor.affiliate_url || actor.url || '';
return `${title}|${affiliateUrl}`;
});
const filePath = path.join(__dirname, '..', filename);
fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
console.log(`Generated simple list: ${filename}`);
}
// Main execution
async function main() {
console.log('='.repeat(60));
console.log('Apify Actors Fetcher');
console.log('='.repeat(60));
console.log();
try {
// Fetch all actors
const actors = await fetchAllActors(100);
if (actors.length > 0) {
// Save to JSON
saveToJSON(actors, 'apify_actors.json');
// Generate markdown list
generateMarkdownList(actors, 'APIFY_ACTORS.md');
// Generate simple list
generateSimpleList(actors, 'apify_actors_simple.txt');
console.log('\n' + '='.repeat(60));
console.log('Done! All files have been generated.');
console.log('='.repeat(60));
} else {
console.log('No actors were fetched. Please check the API connection.');
}
} catch (error) {
console.error('Fatal error:', error);
process.exit(1);
}
}
// Run the script
main();