1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import {osu_fetch} from './api.js';
- import db from './database.js';
- import {sync_discord_info} from './discord_updates.js';
- async function get_user(user_id) {
- const user = db.prepare(`SELECT * FROM user WHERE user_id = ?`).get(user_id);
- if (!user) {
- return null;
- }
- let data = JSON.parse(user.profile_data);
- const seconds_since_last_update = (Date.now() - Date.parse(data.last_visit)) / 1000;
- 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.');
- }
- data = res.users[0];
- db.prepare(
- `UPDATE user SET username = ?, country_code = ?, profile_data = ? WHERE user_id = ?`,
- ).run(data.username, data.country_code, JSON.stringify(data), user.user_id);
- if (user.username != data.username && user.username != 'New user') {
- // Update discord nickname, unless we're in already the process of
- // linking the account (that's when we have the temporary "New user").
- await sync_discord_info(user, 'osu! username change');
- }
- user.country_code = data.country_code;
- user.profile_data = data;
- 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,
- ];
- return user;
- }
- async function get_or_create_user(user_id) {
- const user = await get_user(user_id);
- if (user) {
- return user;
- }
- 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);
- }
- 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)`,
- ).run(user_id, user_data.username, user_data.country_code, JSON.stringify(user_data));
- return await get_user(user_id);
- }
- export {get_or_create_user, get_user};
|