-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
487 lines (403 loc) · 19.6 KB
/
script.js
File metadata and controls
487 lines (403 loc) · 19.6 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
(function() {
let globalFollowers = [];
let globalFollowing = [];
async function analyzeConnections() {
console.log('analyzeConnections function called');
const username = document.getElementById('username').value.trim();
const pat = document.getElementById('pat').value.trim();
if (!username || !pat) {
showError('Please enter both username and PAT token');
return;
}
showLoading(true);
showError('');
hideResults();
try {
const headers = {
'Authorization': `token ${pat}`,
'Accept': 'application/vnd.github.v3+json'
};
// First verify the token by checking user details
try {
const userResponse = await fetch(`https://api.github.com/user`, { headers });
if (!userResponse.ok) {
throw new Error('Invalid PAT token or insufficient permissions');
}
} catch (error) {
throw new Error('Failed to validate PAT token. Please check your token.');
}
// Fetch followers and following lists
const [followers, following] = await Promise.all([
fetchGitHubData(`https://api.github.com/users/${username}/followers?per_page=100`, headers),
fetchGitHubData(`https://api.github.com/users/${username}/following?per_page=100`, headers)
]);
// Store the data globally
globalFollowers = followers;
globalFollowing = following;
// Process the data
const followersSet = new Set(followers.map(user => user.login));
const followingSet = new Set(following.map(user => user.login));
// Find mutual connections
const mutualConnections = followers.filter(user => followingSet.has(user.login));
const followersOnly = followers.filter(user => !followingSet.has(user.login));
const followingOnly = following.filter(user => !followersSet.has(user.login));
// Update UI
updateStats(followers.length, following.length, mutualConnections.length);
updateLists(mutualConnections, followersOnly, followingOnly);
showResults();
initializeListActions(); // Add this line
} catch (error) {
showError(error.message || 'An unexpected error occurred');
} finally {
showLoading(false);
}
}
async function fetchGitHubData(url, headers) {
let allData = [];
let currentUrl = url;
while (currentUrl) {
const response = await fetch(currentUrl, { headers });
if (response.status === 401) {
throw new Error('Invalid authentication token. Please check your PAT token.');
}
if (response.status === 403) {
throw new Error('API rate limit exceeded or insufficient permissions.');
}
if (response.status === 404) {
throw new Error('User not found. Please check the username.');
}
if (!response.ok) {
throw new Error(`GitHub API Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
allData = allData.concat(data);
// Check for pagination
const linkHeader = response.headers.get('Link');
currentUrl = null;
if (linkHeader) {
const nextLink = linkHeader.split(',').find(link => link.includes('rel="next"'));
if (nextLink) {
currentUrl = nextLink.split(';')[0].trim().slice(1, -1);
}
}
}
return allData;
}
function updateStats(followers, following, mutual) {
document.getElementById('followers-count').textContent = followers;
document.getElementById('following-count').textContent = following;
document.getElementById('mutual-count').textContent = mutual;
}
function updateLists(mutual, followersOnly, followingOnly) {
updateList('mutual-list', mutual);
updateList('followers-only-list', followersOnly);
updateList('following-only-list', followingOnly);
}
function updateList(elementId, users) {
const list = document.getElementById(elementId);
list.innerHTML = users
.map(user => `<li class="user-item">
<input type="checkbox" data-username="${user.login}">
<a href="${user.html_url}" target="_blank">
<img src="${user.avatar_url}" alt="${user.login}" width="25" height="25">
${user.login}
</a>
<span class="action-status"></span>
</li>`)
.join('');
}
// Add new functions for follow/unfollow functionality
async function followUser(username, headers) {
const response = await fetch(`https://api.github.com/user/following/${username}`, {
method: 'PUT',
headers
});
if (!response.ok) throw new Error('Failed to follow user');
}
async function unfollowUser(username, headers) {
const response = await fetch(`https://api.github.com/user/following/${username}`, {
method: 'DELETE',
headers
});
if (!response.ok) throw new Error('Failed to unfollow user');
}
function initializeListActions() {
// Handle select all checkboxes
document.querySelectorAll('.select-all').forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
const listId = e.target.dataset.list;
const listCheckboxes = document.querySelectorAll(`#${listId} input[type="checkbox"]`);
listCheckboxes.forEach(cb => cb.checked = e.target.checked);
});
});
// Handle follow/unfollow buttons
document.querySelectorAll('.follow-selected, .unfollow-selected').forEach(button => {
button.addEventListener('click', async (e) => {
const listId = e.target.dataset.list;
const selectedUsers = document.querySelectorAll(`#${listId} input[type="checkbox"]:checked`);
const headers = {
'Authorization': `token ${document.getElementById('pat').value.trim()}`,
'Accept': 'application/vnd.github.v3+json'
};
for (const checkbox of selectedUsers) {
const userItem = checkbox.closest('.user-item');
userItem.classList.add('processing');
try {
if (e.target.classList.contains('follow-selected')) {
await followUser(checkbox.dataset.username, headers);
updateFeedbackStatus(userItem, true, 'Following');
} else {
await unfollowUser(checkbox.dataset.username, headers);
updateFeedbackStatus(userItem, true, 'Unfollowed');
}
} catch (error) {
updateFeedbackStatus(userItem, false, 'Failed');
} finally {
userItem.classList.remove('processing');
checkbox.checked = false;
}
// Add delay between requests
await new Promise(resolve => setTimeout(resolve, 300));
}
});
});
}
async function getRecommendedUnfollows() {
const recommendedUnfollows = [];
const totalUsers = globalFollowing.length;
let processedUsers = 0;
updateLoadingMessage(`Starting analysis of ${totalUsers} users...`);
for (const user of globalFollowing) {
try {
// Get user's detailed information
const url = `https://api.github.com/users/${user.login}`;
console.log(`Fetching data for ${user.login} from: ${url}`);
const headers = {
'Authorization': `token ${document.getElementById('pat').value.trim()}`,
'Accept': 'application/vnd.github.v3+json'
};
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch user data: ${response.status}`);
}
const userDetails = await response.json();
// Debug information
console.log(`${user.login}:`, {
followers: userDetails.followers,
following: userDetails.following,
ratio: userDetails.following / (userDetails.followers || 1)
});
// Simpler ratio check
if (userDetails.followers === 0 || userDetails.following / userDetails.followers >= 2) {
console.log(`✓ Found match: ${user.login}`);
recommendedUnfollows.push({
...user,
followers: userDetails.followers,
following: userDetails.following,
ratio: userDetails.following / (userDetails.followers || 1)
});
}
processedUsers++;
updateLoadingMessage(`Analyzed ${processedUsers}/${totalUsers} users...`);
} catch (error) {
console.error(`Error analyzing ${user.login}:`, error);
processedUsers++;
}
// Smaller delay to avoid rate limits
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log('Analysis Results:', {
totalProcessed: processedUsers,
recommendedCount: recommendedUnfollows.length,
recommendations: recommendedUnfollows
});
return recommendedUnfollows;
}
async function showRecommendedUnfollows() {
console.log('showRecommendedUnfollows function called');
if (!globalFollowing.length) {
showError('Please analyze your connections first');
return;
}
showLoading(true);
showError('');
try {
const recommendedUnfollows = await getRecommendedUnfollows();
const list = document.getElementById('recommended-list');
if (recommendedUnfollows.length === 0) {
list.innerHTML = `
<li class="no-results">
<div>No recommended unfollows found</div>
<small>Criteria: Users who follow ≥ 2x more people than follow them</small>
<small>Or users with 0 followers</small>
</li>`;
} else {
list.innerHTML = recommendedUnfollows
.map(user => `<li class="user-item">
<input type="checkbox" data-username="${user.login}">
<a href="${user.html_url}" target="_blank">
<img src="${user.avatar_url}" alt="${user.login}" width="25" height="25">
${user.login}
</a>
<span class="user-stats">
Following/Followers: ${user.following}/${user.followers}
(Ratio: ${user.ratio.toFixed(1)})
</span>
<span class="action-status"></span>
</li>`)
.join('');
}
document.getElementById('recommended-unfollows').classList.remove('hidden');
initializeListActions();
} catch (error) {
console.error('Recommendation error:', error);
showError('Error: ' + error.message);
} finally {
showLoading(false);
}
}
async function getRecommendedFollowers(username, headers) {
const recommendedFollowers = [];
let processedUsers = 0;
let potentialFollows = [];
updateLoadingMessage(`Fetching potential users to follow...`);
try {
// Fetch followers of the current user
potentialFollows = await fetchGitHubData(`https://api.github.com/users/${username}/followers?per_page=100`, headers);
const totalPotentialFollows = potentialFollows.length;
updateLoadingMessage(`Analyzing followers of ${username} for potential follows...`);
// Create a set of your followers for quick lookup
const myFollowersSet = new Set(globalFollowers.map(f => f.login));
const myFollowingSet = new Set(globalFollowing.map(f => f.login));
for (const potentialFollow of potentialFollows) {
try {
// Fetch users that the current follower is following
const followingUrl = `https://api.github.com/users/${potentialFollow.login}/following?per_page=100`;
const usersFollowedByPotential = await fetchGitHubData(followingUrl, headers);
for (const user of usersFollowedByPotential) {
// Skip if user is already a follower OR is already being followed
if (myFollowersSet.has(user.login) || myFollowingSet.has(user.login)) {
console.log(`Skipping existing connection: ${user.login}`);
continue;
}
// Recommendation criteria: Following >= Followers
const userDetailsUrl = `https://api.github.com/users/${user.login}`;
const userDetailsResponse = await fetch(userDetailsUrl, { headers });
if (!userDetailsResponse.ok) {
console.warn(`Failed to fetch user data: ${userDetailsResponse.status}`);
continue;
}
const userDetails = await userDetailsResponse.json();
if (userDetails.following >= userDetails.followers) {
console.log(`✓ Found match: ${userDetails.login}`);
recommendedFollowers.push({
...user,
followers: userDetails.followers,
following: userDetails.following
});
}
}
processedUsers++;
updateLoadingMessage(`Analyzed ${processedUsers}/${totalPotentialFollows} users...`);
if (recommendedFollowers.length >= 50) {
console.log('Reached maximum recommendations, stopping analysis.');
break;
}
} catch (error) {
console.error(`Error analyzing ${potentialFollow.login}:`, error);
}
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log('Analysis Results:', {
totalProcessed: processedUsers,
recommendedCount: recommendedFollowers.length,
recommendations: recommendedFollowers
});
return recommendedFollowers;
} catch (error) {
showError('Error fetching recommended followers: ' + error.message);
return [];
}
}
async function showRecommendedFollowers() {
console.log('showRecommendedFollowers function called');
showLoading(true);
showError('');
try {
const username = document.getElementById('username').value.trim();
const pat = document.getElementById('pat').value.trim();
const headers = {
'Authorization': `token ${pat}`,
'Accept': 'application/vnd.github.v3+json'
};
const recommendedFollowers = await getRecommendedFollowers(username, headers);
const list = document.getElementById('recommended-followers-list');
if (recommendedFollowers.length === 0) {
list.innerHTML = `<li class="no-results">No recommended followers found.</li>`;
} else {
list.innerHTML = recommendedFollowers.map(user => `
<li class="user-item">
<input type="checkbox" data-username="${user.login}">
<a href="${user.html_url}" target="_blank">
<img src="${user.avatar_url}" alt="${user.login}" width="25" height="25">
${user.login}
</a>
<span class="user-stats">
Following: ${user.following} | Followers: ${user.followers}
</span>
<span class="action-status"></span>
</li>
`).join('');
}
document.getElementById('recommended-followers').classList.remove('hidden');
initializeListActions();
} catch (error) {
showError('Error: ' + error.message);
} finally {
showLoading(false);
}
}
function updateLoadingMessage(message) {
const loadingElement = document.getElementById('loading');
loadingElement.textContent = message;
}
function showLoading(show) {
document.getElementById('loading').classList.toggle('hidden', !show);
}
function showError(message) {
const error = document.getElementById('error');
error.textContent = message;
error.classList.toggle('hidden', !message);
}
function showResults() {
document.getElementById('results').classList.remove('hidden');
}
function hideResults() {
document.getElementById('results').classList.add('hidden');
}
function updateFeedbackStatus(element, isSuccess, message) {
const statusElement = element.querySelector('.action-status');
statusElement.innerHTML = isSuccess ?
`<i class="fas fa-check-circle"></i> ${message}` :
`<i class="fas fa-times-circle"></i> ${message}`;
statusElement.className = 'action-status';
statusElement.classList.add(isSuccess ? 'success' : 'error');
statusElement.classList.add('show');
// Remove the status after 5 seconds
setTimeout(() => {
statusElement.classList.remove('show');
}, 5000);
}
document.addEventListener('DOMContentLoaded', () => {
const analyzeButton = document.getElementById('analyzeButton');
const showUnfollowsButton = document.getElementById('showUnfollowsButton');
const showFollowersButton = document.getElementById('showFollowersButton');
console.log('DOMContentLoaded event fired');
analyzeButton.addEventListener('click', analyzeConnections);
console.log('analyzeButton event listener attached');
showUnfollowsButton.addEventListener('click', showRecommendedUnfollows);
console.log('showUnfollowsButton event listener attached');
showFollowersButton.addEventListener('click', showRecommendedFollowers);
console.log('showFollowersButton event listener attached');
});
})();