Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nikelborm committed May 8, 2024
0 parents commit 8103768
Show file tree
Hide file tree
Showing 24 changed files with 1,374 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Release Workflow
on:
push:
branches: [ main ]

jobs:
build:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v3
-
name: 'Deps: Install'
run: |
npm install
-
name: 'Build'
run: |
./node_modules/.bin/ncc build ./index.js -o ./dist --no-source-map-register --minify --no-cache
-
name: 'Release: Upload'
uses: softprops/action-gh-release@v1
with:
tag_name: latest-${{github.sha}}
fail_on_unmatched_files: true
files: |
./dist/index.js
./template.env
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.env
config.json
cache.json
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"json.maxItemsComputed": 100,
"editor.foldingMaximumRegions": 100,
"indentRainbow.excludedLanguages": [
"json"
]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 @nikelborm

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Find communities around you
4 changes: 4 additions & 0 deletions cache.template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"resolvedFriendGraphNodes": [],
"resolvedFriendships": []
}
8 changes: 8 additions & 0 deletions config.template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"userAccessToken": null,
"previouslyAskedToSearchForUserIds": [],
"notInterestedInUserIdsOrNicknames": [],
"unresolvedNicknamesAndIdsOfPeopleToSearchFor": ["nickname", "id1"],
"resolvedFriendGraphNodes": [],
"resolvedFriendships": []
}
128 changes: 128 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// @ts-check
'use strict';

import open from 'open';
import prompts from 'prompts';
import {
ZodCacheSchema,
ZodConfigSchema,
readJsonFile,
writeJsonFile,
updateUserAccessTokenIn,
canUserBePotentialFriend,
fetchUnresolvedUsers,
FriendsGraph,
} from './src/index.js';

let [ config, cache ] = await Promise.all([
readJsonFile('./config.json', ZodConfigSchema),
readJsonFile('./cache.json', ZodCacheSchema),
]);

const saveConfig = async () => await writeJsonFile('./config.json', config, ZodConfigSchema);
const saveCacheAndConfig = async () => await Promise.all([
saveConfig(),
writeJsonFile('./cache.json', cache, ZodCacheSchema),
]);

// if (!process.env.VK_SERVICE_KEY)
// throw new Error('VK_SERVICE_KEY is not defined');
// const vkAccessToken = process.env.VK_SERVICE_KEY;
const vkAccessToken = await updateUserAccessTokenIn(config);

globalLoop: while(true) {
const {
userIdToUserMap,
usersWithFriends,
} = await fetchUnresolvedUsers(
vkAccessToken,
config.unresolvedNicknamesAndIdsOfPeopleToSearchFor
);

config.unresolvedNicknamesAndIdsOfPeopleToSearchFor = [];
config.previouslyAskedToSearchForUserIds.push(
...usersWithFriends.map(({ userId }) => userId)
);

userIdToUserMap.fillWith(cache.resolvedFriendGraphNodes);

const friendsGraph = new FriendsGraph();

friendsGraph.addUsers(userIdToUserMap.getAllUsers());
friendsGraph.addFriendShips(cache.resolvedFriendships);

for (const { friendships } of usersWithFriends) {
friendsGraph.addFriendShips(friendships());
}


// manually extracting edges from graphology graph is the best way to avoid duplicates in edge cache
// manually extracting nodes from userIdToUserMap is the best way to avoid duplicates in node cache
cache.resolvedFriendGraphNodes = [...userIdToUserMap.getAllUsers()];
cache.resolvedFriendships = friendsGraph.getAllFriendships();
await saveCacheAndConfig();


// it is subset of [...all my friends(first handshake), ...friends of my friends(second handshake)]
// it has people that are not in my friends list directly, but can potentially be friends with me (they share >=2 friend with me)
// if we cannot access the person's profile (can_access_closed field), then he/she is not included in the list
// if we previously added user to "not interested in" list, then he/she is not included in the list
// if we previously asked to load user by adding to "unresolved people to search for" list, then he/she is not included in the list, because we already seen him/her
const potentialFriends = friendsGraph.graph
.mapNodes((_, user) => ({
user,
userId: user.id,
friendsAmount: friendsGraph.getFriendsAmountOf(user.id),
link: `https://vk.com/${user.screen_name}`,
}))
.filter(({ friendsAmount, user }) =>
friendsAmount >= 2 &&
canUserBePotentialFriend(user, config)
)
.sort((a, b) => b.friendsAmount - a.friendsAmount || b.userId - a.userId);

console.log('Potential friends: ');
console.table(potentialFriends, [
'userId',
'friendsAmount',
'link'
]);

if(!potentialFriends.length) {
console.log('No potential friends found.');
break globalLoop;
}

for (let candidateIndex = 0; candidateIndex < potentialFriends.length; candidateIndex++) {
const potentialFriend = potentialFriends[candidateIndex];

console.log(`\nName: ${potentialFriend.user.first_name} ${potentialFriend.user.last_name}`);
console.log(`Link: ${potentialFriend.link}`);
console.log(`Friends: ${friendsGraph.getFriendsAmountOf(potentialFriend.userId)}`);
await open(potentialFriend.link);
const { answer } = await prompts({
type: 'select',
name: 'answer',
message: 'Do you know this person? (Use arrow keys)',
choices: [
{ title: 'Definitely yes', description: 'Graph will be expanded with their friends', value: 'yes' },
{ title: 'Definitely no', value: 'no' },
{ title: 'Save progress and exit', value: 'exit' }
],
initial: 1
});

if (answer === 'yes') {
config.unresolvedNicknamesAndIdsOfPeopleToSearchFor.push(potentialFriend.userId);
await saveConfig();
continue globalLoop;
} else if (answer === 'no') {
config.notInterestedInUserIdsOrNicknames.push(potentialFriend.userId);
await saveConfig();
} else if (answer === 'exit') {
break globalLoop;
}
}
}

await saveCacheAndConfig();
Loading

0 comments on commit 8103768

Please sign in to comment.