Website for visualizing a persons github network.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

349 lines
8.7 KiB

  1. const routes = require('express').Router();
  2. const got = require("got");
  3. const cache = require('memory-cache');
  4. const dotenv = require("dotenv").config();
  5. const GITHUB_API = "https://api.github.com";
  6. const authenticate = `client_id=${process.env.CLIENT_ID}&client_secret=${process.env.CLIENT_SECRET}`;
  7. const API_FOLLOWING = "/following";
  8. const API_FOLLOWERS = "/followers";
  9. const API_USER_PATH = "/users/";
  10. const API_ORGS_PATH = "/orgs/";
  11. const API_PAGINATION_SIZE = 100; // 100 is the max, 30 is the default
  12. // if this is too large, it would be infeasible to make graphs for people following popular people
  13. const API_MAX_PAGES = 2;
  14. const API_PAGINATION = "&per_page=" + API_PAGINATION_SIZE;
  15. const REPOS_PATH = "/repos";
  16. /**
  17. * Queries data from the github APi server and returns it as
  18. * a json object in a promise.
  19. *
  20. * This makes no attempt to cache
  21. *
  22. * @param {*} requestURL endpoint on githubapi: ex: /users/jrtechs/following
  23. */
  24. const queryGithubAPIRaw = async requestURL => {
  25. let queryURL = requestURL.includes("?page=")
  26. ? `${GITHUB_API}${requestURL}&${authenticate}`
  27. :`${GITHUB_API}${requestURL}?${authenticate}`;
  28. console.log(queryURL);
  29. try {
  30. const req = await got(queryURL, { json: true });
  31. cache.put(requestURL, req);
  32. return req;
  33. } catch (error) {
  34. console.log(error);
  35. cache.put(requestURL, `${error.statusCode} - ${error.statusMessage}`);
  36. }
  37. }
  38. /**
  39. * Queries data from the github api server
  40. * and caches the results locally.
  41. *
  42. * @param {*} requestURL
  43. */
  44. const queryGitHubAPI = async requestURL => {
  45. const apiData = cache.get(requestURL);
  46. if (apiData) {
  47. console.log("Fetched From Cache");
  48. return apiData
  49. }
  50. try {
  51. return await queryGithubAPIRaw(requestURL);
  52. } catch (error) {
  53. console.log(error);
  54. }
  55. }
  56. /**
  57. * Fetches all content from a particular github api endpoint
  58. * using their pagination schema.
  59. *
  60. * @param {*} username username of github client
  61. * @param {*} apiPath following or followers
  62. * @param {*} page current pagination page
  63. * @param {*} lst list we are building on
  64. */
  65. const fetchAllWithPagination = async (apiPath, page, lst) => {
  66. try {
  67. const req = await queryGithubAPIRaw(`${apiPath}?page=${page}${API_PAGINATION}`);
  68. if (req) {
  69. const list = lst.concat(req.body);
  70. if(page < API_MAX_PAGES && req.length === API_PAGINATION_SIZE) {
  71. const redo = await fetchAllWithPagination(apiPath, page + 1, list);
  72. return redo;
  73. }
  74. return list;
  75. }
  76. } catch (error) {
  77. console.log("Error with api request");
  78. }
  79. }
  80. /**
  81. * Makes a copy of a JS object with certain properties
  82. *
  83. * @param {*} props
  84. * @param {*} obj
  85. */
  86. function copyWithProperties(props, obj)
  87. {
  88. var newO = new Object();
  89. for(var i =0; i < props.length; i++)
  90. {
  91. newO[props[i]] = obj[props[i]];
  92. }
  93. return newO;
  94. }
  95. /**
  96. * Combines the list of friends and followers ignoring duplicates
  97. * that are already in the list. (person is both following and followed by someone)
  98. *
  99. * This also removes any unused properties like events_url and organizations_url
  100. *
  101. * @param {*} followingAndFollowers
  102. */
  103. const minimizeFriends = people => {
  104. let friendLst = [];
  105. let ids = new Set();
  106. people.forEach(person => {
  107. if(!ids.has(person.id)) {
  108. ids.add(person.id);
  109. friendLst.push({
  110. login: person.login,
  111. avatar_url: person.avatar_url
  112. });
  113. }
  114. });
  115. return friendLst;
  116. }
  117. /**
  118. * Fetches all the people that are either following or is followed
  119. * by a person on github. This will cache the results to make simultaneous
  120. * connections easier and less demanding on the github API.
  121. *
  122. * @param {*} user
  123. */
  124. const queryFriends = async user => {
  125. const cacheHit = cache.get("/friends/" + user);
  126. if (cacheHit){
  127. console.log("Friends cache hit");
  128. return cacheHit;
  129. }
  130. try {
  131. const followers = await fetchAllWithPagination(API_USER_PATH + user + API_FOLLOWERS, 1, []);
  132. const following = await fetchAllWithPagination(API_USER_PATH + user + API_FOLLOWING, 1, []);
  133. const fList = minimizeFriends(following.concat(followers));
  134. cache.put(`/friends/${user}`, fList);
  135. return fList;
  136. } catch (error) {
  137. console.log("API Error", err);
  138. }
  139. }
  140. /**
  141. *
  142. * Fetches all of the members of an organization from the
  143. * API or cache
  144. *
  145. * /orgs/RITlug/members?page=1
  146. *
  147. * @param {*} orgName
  148. */
  149. function getOrganizationMembers(orgName)
  150. {
  151. const cacheHit = cache.get("/org/users/" + orgName);
  152. return new Promise((resolve, reject)=>
  153. {
  154. if(cacheHit == null)
  155. {
  156. fetchAllWithPagination(API_ORGS_PATH + orgName + "/members", 1, []).then((mems)=>
  157. {
  158. var minimized = minimizeFriends(mems);
  159. resolve(minimized);
  160. cache.put("/org/users/" + orgName, minimized);
  161. }).catch((err)=>
  162. {
  163. console.log(err)
  164. })
  165. }
  166. else
  167. {
  168. console.log("Org members cache hit");
  169. resolve(cacheHit);
  170. }
  171. });
  172. }
  173. /**
  174. * Minimizes the JSON for a list of repositories
  175. *
  176. * @param {*} repositories
  177. */
  178. function minimizeRepositories(repositories)
  179. {
  180. var rList = [];
  181. for(var i = 0; i < repositories.length; i++)
  182. {
  183. rList.push(copyWithProperties(["name", "created_at", "homepage",
  184. "description", "language", "forks", "watchers",
  185. "open_issues_count", "license", "html_url"],
  186. repositories[i]));
  187. }
  188. return rList;
  189. }
  190. /**
  191. * Fetches all repositories from the API
  192. *
  193. * @param {*} user name of org/user
  194. * @param {*} orgsOrUsers either /users/ or /orgs/
  195. */
  196. function queryRepositories(user, orgsOrUsers)
  197. {
  198. const cacheHit = cache.get(user + REPOS_PATH);
  199. return new Promise((resolve, reject)=>
  200. {
  201. if(cacheHit == null)
  202. {
  203. fetchAllWithPagination(orgsOrUsers + user + REPOS_PATH, 1, []).then((repos)=>
  204. {
  205. var minimized = minimizeRepositories(repos);
  206. resolve(minimized);
  207. cache.put(user + REPOS_PATH, minimized);
  208. }).catch((err)=>
  209. {
  210. console.log(err)
  211. console.log("bad things went down");
  212. })
  213. }
  214. else
  215. {
  216. console.log("Repositories cache hit");
  217. resolve(cacheHit);
  218. }
  219. });
  220. }
  221. /**
  222. * /users/name/following/followers
  223. */
  224. routes.get("/friends/:name", async (req, res)=> {
  225. try {
  226. const query = await queryFriends(req.params.name);
  227. res.json(query);
  228. } catch (error) {
  229. res.status(500).json({error: 'API error fetching friends'});
  230. }
  231. });
  232. routes.get("/org/users/:name", (request, result)=>
  233. {
  234. getOrganizationMembers(request.params.name).then(friends=>
  235. {
  236. result.json(friends)
  237. .end();
  238. }).catch(error=>
  239. {
  240. result.status(500)
  241. .json({error: 'API error fetching friends'})
  242. .end();
  243. });
  244. });
  245. routes.get("/repositories/:name", (request, result)=>
  246. {
  247. queryRepositories(request.params.name, API_USER_PATH).then(repos=>
  248. {
  249. result.json(repos)
  250. .end();
  251. }).catch(error=>
  252. {
  253. result.status(500)
  254. .json({error: 'API error fetching friends'})
  255. .end();
  256. });
  257. });
  258. routes.get("/org/repositories/:name", (request, result)=>
  259. {
  260. queryRepositories(request.params.name, API_ORGS_PATH).then(repos=>
  261. {
  262. result.json(repos)
  263. .end();
  264. }).catch(error=>
  265. {
  266. result.status(500)
  267. .json({error: 'API error fetching friends'})
  268. .end();
  269. });
  270. });
  271. routes.get('/*', (request, result) =>
  272. {
  273. var gitHubAPIURL = request.url;
  274. result.setHeader('Content-Type', 'application/json');
  275. queryGitHubAPI(gitHubAPIURL).then((data)=>
  276. {
  277. if(data.hasOwnProperty("id") || data[0].hasOwnProperty("id"))
  278. {
  279. result.write(JSON.stringify(data));
  280. }
  281. else
  282. {
  283. result.write("[]");
  284. }
  285. result.end();
  286. }).catch((error)=>
  287. {
  288. try
  289. {
  290. if(error.hasOwnProperty("id") || error[0].hasOwnProperty("id"))
  291. {
  292. result.write(JSON.stringify(error));
  293. }
  294. else
  295. {
  296. result.write("[]");
  297. }
  298. }
  299. catch(error)
  300. {
  301. result.write("[]");
  302. };
  303. result.end();
  304. });
  305. if(cache.size() > 50000)
  306. {
  307. cache.clear();
  308. }
  309. });
  310. module.exports = routes;