瀏覽代碼

Remove get_user_by_name

Clément Wolf 4 月之前
父節點
當前提交
e1cfacb1d5
共有 5 個文件被更改,包括 52 次插入115 次删除
  1. 4 5
      database.js
  2. 16 43
      lobby.js
  3. 25 56
      user.js
  4. 4 4
      website.js
  5. 3 7
      website_ssr.js

+ 4 - 5
database.js

@@ -59,11 +59,10 @@ db.exec(`
 
 
   CREATE TABLE IF NOT EXISTS user (
-    user_id         INTEGER   PRIMARY KEY,
-    username        TEXT      NOT NULL,
-    country_code    TEXT      NOT NULL,
-    profile_data    TEXT      NOT NULL,
-
+    user_id         INTEGER PRIMARY KEY,
+    username        TEXT    NOT NULL,
+    country_code    TEXT    NOT NULL,
+    profile_data    TEXT    NOT NULL,
     discord_user_id TEXT
   );
 

+ 16 - 43
lobby.js

@@ -6,7 +6,7 @@ import db from './database.js';
 
 import Config from './util/config.js';
 import {capture_sentry_exception} from './util/helpers.js';
-import {get_user_by_id, get_user_by_name} from './user.js';
+import {get_or_create_user} from './user.js';
 
 
 class BanchoLobby extends EventEmitter {
@@ -158,28 +158,8 @@ class BanchoLobby extends EventEmitter {
           }
           this.emit('refereeRemoved', m[1]);
         } else if (m = slot_regex.exec(message)) {
-          const cached = this.player_cache.find((p) => p.user_id == m[3]);
-          if (cached) {
-            cached.irc_username = m[4].substring(0, 15).trimEnd();
-            cached.state = m[2];
-            cached.is_host = m[4].substring(16).indexOf('Host') != -1;
-            if (cached.is_host) {
-              this.host = cached;
-            }
-
-            if (!this.players.some((p) => p.user_id == cached.user_id)) {
-              this.players.push(cached);
-            }
-            this.players_to_parse--;
-            if (this.players_to_parse == 0) {
-              this.emit('settings');
-            }
-
-            return;
-          }
-
           // !mp settings - single user result
-          get_user_by_id(parseInt(m[3], 10), true).then((player) => {
+          const update_player = (player) => {
             player.irc_username = m[4].substring(0, 15).trimEnd();
             player.state = m[2];
             player.is_host = m[4].substring(16).indexOf('Host') != -1;
@@ -187,21 +167,19 @@ class BanchoLobby extends EventEmitter {
               this.host = player;
             }
 
-            if (!this.players.some((p) => p.user_id == player.user_id)) {
-              this.players.push(player);
-            }
-            this.players_to_parse--;
-            if (this.players_to_parse == 0) {
-              this.emit('settings');
-            }
-          }).catch((err) => {
-            console.error(`Failed to init user on !mp settings`);
-            capture_sentry_exception(err);
+            this.players.push(player);
             this.players_to_parse--;
             if (this.players_to_parse == 0) {
               this.emit('settings');
             }
-          });
+          };
+
+          const cached_player = this.player_cache.find((p) => p.user_id == m[3]);
+          if (cached_player) {
+            update_player(cached_player);
+          } else {
+            get_or_create_user(parseInt(m[3], 10)).then(update_player);
+          }
         } else if (m = new_host_regex.exec(message)) {
           // host changed
           for (const player of this.players) {
@@ -211,16 +189,11 @@ class BanchoLobby extends EventEmitter {
           this.emit('host');
         } else if (m = joined_regex.exec(message)) {
           // player joined
-          get_user_by_name(m[1]).then((player) => {
-            player.irc_username = m[1];
-            if (!this.players.some((p) => p.user_id == player.user_id)) {
-              this.players.push(player);
-            }
-            this.emit('playerJoined', player);
-          }).catch((err) => {
-            // nothing to do ¯\_(ツ)_/¯
-            // will fix itself on the next !mp settings call.
-          });
+          const player = {
+            irc_username: m[1],
+          };
+          this.players.push(player);
+          this.emit('playerJoined', player);
         } else if (m = left_regex.exec(message)) {
           // player left
           const irc_username = m[1];

+ 25 - 56
user.js

@@ -1,40 +1,17 @@
 import {osu_fetch} from './api.js';
-import bancho from './bancho.js';
 import db from './database.js';
 import {sync_discord_info} from './discord_updates.js';
 
 
-async function init_user(user_id) {
-  for (let ruleset = 0; ruleset < 4; ruleset++) {
-    db.prepare(`INSERT INTO
-      rating (user_id, mode, s3_scores, total_scores, elo,  division)
-      VALUES (?,       ?,    0,         0,            1500, 'Unranked')
-      RETURNING *`,
-    ).run(user_id, ruleset);
+async function get_user(user_id) {
+  const user = db.prepare(`SELECT * FROM user WHERE user_id = ?`).get(user_id);
+  if (!user) {
+    return null;
   }
 
-  const user_data = {
-    username: 'New user',
-    country_code: 'Unknown',
-    country_name: 'Unknown country',
-    last_visit: new Date(0).toISOString(),
-  };
-  const user = db.prepare(`
-      INSERT INTO user (user_id, username, country_code, profile_data, discord_user_id)
-      VALUES           (?,       ?,        ?,            ?,            NULL)
-      RETURNING *`,
-  ).get(user_id, user_data.username, user_data.country_code, JSON.stringify(user_data));
-  await populate_ratings_and_update_profile(user);
-  return user;
-}
-
-
-async function populate_ratings_and_update_profile(user) {
-  user.ratings = db.prepare(`SELECT * FROM rating WHERE user_id = ? ORDER BY mode ASC`).all(user.user_id);
-
   let data = JSON.parse(user.profile_data);
   const seconds_since_last_update = (Date.now() - Date.parse(data.last_visit)) / 1000;
-  if (bancho.connected && (seconds_since_last_update > 24 * 3600)) {
+  if (seconds_since_last_update > 24 * 3600) {
     const res = await osu_fetch(`https://osu.ppy.sh/api/v2/users?ids[0]=${user.user_id}`);
     if (!res.users[0]) {
       throw new Error('User profile unavailable. Probably banned.');
@@ -56,50 +33,42 @@ async function populate_ratings_and_update_profile(user) {
     user.username = data.username;
   }
 
+  user.ratings = db.prepare(`SELECT * FROM rating WHERE user_id = ? ORDER BY mode ASC`).all(user_id);
   user.pps = [
     (data.statistics_rulesets?.osu?.pp || 0) / 20,
     (data.statistics_rulesets?.taiko?.pp || 0) / 20,
     (data.statistics_rulesets?.fruits?.pp || 0) / 20,
     (data.statistics_rulesets?.mania?.pp || 0) / 20,
   ];
-}
-
-
-async function get_user_by_id(user_id, create) {
-  let user = db.prepare(`SELECT * FROM user WHERE user_id = ?`).get(user_id);
-  if (user) {
-    await populate_ratings_and_update_profile(user);
-    return user;
-  }
-
-  if (!create) {
-    return null;
-  }
 
-  user = await init_user(user_id);
   return user;
 }
 
-async function get_user_by_name(name) {
-  let user = db.prepare(`SELECT * FROM user WHERE username = ?`).get(name);
+async function get_or_create_user(user_id) {
+  const user = await get_user(user_id);
   if (user) {
-    await populate_ratings_and_update_profile(user);
     return user;
   }
 
-  let user_id;
-  try {
-    user_id = await bancho.whois(name);
-  } catch (err) {
-    user_id = await osu_fetch(`https://osu.ppy.sh/api/v2/users/${name}?key=username`).id;
+  for (let ruleset = 0; ruleset < 4; ruleset++) {
+    db.prepare(`INSERT INTO
+      rating (user_id, mode, s3_scores, total_scores, elo,  division)
+      VALUES (?,       ?,    0,         0,            1500, 'Unranked')`,
+    ).run(user_id, ruleset);
   }
 
-  if (!user_id) {
-    return null;
-  }
+  const user_data = {
+    username: 'New user',
+    country_code: 'Unknown',
+    country_name: 'Unknown country',
+    last_visit: new Date(0).toISOString(),
+  };
+  db.prepare(`
+      INSERT INTO user (user_id, username, country_code, profile_data, discord_user_id)
+      VALUES           (?,       ?,        ?,            ?,            NULL)`,
+  ).get(user_id, user_data.username, user_data.country_code, JSON.stringify(user_data));
 
-  user = await get_user_by_id(user_id);
-  return user;
+  return await get_user(user_id);
 }
 
-export {get_user_by_id, get_user_by_name};
+export {get_or_create_user, get_user};

+ 4 - 4
website.js

@@ -7,7 +7,7 @@ import Sentry from '@sentry/node';
 import bancho from './bancho.js';
 import db from './database.js';
 import {sync_discord_info} from './discord_updates.js';
-import {get_user_by_id} from './user.js';
+import {get_or_create_user, get_user} from './user.js';
 import Config from './util/config.js';
 import {render_error, gen_url} from './util/helpers.js';
 import {register_routes as register_api_routes} from './website_api.js';
@@ -160,7 +160,7 @@ async function listen() {
 
       // Initialize the user in the database if needed
       try {
-        await get_user_by_id(user_profile.id, true);
+        await get_or_create_user(user_profile.id);
       } catch (err) {
         return http_res.end(render_error(`Couldn't fetch profile... Are you banned?`));
       }
@@ -192,7 +192,7 @@ async function listen() {
       // Initialize the user in the database if needed
       let user;
       try {
-        user = await get_user_by_id(user_profile.id, true);
+        user = await get_or_create_user(user_profile.id);
       } catch (err) {
         return http_res.end(render_error(`Couldn't fetch profile... Are you banned?`));
       }
@@ -227,7 +227,7 @@ async function listen() {
     }
 
     try {
-      const user = await get_user_by_id(req.signedCookies.user, false);
+      const user = await get_user(req.signedCookies.user);
       await bancho.privmsg(user.username, `${user.username}, here's your invite: [http://osump://${inviting_lobby.invite_id}/ ${inviting_lobby.name}]`);
       http_res.status(200).json({success: true});
     } catch (err) {

+ 3 - 7
website_ssr.js

@@ -5,7 +5,7 @@ import twemoji from 'twemoji';
 import Config from './util/config.js';
 import countries from './countries.js';
 import db from './database.js';
-import {get_user_by_id} from './user.js';
+import {get_user} from './user.js';
 import {get_user_rank} from './elo.js';
 import {get_user_matches, get_leaderboard_page} from './website_api.js';
 
@@ -61,12 +61,8 @@ async function render_user_profile(req, res, page_num) {
   mini_cache(res);
 
   const mode = get_mode(req);
-  let user;
-  try {
-    // get_user_by_id() throws an error when the user is banned from bancho
-    user = await get_user_by_id(req.params.userId, false);
-    if (!user) throw new Error('User not found');
-  } catch (err) {
+  const user = await get_user(req.params.userId);
+  if (!user) {
     return res.status(404).end(user_not_found_page);
   }