♻️ 重构用户登录逻辑及切换

#126
This commit is contained in:
目棃
2024-09-21 19:32:14 +08:00
parent 39a1a1dd77
commit cc7dd7c8ca
27 changed files with 739 additions and 897 deletions

View File

@@ -8,7 +8,7 @@ import { app } from "@tauri-apps/api";
import Database from "@tauri-apps/plugin-sql";
import initDataSql from "./sql/initData.js";
import { insertAppData, insertGameAccountData, insertRecordData } from "./sql/insertData.js";
import { insertAppData, insertRecordData } from "./sql/insertData.js";
class Sqlite {
/**
@@ -89,48 +89,6 @@ class Sqlite {
return localVersion !== dbVersion;
}
/**
* @description 获取 cookie
* @since Beta v0.3.8
* @returns {Promise<TGApp.User.Account.Cookie>}
*/
public async getCookie(): Promise<TGApp.User.Account.Cookie> {
const db = await this.getDB();
const sql = "SELECT value FROM AppData WHERE key='cookie';";
const res: Array<{ value: string }> = await db.select(sql);
return JSON.parse(res[0].value);
}
/**
* @description 插入 Account 数据
* @since Beta v0.4.7
* @param {TGApp.User.Account.Game[]} accounts
* @returns {Promise<void>}
*/
public async saveAccount(accounts: TGApp.User.Account.Game[]): Promise<void> {
const db = await this.getDB();
await db.execute("DELETE FROM GameAccount WHERE true;");
for (const a of accounts) {
const sql = insertGameAccountData(a);
await db.execute(sql);
}
}
/**
* @description 获取当前选择的游戏账号
* @since Beta v0.4.1
* @returns {Promise<TGApp.Sqlite.Account.Game|false>}
*/
public async getCurAccount(): Promise<TGApp.Sqlite.Account.Game | false> {
const db = await this.getDB();
const check = "SELECT * FROM GameAccount";
const checkRes: TGApp.Sqlite.Account.Game[] = await db.select(check);
if (checkRes.length === 0) return false;
if (checkRes.length === 1) return checkRes[0];
const res = checkRes.filter((item) => item.isChosen === 1);
return res.length === 0 ? false : res[0];
}
/**
* @description 保存 appData
* @since Beta v0.3.3
@@ -202,21 +160,6 @@ class Sqlite {
return res[0];
}
/**
* @description 获取角色数据
* @since Beta v0.3.3
* @param {number} id 角色 ID
* @returns {Promise<TGApp.Sqlite.Character.AppData}> 角色数据
*/
public async getAppCharacter(id: number): Promise<TGApp.Sqlite.Character.AppData> {
const db = await this.getDB();
const sql = `SELECT *
FROM AppCharacters
WHERE id = ${id}`;
const res: TGApp.Sqlite.Character.AppData[] = await db.select(sql);
return res[0];
}
/**
* @description 检测特定表是否存在
* @since Beta v0.4.5

View File

@@ -0,0 +1,235 @@
/**
* @file plugins/Sqlite/modules/userAccounts.ts
* @description 用户账户模块
* @since Beta v0.6.0
*/
import { timestampToDate } from "../../../utils/toolFunc.js";
import TGSqlite from "../index.js";
/**
* @description 获取插入游戏账号数据的sql
* @since Beta v0.6.0
* @param {string} uid - 米社UID
* @param {TGApp.BBS.Account.GameAccount} data - 游戏账号数据
* @return {string}
*/
function getInsertGameAccountSql(uid: string, data: TGApp.BBS.Account.GameAccount): string {
const isChosen = data.is_chosen ? 1 : 0;
const isOfficial = data.is_official ? 1 : 0;
const timeNow = timestampToDate(new Date().getTime());
return `
INSERT INTO GameAccount(uid, gameBiz, gameUid, isChosen, isOfficial, level, nickname, region, regionName, updated)
VALUES ('${uid}', '${data.game_biz}', '${data.game_uid}', ${isChosen}, ${isOfficial}, ${data.level},
'${data.nickname}', '${data.region}', '${data.region_name}', '${timeNow}')
ON CONFLICT(uid, gameUid) DO UPDATE
SET gameBiz = '${data.game_biz}',
isChosen = ${isChosen},
isOfficial = ${isOfficial},
level = ${data.level},
nickname = '${data.nickname}',
region = '${data.region}',
regionName = '${data.region_name}',
updated = '${timeNow}';
`;
}
/**
* @description 数据库转成可用数据
* @since Beta v0.6.0
* @param {TGApp.Sqlite.Account.User} data - 用户数据
* @returns {TGApp.App.Account.User}
*/
function parseUser(data: TGApp.Sqlite.Account.User): TGApp.App.Account.User {
return {
uid: data.uid,
brief: JSON.parse(data.brief),
cookie: JSON.parse(data.cookie),
updated: data.updated,
};
}
/**
* @description 转成数据库数据方便存储
* @since Beta v0.6.0
* @param {TGApp.App.Account.User} data - 用户数据
* @returns {TGApp.Sqlite.Account.User}
*/
function transUser(data: TGApp.App.Account.User): TGApp.Sqlite.Account.User {
return {
uid: data.uid,
brief: JSON.stringify(data.brief),
cookie: JSON.stringify(data.cookie),
updated: timestampToDate(new Date().getTime()),
};
}
/**
* @description 获取所有用户数据
* @since Beta v0.6.0
* @returns {Promise<TGApp.App.Account.User[]>}
*/
async function getAllAccount(): Promise<TGApp.App.Account.User[]> {
const db = await TGSqlite.getDB();
const res = await db.select<TGApp.Sqlite.Account.User[]>("SELECT * FROM UserAccount;");
return res.map((account) => parseUser(account));
}
/**
* @description 获取所有UID
* @since Beta v0.6.0
* @returns {Promise<string[]>}
*/
async function getAllAccountId(): Promise<string[]> {
const db = await TGSqlite.getDB();
type resType = Array<{ uid: string }>;
const res = await db.select<resType>("SELECT DISTINCT uid FROM GameAccount;");
return res.map((account) => account.uid);
}
/**
* @description 获取指定用户数据
* @since Beta v0.6.0
* @param {string} uid - 用户UID
* @returns {Promise<TGApp.App.Account.User|false>}
*/
async function getUserAccount(uid: string): Promise<TGApp.App.Account.User | false> {
const db = await TGSqlite.getDB();
const res = await db.select<TGApp.Sqlite.Account.User[]>(
"SELECT * FROM UserAccount WHERE uid = ?",
[uid],
);
if (res.length === 0) return false;
return parseUser(res[0]);
}
/**
* @description 更新用户数据
* @since Beta v0.6.0
* @param {TGApp.App.Account.User} data - 用户cookie
* @returns {Promise<void>}
*/
async function saveAccount(data: TGApp.App.Account.User): Promise<void> {
const db = await TGSqlite.getDB();
const table = transUser(data);
const timeNow = timestampToDate(new Date().getTime());
await db.execute(
"INSERT INTO UserAccount(uid, cookie, brief, updated) VALUES \
(?,?,?,?) ON CONFLICT (uid) DO UPDATE SET cookie=?,brief=?,updated=?",
[table.uid, table.cookie, table.brief, timeNow, table.cookie, table.brief, timeNow],
);
}
/**
* @description 复制cookie
* @since Beta v0.6.0
* @param {TGApp.App.Account.Cookie} cookie - cookie
* @return {string}
*/
function copyCookie(cookie: TGApp.App.Account.Cookie): string {
let res = "";
if (cookie.ltuid && cookie.ltuid !== "") {
res += `ltuid=${cookie.ltuid};`;
}
if (cookie.ltoken && cookie.ltoken !== "") {
res += `ltoken=${cookie.ltoken};`;
}
if (cookie.mid && cookie.mid !== "") {
res += `mid=${cookie.mid};`;
}
if (cookie.cookie_token && cookie.cookie_token !== "") {
res += `cookie_token=${cookie.cookie_token};`;
}
if (cookie.stoken && cookie.stoken !== "") {
res += `stoken=${cookie.stoken};`;
}
if (cookie.stuid && cookie.stuid !== "") {
res += `stuid=${cookie.stuid};`;
}
if (cookie.account_id && cookie.account_id !== "") {
res += `account_id=${cookie.account_id};`;
}
return res;
}
/**
* @description 获取指定用户账号
* @since Beta v0.6.0
* @param {string} uid - 用户UID
* @returns {Promise<TGApp.Sqlite.Account.Game[]>}
*/
async function getGameAccount(uid: string): Promise<TGApp.Sqlite.Account.Game[]> {
const db = await TGSqlite.getDB();
return await db.select<TGApp.Sqlite.Account.Game[]>("SELECT * FROM GameAccount WHERE uid = ?;", [
uid,
]);
}
/**
* @description 切换到指定游戏账号
* @since Beta v0.6.0
* @param {string} uid - 米社UID
* @param {string} gameUid - 游戏UID
* @returns {Promise<void>}
*/
async function switchGameAccount(uid: string, gameUid: string): Promise<void> {
const db = await TGSqlite.getDB();
await db.execute("UPDATE GameAccount SET isChosen = 0,updated=? WHERE uid = ?;", [
timestampToDate(new Date().getTime()),
uid,
]);
await db.execute("UPDATE GameAccount SET isChosen=1,updated=? WHERE uid = ? AND gameUid = ?;", [
timestampToDate(new Date().getTime()),
uid,
gameUid,
]);
}
/**
* @description 获取最近的游戏账户
* @since Beta v0.6.0
* @param {string} uid - 米社UID
* @return {Promise<TGApp.Sqlite.Account.Game|false>}
*/
async function getCurGameAccount(uid: string): Promise<TGApp.Sqlite.Account.Game | false> {
const gameAccounts = await getGameAccount(uid);
if (gameAccounts.length === 0) return false;
const curGameAccount = gameAccounts.find((account) => account.isChosen === 1);
if (!curGameAccount) return gameAccounts[0];
return curGameAccount;
}
/**
* @description 保存游戏账户数据
* @since Beta v0.6.0
* @param {string} uid - 米社UID
* @param {TGApp.BBS.Account.GameAccount[]} accounts - 账户数据
* @return {Promise<void>}
*/
async function saveGameAccount(
uid: string,
accounts: TGApp.BBS.Account.GameAccount[],
): Promise<void> {
const db = await TGSqlite.getDB();
for (const account of accounts) {
await db.execute(getInsertGameAccountSql(uid, account));
}
}
const TSUserAccount = {
account: {
getAllUid: getAllAccountId,
getAllAccount,
getAccount: getUserAccount,
saveAccount,
copy: copyCookie,
},
game: {
getAccount: getGameAccount,
switchAccount: switchGameAccount,
getCurAccount: getCurGameAccount,
saveAccounts: saveGameAccount,
},
};
export default TSUserAccount;

View File

@@ -1,22 +1,67 @@
/**
* @file plugins/Sqlite/modules/userAvatar.ts
* @description 用户角色模块
* @since Beta v0.5.3
* @since Beta v0.6.0
*/
import { AppCharacterData } from "../../../data/index.js";
import { timestampToDate } from "../../../utils/toolFunc.js";
import TGSqlite from "../index.js";
import { insertRoleData } from "../sql/insertData.js";
/**
* @description 获取角色插入Sql
* @since Beta v0.6.0
* @param {string} uid - 用户UID
* @param {TGApp.Game.Avatar.DetailList} data - 角色数据
* @return {string}
*/
function getInsertSql(uid: string, data: TGApp.Game.Avatar.DetailList): string {
const role: TGApp.Sqlite.Character.UserRoleDB = {
uid: Number(uid),
cid: data.base.id,
avatar: JSON.stringify(data.base),
weapon: JSON.stringify(data.weapon),
relics: JSON.stringify(data.relics),
constellations: JSON.stringify(data.constellations),
costumes: JSON.stringify(data.costumes),
skills: JSON.stringify(data.skills),
propSelected: JSON.stringify(data.selected_properties),
propBase: JSON.stringify(data.base_properties),
propExtra: JSON.stringify(data.extra_properties),
propRecommend: JSON.stringify(data.recommend_relic_property),
updated: timestampToDate(new Date().getTime()),
};
return `
INSERT INTO UserCharacters (uid, cid, avatar, weapon, relics, constellations, costumes, skills,
propSelected, propBase, propExtra, propRecommend, updated)
VALUES (${uid}, ${role.cid}, '${role.avatar}', '${role.weapon}', '${role.relics}', '${role.constellations}',
'${role.costumes}', '${role.skills}', '${role.propSelected}', '${role.propBase}', '${role.propExtra}',
'${role.propRecommend}', '${role.updated}')
ON CONFLICT(uid, cid) DO UPDATE
SET avatar = '${role.avatar}',
weapon = '${role.weapon}',
relics = '${role.relics}',
constellations = '${role.constellations}',
costumes = '${role.costumes}',
skills = '${role.skills}',
propSelected = '${role.propSelected}',
propBase = '${role.propBase}',
propExtra = '${role.propExtra}',
propRecommend = '${role.propRecommend}',
updated = '${role.updated}';
`;
}
/**
* @description 获取用户角色id列表
* @since Beta v0.5.3
* @returns {Promise<string[]>} 角色id列表
*/
async function getAllAvatarId(): Promise<string[]> {
async function getAllUid(): Promise<string[]> {
const db = await TGSqlite.getDB();
type resType = Array<{ cid: string }>;
type resType = Array<{ uid: string }>;
const res = await db.select<resType>("SELECT DISTINCT cid FROM UserCharacters;");
return res.map((i) => i.cid);
return res.map((i) => i.uid);
}
/**
@@ -50,35 +95,32 @@ async function getAvatars(uid: string): Promise<TGApp.Sqlite.Character.UserRole[
/**
* @description 保存用户角色数据
* @since Beta v0.5.3
* @since Beta v0.6.0
* @param {string} uid 用户 uid
* @param {TGApp.Game.Avatar.DetailList[]} data 角色数据
* @returns {Promise<void>}
*/
async function saveAvatars(uid: string, data: TGApp.Game.Avatar.DetailList[]): Promise<void> {
const db = await TGSqlite.getDB();
const sql = insertRoleData(uid, data);
await db.execute(sql);
for (const role of data) {
await db.execute(getInsertSql(uid, role));
}
}
/**
* @description 获取角色名片
* @since Beta v0.5.3
* @since Beta v0.6.0
* @param {number} id 角色 id
* @returns {Promise<string|false>}
* @returns {string|false}
*/
async function getAvatarCard(id: number): Promise<string | false> {
const db = await TGSqlite.getDB();
type resType = Array<{ card: string }>;
const res = await db.select<resType>("SELECT nameCard as card FROM AppCharacters WHERE id = ?;", [
id,
]);
if (res.length === 0) return false;
return res[0].card;
function getAvatarCard(id: number): string {
const find = AppCharacterData.find((c) => c.id === id);
if (!find) return "原神·印象";
return find.nameCard;
}
const TSUserAvatar = {
getAllAvatarId,
getAllUid,
getAvatars,
saveAvatars,
getAvatarCard,

View File

@@ -16,22 +16,11 @@ create table if not exists Achievements
primary key (id, uid)
);
-- @brief 重新创建成就系列数据表
-- @brief 移除成就系列数据表
drop table if exists AchievementSeries;
-- @brief 创建角色数据表
create table if not exists AppCharacters
(
id integer primary key,
name text,
title text,
birthday text,
star integer,
element text,
weapon text,
nameCard text,
updated text
);
-- @brief 移除角色数据表
drop table if exists AppCharacters;
-- @brief 创建应用数据表
create table if not exists AppData
@@ -41,9 +30,22 @@ create table if not exists AppData
updated text
);
-- @brief 创建用户数据表
create table if not exists UserAccount
(
uid text primary key,
cookie text,
brief text,
updated text
);
-- @brief 重新创建账号数据表
drop table if exists GameAccount;
-- @brief 创建游戏账号数据表
create table if not exists GameAccount
(
uid text,
gameBiz text,
gameUid text,
isChosen boolean,
@@ -53,7 +55,7 @@ create table if not exists GameAccount
region text,
regionName text,
updated text,
primary key (gameBiz, gameUid)
primary key (uid, gameUid)
);
-- @brief 移除名片表

View File

@@ -6,11 +6,9 @@
import { app } from "@tauri-apps/api";
import { AppNameCardsData, AppCharacterData } from "../../../data/index.js";
import { getBuildTime } from "../../../utils/TGBuild.js";
import initTableSql from "./initTable.js";
import { insertNameCardData, insertCharacterData } from "./insertData.js";
/**
* @description 初始化应用表数据
@@ -41,24 +39,6 @@ async function initAppData(): Promise<string[]> {
return sqlRes;
}
/**
* @description 初始化应用名片数据
* @since Alpha v0.2.0
* @returns {string[]} sql
*/
function initNameCardData(): string[] {
return AppNameCardsData.map((item) => insertNameCardData(item));
}
/**
* @description 初始化角色数据
* @since Alpha v0.2.0
* @returns {string[]} sql
*/
function initCharacterData(): string[] {
return AppCharacterData.map((item) => insertCharacterData(item));
}
/**
* @description 初始化数据
* @since Beta v0.4.5
@@ -68,8 +48,6 @@ async function initDataSql(): Promise<string[]> {
const sqlRes: string[] = [];
sqlRes.push(...initTableSql());
sqlRes.push(...(await initAppData()));
sqlRes.push(...initNameCardData());
sqlRes.push(...initCharacterData());
return sqlRes;
}

View File

@@ -4,8 +4,8 @@
* @since Beta v0.6.0
*/
import { timestampToDate } from "../../../utils/toolFunc.js";
import { transUserRecord } from "../utils/transUserRecord.js";
import { transUserRoles } from "../utils/transUserRoles.js";
/**
* @description 插入应用数据
@@ -23,123 +23,27 @@ export function insertAppData(key: string, value: string): string {
`;
}
/**
* @description 插入游戏账号数据
* @since Alpha v0.2.0
* @param {TGApp.User.Account.Game} data 游戏账号数据
* @returns {string} sql
*/
export function insertGameAccountData(data: TGApp.User.Account.Game): string {
const isChosen = data.is_chosen ? 1 : 0;
const isOfficial = data.is_official ? 1 : 0;
return `
INSERT INTO GameAccount (gameBiz, gameUid, isChosen, isOfficial, level, nickname, region, regionName, updated)
VALUES ('${data.game_biz}', '${data.game_uid}', ${isChosen}, ${isOfficial}, ${data.level}, '${data.nickname}',
'${data.region}', '${data.region_name}', datetime('now', 'localtime'))
ON CONFLICT(gameBiz, gameUid) DO UPDATE
SET isChosen = ${isChosen},
isOfficial = ${isOfficial},
level = ${data.level},
nickname = '${data.nickname}',
region = '${data.region}',
regionName = '${data.region_name}',
updated = datetime('now', 'localtime');
`;
}
/**
* @description 插入名片数据
* @since Alpha v0.2.0
* @param {TGApp.App.NameCard.Item} data 名片数据
* @returns {string} sql
*/
export function insertNameCardData(data: TGApp.App.NameCard.Item): string {
return `
INSERT INTO NameCard (name, "desc", type, source, updated)
VALUES ('${data.name}', '${data.desc}', '${data.type}', '${data.source}', datetime('now', 'localtime'))
ON CONFLICT(name, type) DO UPDATE
SET "desc" = '${data.desc}',
source = '${data.source}',
updated = datetime('now', 'localtime');
`;
}
/**
* @description 插入角色数据
* @since Beta v0.3.3
* @param {TGApp.User.Character.Item} data 角色数据
* @returns {string} sql
*/
export function insertCharacterData(data: TGApp.App.Character.WikiBriefInfo): string {
return `
INSERT INTO AppCharacters (id, name, title, birthday, star, element, weapon, nameCard, updated)
VALUES (${data.id}, '${data.name}', '${data.title}', '${data.birthday.toString()}',
${data.star}, '${data.element}', '${data.weapon}', '${data.nameCard}',
datetime('now', 'localtime'))
ON CONFLICT(id) DO UPDATE
SET name = '${data.name}',
title = '${data.title}',
star = ${data.star},
element = '${data.element}',
weapon = '${data.weapon}',
nameCard = '${data.nameCard}',
birthday = '${data.birthday.toString()}';
`;
}
/**
* @description 插入原神战绩数据
* @since Alpha v0.2.0
* @since Beta v0.6.0
* @param {TGApp.Game.Record.FullData} data 原神战绩数据
* @param {string} uid 用户 UID
* @returns {string} sql
*/
export function insertRecordData(data: TGApp.Game.Record.FullData, uid: string): string {
const transData = transUserRecord(data);
const timeNow = timestampToDate(new Date().getTime());
transData.uid = uid;
return `
INSERT INTO UserRecord(uid, role, avatars, stats, worldExplore, homes, updated)
VALUES ('${transData.uid}', '${transData.role}', '${transData.avatars}', '${transData.stats}',
'${transData.worldExplore}', '${transData.homes}', datetime('now', 'localtime'))
'${transData.worldExplore}', '${transData.homes}', '${timeNow}')
ON CONFLICT(uid) DO UPDATE
SET role = '${transData.role}',
avatars = '${transData.avatars}',
stats = '${transData.stats}',
worldExplore = '${transData.worldExplore}',
homes = '${transData.homes}',
updated = datetime('now', 'localtime');
updated = '${timeNow}';
`;
}
/**
* @description 插入用户角色数据
* @since Beta v0.5.3
* @param {string} uid 用户 UID
* @param {TGApp.Game.Avatar.DetailList[]} data 角色数据
* @returns {string} sql
*/
export function insertRoleData(uid: string, data: TGApp.Game.Avatar.DetailList[]): string {
const sql = data.map((item) => {
const role = transUserRoles(item);
return `
INSERT INTO UserCharacters (uid, cid, avatar, weapon, relics, constellations, costumes, skills,
propSelected, propBase, propExtra, propRecommend, updated)
VALUES (${uid}, ${role.cid}, '${role.avatar}', '${role.weapon}', '${role.relics}', '${role.constellations}',
'${role.costumes}', '${role.skills}', '${role.propSelected}', '${role.propBase}', '${role.propExtra}',
'${role.propRecommend}', datetime('now', 'localtime'))
ON CONFLICT(uid, cid) DO UPDATE
SET avatar = '${role.avatar}',
weapon = '${role.weapon}',
relics = '${role.relics}',
constellations = '${role.constellations}',
costumes = '${role.costumes}',
skills = '${role.skills}',
propSelected = '${role.propSelected}',
propBase = '${role.propBase}',
propExtra = '${role.propExtra}',
propRecommend = '${role.propRecommend}',
updated = datetime('now', 'localtime');
`;
});
return sql.join("");
}

View File

@@ -1,31 +0,0 @@
/**
* @file plugins/Sqlite/utils/transUserRoles.ts
* @description 转换用户角色数据格式,用于数据库存储
* @since Beta v0.5.3
*/
/**
* @description 将通过 api 获取到的用户角色数据转换为数据库中的数据
* @since Beta v0.5.3
* @param {TGApp.Game.Character.ListItem} data 用户角色数据
* @returns {TGApp.Sqlite.Character.UserRole} 转换后的用户角色数据
*/
export function transUserRoles(
data: TGApp.Game.Avatar.DetailList,
): TGApp.Sqlite.Character.UserRoleDB {
return {
uid: -1,
cid: data.base.id,
avatar: JSON.stringify(data.base),
weapon: JSON.stringify(data.weapon),
relics: JSON.stringify(data.relics),
constellations: JSON.stringify(data.constellations),
costumes: JSON.stringify(data.costumes),
skills: JSON.stringify(data.skills),
propSelected: JSON.stringify(data.selected_properties),
propBase: JSON.stringify(data.base_properties),
propExtra: JSON.stringify(data.extra_properties),
propRecommend: JSON.stringify(data.recommend_relic_property),
updated: "",
};
}