user.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {osu_fetch} from './api.js';
  2. import db from './database.js';
  3. import {sync_discord_info} from './discord_updates.js';
  4. async function get_user(user_id) {
  5. const user = db.prepare(`SELECT * FROM user WHERE user_id = ?`).get(user_id);
  6. if (!user) {
  7. return null;
  8. }
  9. let data = JSON.parse(user.profile_data);
  10. const seconds_since_last_update = (Date.now() - Date.parse(data.last_visit)) / 1000;
  11. if (seconds_since_last_update > 24 * 3600) {
  12. const res = await osu_fetch(`https://osu.ppy.sh/api/v2/users?ids[0]=${user.user_id}`);
  13. if (!res.users[0]) {
  14. throw new Error('User profile unavailable. Probably banned.');
  15. }
  16. data = res.users[0];
  17. db.prepare(
  18. `UPDATE user SET username = ?, country_code = ?, profile_data = ? WHERE user_id = ?`,
  19. ).run(data.username, data.country_code, JSON.stringify(data), user.user_id);
  20. if (user.username != data.username && user.username != 'New user') {
  21. // Update discord nickname, unless we're in already the process of
  22. // linking the account (that's when we have the temporary "New user").
  23. await sync_discord_info(user, 'osu! username change');
  24. }
  25. user.country_code = data.country_code;
  26. user.profile_data = data;
  27. user.username = data.username;
  28. }
  29. user.ratings = db.prepare(`SELECT * FROM rating WHERE user_id = ? ORDER BY mode ASC`).all(user_id);
  30. user.pps = [
  31. (data.statistics_rulesets?.osu?.pp || 0) / 20,
  32. (data.statistics_rulesets?.taiko?.pp || 0) / 20,
  33. (data.statistics_rulesets?.fruits?.pp || 0) / 20,
  34. (data.statistics_rulesets?.mania?.pp || 0) / 20,
  35. ];
  36. return user;
  37. }
  38. async function get_or_create_user(user_id) {
  39. const user = await get_user(user_id);
  40. if (user) {
  41. return user;
  42. }
  43. for (let ruleset = 0; ruleset < 4; ruleset++) {
  44. db.prepare(`INSERT INTO
  45. rating (user_id, mode, s3_scores, total_scores, elo, division)
  46. VALUES (?, ?, 0, 0, 1500, 'Unranked')`,
  47. ).run(user_id, ruleset);
  48. }
  49. const user_data = {
  50. username: 'New user',
  51. country_code: 'Unknown',
  52. country_name: 'Unknown country',
  53. last_visit: new Date(0).toISOString(),
  54. };
  55. db.prepare(`
  56. INSERT INTO user (user_id, username, country_code, profile_data, discord_user_id)
  57. VALUES (?, ?, ?, ?, NULL)`,
  58. ).run(user_id, user_data.username, user_data.country_code, JSON.stringify(user_data));
  59. return await get_user(user_id);
  60. }
  61. export {get_or_create_user, get_user};