feat(api): add Dakao commands
This commit is contained in:
1 parent
57e3c68ea8
commit
efa133a1a2
29 files changed
+5335
No files matched your search
@@ -0,0 +1,406 @@
|
||||
/**
|
||||
* Add or update one lolympus user manually from Kakao + Riot identity.
|
||||
*
|
||||
* This is for the last few users that need manual handling.
|
||||
*
|
||||
* Install:
|
||||
* npm install mongodb
|
||||
*
|
||||
* Dry-run with Riot API enrichment:
|
||||
* MONGODB_URI="mongodb://..." \
|
||||
* RIOT_API_KEY="RGAPI-..." \
|
||||
* KAKAO_TALK_ID="7448687768283723562" \
|
||||
* KAKAO_TALK_NICKNAME="탑은죄악이다/95/남/G" \
|
||||
* RIOT_ID="탑은죄악이다#망나니" \
|
||||
* PREFERRED_POSITIONS="TOP,JGL" \
|
||||
* node add-manual-dakao-riot-user.js
|
||||
*
|
||||
* Write:
|
||||
* DRY_RUN=false MONGODB_URI="..." RIOT_API_KEY="..." ... node add-manual-dakao-riot-user.js
|
||||
*
|
||||
* Fallback without Riot API:
|
||||
* PUUID="..." RIOT_ID="..." node add-manual-dakao-riot-user.js
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const { MongoClient, ObjectId } = require("mongodb");
|
||||
|
||||
const CONFIG = {
|
||||
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
||||
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
|
||||
COMMUNITY_ID: new ObjectId(
|
||||
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
||||
),
|
||||
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
|
||||
RIOT_REGION: process.env.RIOT_REGION ?? "asia",
|
||||
RIOT_PLATFORM: process.env.RIOT_PLATFORM ?? "kr",
|
||||
MASTERY_COUNT: Number(process.env.MASTERY_COUNT ?? 10),
|
||||
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
|
||||
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
|
||||
DRY_RUN: process.env.DRY_RUN !== "false",
|
||||
FAIL_ON_CONFLICT: process.env.FAIL_ON_CONFLICT !== "false",
|
||||
};
|
||||
|
||||
const INPUT = {
|
||||
kakaoTalkId: process.env.KAKAO_TALK_ID ?? "",
|
||||
kakaoTalkNickname: process.env.KAKAO_TALK_NICKNAME ?? "",
|
||||
riotId: process.env.RIOT_ID ?? "",
|
||||
puuid: process.env.PUUID ?? "",
|
||||
preferredPositions: process.env.PREFERRED_POSITIONS ?? "",
|
||||
role: process.env.ROLE ?? "member",
|
||||
isActivated: process.env.IS_ACTIVATED !== "false",
|
||||
};
|
||||
|
||||
function normalizeString(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function splitRiotId(riotId) {
|
||||
const value = normalizeString(riotId);
|
||||
const hashIndex = value.lastIndexOf("#");
|
||||
if (hashIndex <= 0 || hashIndex === value.length - 1) {
|
||||
throw new Error(`Invalid RIOT_ID. Expected "gameName#tagLine": ${riotId}`);
|
||||
}
|
||||
return {
|
||||
gameName: value.slice(0, hashIndex).trim(),
|
||||
tagLine: value.slice(hashIndex + 1).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePositions(value) {
|
||||
const allowed = new Set(["TOP", "JGL", "MID", "ADC", "SUP"]);
|
||||
return normalizeString(value)
|
||||
.split(",")
|
||||
.map((position) => normalizeString(position).toUpperCase())
|
||||
.filter((position) => allowed.has(position))
|
||||
.map((position, index) => ({ position, priority: index + 1 }));
|
||||
}
|
||||
|
||||
function removeUndefined(value) {
|
||||
if (Array.isArray(value)) return value.map(removeUndefined);
|
||||
if (
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
!(value instanceof Date) &&
|
||||
!(value instanceof ObjectId)
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([, entryValue]) => entryValue !== undefined)
|
||||
.map(([key, entryValue]) => [key, removeUndefined(entryValue)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function maskConfig() {
|
||||
return {
|
||||
...CONFIG,
|
||||
MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"),
|
||||
RIOT_API_KEY: CONFIG.RIOT_API_KEY ? "***" : "",
|
||||
};
|
||||
}
|
||||
|
||||
function requireInput() {
|
||||
const missing = [];
|
||||
if (!normalizeString(INPUT.kakaoTalkId)) missing.push("KAKAO_TALK_ID");
|
||||
if (!normalizeString(INPUT.kakaoTalkNickname)) {
|
||||
missing.push("KAKAO_TALK_NICKNAME");
|
||||
}
|
||||
if (!normalizeString(INPUT.riotId)) missing.push("RIOT_ID");
|
||||
if (!CONFIG.RIOT_API_KEY && !normalizeString(INPUT.puuid)) {
|
||||
missing.push("RIOT_API_KEY or PUUID");
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing required env: ${missing.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRiotJson({ host, path, query }) {
|
||||
if (!CONFIG.RIOT_API_KEY) return null;
|
||||
|
||||
const url = new URL(`https://${host}${path}`);
|
||||
for (const [key, value] of Object.entries(query ?? {})) {
|
||||
if (value !== undefined && value !== null) {
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const response = await fetch(url, {
|
||||
headers: { "X-Riot-Token": CONFIG.RIOT_API_KEY },
|
||||
});
|
||||
|
||||
if (response.status === 429) {
|
||||
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
|
||||
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
||||
continue;
|
||||
}
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => "");
|
||||
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAccountByRiotId({ gameName, tagLine }) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
|
||||
path: `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchSummonerByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchLeagueEntriesByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchChampionMasteriesByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
|
||||
query: { count: CONFIG.MASTERY_COUNT },
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchRecentMatchIdsByPuuid(puuid) {
|
||||
if (!CONFIG.FETCH_RECENT_MATCH_IDS) return [];
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
|
||||
path: `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
|
||||
query: { start: 0, count: CONFIG.RECENT_MATCH_COUNT },
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchRiotData({ riotId }) {
|
||||
const fallback = splitRiotId(riotId);
|
||||
const account =
|
||||
(await fetchAccountByRiotId(fallback)) ?? {
|
||||
...fallback,
|
||||
puuid: normalizeString(INPUT.puuid),
|
||||
};
|
||||
if (!account?.puuid) {
|
||||
throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`);
|
||||
}
|
||||
|
||||
const [summoner, leagueEntries, championMasteries, matchIds] =
|
||||
await Promise.all([
|
||||
fetchSummonerByPuuid(account.puuid).catch(() => null),
|
||||
fetchLeagueEntriesByPuuid(account.puuid).catch(() => []),
|
||||
fetchChampionMasteriesByPuuid(account.puuid).catch(() => []),
|
||||
fetchRecentMatchIdsByPuuid(account.puuid).catch(() => []),
|
||||
]);
|
||||
|
||||
return {
|
||||
account: {
|
||||
puuid: account.puuid,
|
||||
gameName: normalizeString(account.gameName) || fallback.gameName,
|
||||
tagLine: normalizeString(account.tagLine) || fallback.tagLine,
|
||||
},
|
||||
summoner,
|
||||
leagueEntries: Array.isArray(leagueEntries) ? leagueEntries : [],
|
||||
championMasteries: Array.isArray(championMasteries)
|
||||
? championMasteries
|
||||
: [],
|
||||
matchIds: Array.isArray(matchIds) ? matchIds : [],
|
||||
};
|
||||
}
|
||||
|
||||
function toTierInfo(entry, fetchedAt) {
|
||||
return {
|
||||
leagueId: entry.leagueId,
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
puuid: entry.puuid,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
veteran: entry.veteran,
|
||||
inactive: entry.inactive,
|
||||
freshBlood: entry.freshBlood,
|
||||
hotStreak: entry.hotStreak,
|
||||
miniSeries: entry.miniSeries,
|
||||
fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toTierHistory(entry, recordedAt) {
|
||||
return {
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
recordedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toChampionMastery(entry) {
|
||||
return {
|
||||
puuid: entry.puuid,
|
||||
championId: entry.championId,
|
||||
championLevel: entry.championLevel,
|
||||
championPoints: entry.championPoints,
|
||||
lastPlayTime: entry.lastPlayTime,
|
||||
championPointsSinceLastLevel: entry.championPointsSinceLastLevel,
|
||||
championPointsUntilNextLevel: entry.championPointsUntilNextLevel,
|
||||
markRequiredForNextLevel: entry.markRequiredForNextLevel,
|
||||
tokensEarned: entry.tokensEarned,
|
||||
championSeasonMilestone: entry.championSeasonMilestone,
|
||||
milestoneGrades: entry.milestoneGrades,
|
||||
nextSeasonMilestone: entry.nextSeasonMilestone,
|
||||
};
|
||||
}
|
||||
|
||||
function buildRiotAccount(riotData, now) {
|
||||
return removeUndefined({
|
||||
puuid: riotData.account.puuid,
|
||||
gameName: riotData.account.gameName,
|
||||
tagLine: riotData.account.tagLine,
|
||||
profileIconId: riotData.summoner?.profileIconId ?? 0,
|
||||
revisionDate: riotData.summoner?.revisionDate ?? 0,
|
||||
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
|
||||
isPrimary: true,
|
||||
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
|
||||
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)),
|
||||
matchIds: riotData.matchIds,
|
||||
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
|
||||
championMasteries: riotData.championMasteries
|
||||
.slice(0, CONFIG.MASTERY_COUNT)
|
||||
.map(toChampionMastery),
|
||||
championMasteriesFetchedAt:
|
||||
riotData.championMasteries.length > 0 ? now : undefined,
|
||||
championRecords: {},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
function mergeRiotAccount(existingAccounts, nextAccount) {
|
||||
const merged = (existingAccounts ?? [])
|
||||
.filter(
|
||||
(account) =>
|
||||
account.puuid !== nextAccount.puuid &&
|
||||
!(
|
||||
normalizeString(account.gameName).toLowerCase() ===
|
||||
normalizeString(nextAccount.gameName).toLowerCase() &&
|
||||
normalizeString(account.tagLine).toLowerCase() ===
|
||||
normalizeString(nextAccount.tagLine).toLowerCase()
|
||||
),
|
||||
)
|
||||
.map((account) => ({ ...account, isPrimary: false }));
|
||||
return [nextAccount, ...merged];
|
||||
}
|
||||
|
||||
async function buildPlan(User) {
|
||||
const now = new Date();
|
||||
const riotData = await fetchRiotData({ riotId: INPUT.riotId });
|
||||
const account = buildRiotAccount(riotData, now);
|
||||
|
||||
const conflict = await User.findOne({
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
kakaoTalkId: { $ne: INPUT.kakaoTalkId },
|
||||
"riotAccounts.puuid": account.puuid,
|
||||
});
|
||||
if (conflict && CONFIG.FAIL_ON_CONFLICT) {
|
||||
throw new Error(
|
||||
`Riot puuid conflict. existingUserId=${conflict._id.toString()} existingKakaoTalkId=${conflict.kakaoTalkId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const filter = {
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
kakaoTalkId: INPUT.kakaoTalkId,
|
||||
};
|
||||
const existing = await User.findOne(filter);
|
||||
const doc = removeUndefined({
|
||||
_id: existing?._id ?? new ObjectId(),
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
role: INPUT.role,
|
||||
kakaoTalkId: INPUT.kakaoTalkId,
|
||||
kakaoTalkNickname: INPUT.kakaoTalkNickname,
|
||||
riotAccounts: mergeRiotAccount(existing?.riotAccounts, account),
|
||||
preferredPositions: normalizePositions(INPUT.preferredPositions),
|
||||
isActivated: INPUT.isActivated,
|
||||
createdAt: existing?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
return {
|
||||
mode: existing ? "update" : "insert",
|
||||
filter,
|
||||
doc,
|
||||
conflict: conflict
|
||||
? {
|
||||
existingUserId: conflict._id,
|
||||
existingKakaoTalkId: conflict.kakaoTalkId,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function applyPlan(User, plan) {
|
||||
if (CONFIG.DRY_RUN) return { dryRun: true, plan };
|
||||
|
||||
if (plan.mode === "update") {
|
||||
const { _id, createdAt, ...setDoc } = plan.doc;
|
||||
await User.updateOne({ _id: plan.doc._id }, { $set: setDoc });
|
||||
return { updated: 1, inserted: 0, userId: plan.doc._id };
|
||||
}
|
||||
|
||||
await User.insertOne(plan.doc);
|
||||
return { updated: 0, inserted: 1, userId: plan.doc._id };
|
||||
}
|
||||
|
||||
async function run() {
|
||||
requireInput();
|
||||
const client = new MongoClient(CONFIG.MONGODB_URI);
|
||||
await client.connect();
|
||||
|
||||
try {
|
||||
const db = client.db(CONFIG.LOLYMPUS_DB_NAME);
|
||||
const User = db.collection("user");
|
||||
const plan = await buildPlan(User);
|
||||
const result = await applyPlan(User, plan);
|
||||
|
||||
return {
|
||||
config: maskConfig(),
|
||||
input: {
|
||||
...INPUT,
|
||||
puuid: INPUT.puuid ? "***provided***" : "",
|
||||
},
|
||||
result,
|
||||
};
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
run()
|
||||
.then((result) => {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user