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

#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

@@ -24,6 +24,7 @@ import TSidebar from "./components/app/t-sidebar.vue";
import showConfirm from "./components/func/confirm.js";
import showSnackbar from "./components/func/snackbar.js";
import TGSqlite from "./plugins/Sqlite/index.js";
import TSUserAccount from "./plugins/Sqlite/modules/userAccount.js";
import { useAppStore } from "./store/modules/app.js";
import { useUserStore } from "./store/modules/user.js";
import { getBuildTime } from "./utils/TGBuild.js";
@@ -132,51 +133,40 @@ async function checkDeviceFp(): Promise<void> {
}
}
// 检测 ck,info 数据
async function checkUserLoad(): Promise<void> {
const ckDB = await TGSqlite.getCookie();
if (JSON.stringify(ckDB) === "{}" && appStore.isLogin) {
showSnackbar({
text: "获取 Cookie 失败!请重新登录!",
color: "error",
timeout: 3000,
});
appStore.isLogin = false;
await TGLogger.Error("[App][checkUserLoad] 获取 Cookie 失败!");
return;
}
if (JSON.stringify(ckDB) !== "{}" && !appStore.isLogin) appStore.isLogin = true;
const ckLocal = userStore.cookie.value;
if (JSON.stringify(ckLocal) !== JSON.stringify(ckDB)) userStore.cookie.value = ckDB;
const infoLocal = userStore.briefInfo.value;
// 检测用户数据目录
const appData = await TGSqlite.getAppData();
const infoDB = appData.find((item) => item.key === "userInfo")?.value;
if (typeof infoDB === "undefined" && JSON.stringify(infoLocal) !== "{}") {
await TGSqlite.saveAppData("userInfo", JSON.stringify(infoLocal));
} else if (typeof infoDB !== "undefined" && infoLocal !== JSON.parse(infoDB)) {
userStore.briefInfo.value = JSON.parse(infoDB);
console.info("briefInfo 数据已更新!");
}
const accountLocal = userStore.account.value;
const accountDB = await TGSqlite.getCurAccount();
if (accountDB === false) {
if (!appStore.isLogin) return;
showSnackbar({
text: "获取 GameAccount 失败!请尝试更新数据库!",
color: "error",
timeout: 3000,
});
await TGLogger.Error("[App][checkUserLoad] 获取 GameAccount 失败!");
return;
}
if (accountDB !== accountLocal) userStore.account.value = accountDB;
const userDir = appData.find((item) => item.key === "userDir")?.value;
if (typeof userDir === "undefined") {
await TGSqlite.saveAppData("userDir", appStore.userDir);
if (typeof userDir === "undefined") await TGSqlite.saveAppData("userDir", appStore.userDir);
else if (userDir !== appStore.userDir) appStore.userDir = userDir;
await mkdir(appStore.userDir, { recursive: true });
// 检测用户数据
const uidDB = await TSUserAccount.account.getAllUid();
if (uidDB.length === 0) {
showSnackbar({ text: "未检测到可用UID请重新登录!", color: "warn" });
return;
}
if (userDir !== appStore.userDir) appStore.userDir = userDir;
await mkdir(appStore.userDir, { recursive: true });
// 然后获取最近的UID
if (userStore.uid.value === undefined || !uidDB.includes(userStore.uid.value)) {
userStore.uid.value = uidDB[0];
}
const curAccount = await TSUserAccount.account.getAccount(userStore.uid.value);
if (curAccount === false) {
showSnackbar({ text: `未获取到${userStore.uid.value}账号数据`, color: "error" });
await TGLogger.Error(`[App][listenOnInit] 获取${userStore.uid.value}账号数据失败`);
await new Promise((resolve) => setTimeout(resolve, 1000));
} else {
userStore.briefInfo.value = curAccount.brief;
userStore.cookie.value = curAccount.cookie;
}
const curGameAccount = await TSUserAccount.game.getCurAccount(userStore.uid.value);
if (curGameAccount === false) {
showSnackbar({ text: `未获取到${userStore.uid.value}游戏数据`, color: "error" });
await TGLogger.Error(`[App][listenOnInit] 获取${userStore.uid.value}游戏数据失败`);
await new Promise((resolve) => setTimeout(resolve, 1000));
} else {
userStore.account.value = curGameAccount;
}
}
async function getDeepLink(): Promise<UnlistenFn> {

View File

@@ -6,6 +6,36 @@
<template #title>{{ userInfo.nickname }}</template>
<template #subtitle>UID:{{ userInfo.uid }}</template>
<template #text>{{ userInfo.desc }}</template>
<template #append>
<v-menu location="start">
<template v-slot:activator="{ props }">
<v-btn
variant="outlined"
@click="showAccounts()"
title="切换默认游戏账户"
v-bind="props"
icon="mdi-gamepad-variant"
/>
</template>
<v-list>
<v-list-item
v-for="account in gameAccounts"
:key="account.gameUid"
@click="switchGameAccount(account)"
>
<v-list-item-title>{{ account.nickname }}</v-list-item-title>
<v-list-item-subtitle>
{{ account.gameUid }}({{ account.regionName }})
</v-list-item-subtitle>
<template #append>
<div v-if="account.gameUid === userStore.account.value.gameUid" title="当前登录账号">
<v-icon color="green">mdi-check</v-icon>
</div>
</template>
</v-list-item>
</v-list>
</v-menu>
</template>
<template #actions>
<v-spacer />
<v-btn
@@ -16,26 +46,50 @@
/>
<v-btn
variant="outlined"
@click="confirmRefreshUser"
@click="confirmRefreshUser(userStore.uid.value!)"
:disabled="userStore.uid.value === undefined"
icon="mdi-refresh"
:loading="loading"
title="刷新用户信息"
/>
<v-btn variant="outlined" @click="confirmCopyCookie" icon="mdi-cookie" title="复制Cookie" />
<v-menu location="start">
<template v-slot:activator="{ props }">
<v-btn
variant="outlined"
icon="mdi-account-switch"
title="切换账户"
@click="showMenu"
v-bind="props"
/>
</template>
<v-list>
<v-list-item
v-for="account in accounts"
:key="account.uid"
@click="loadAccount(account.uid)"
>
<v-list-item-title>{{ account.brief.nickname }}</v-list-item-title>
<v-list-item-subtitle>{{ account.brief.uid }}</v-list-item-subtitle>
<template #append>
<div v-if="account.uid === userStore.uid.value" title="当前登录账号">
<v-icon color="green">mdi-check</v-icon>
</div>
</template>
</v-list-item>
</v-list>
</v-menu>
</template>
</v-card>
</template>
<script lang="ts" setup>
import { UnlistenFn } from "@tauri-apps/api/event";
import { storeToRefs } from "pinia";
import { onMounted, onUnmounted, ref, watch } from "vue";
import { computed, ref } from "vue";
import Mys from "../../plugins/Mys/index.js";
import TGSqlite from "../../plugins/Sqlite/index.js";
import { useAppStore } from "../../store/modules/app.js";
import TSUserAccount from "../../plugins/Sqlite/modules/userAccount.js";
import { useUserStore } from "../../store/modules/user.js";
import TGLogger from "../../utils/TGLogger.js";
import { getDeviceFp } from "../../web/request/getDeviceFp.js";
import TGRequest from "../../web/request/TGRequest.js";
import showConfirm from "../func/confirm.js";
import showGeetest from "../func/geetest.js";
@@ -46,58 +100,36 @@ interface TcUserBadgeEmits {
}
const emits = defineEmits<TcUserBadgeEmits>();
const appStore = useAppStore();
const userStore = storeToRefs(useUserStore());
const loading = ref<boolean>(false);
const userInfo = ref<TGApp.App.Account.BriefInfo>({
nickname: "未登录",
uid: "-1",
desc: "请扫码登录",
avatar: "/source/UI/lumine.webp",
});
let signListener: UnlistenFn;
onMounted(() => {
if (userStore.briefInfo.value && userStore.briefInfo.value.nickname) {
userInfo.value = userStore.briefInfo.value;
}
});
watch(userStore.briefInfo, (v) => {
if (v && v.nickname) {
userInfo.value = v;
}
const accounts = ref<TGApp.App.Account.User[]>([]);
const gameAccounts = ref<TGApp.Sqlite.Account.Game[]>([]);
const userInfo = computed<TGApp.App.Account.BriefInfo>(() => {
if (userStore.uid.value === undefined)
return {
nickname: "未登录",
uid: "-1",
desc: "请使用短信验证码登录",
avatar: "/source/UI/lumine.webp",
};
return userStore.briefInfo.value;
});
async function tryCaptchaLogin(): Promise<void> {
const phone = await showConfirm({
mode: "input",
title: "请输入手机号",
text: "+86",
});
const phone = await showConfirm({ mode: "input", title: "请输入手机号", text: "+86" });
if (!phone) {
showSnackbar({
color: "cancel",
text: "已取消验证码登录",
});
showSnackbar({ color: "cancel", text: "已取消验证码登录" });
return;
}
const phoneReg = /^1[3-9]\d{9}$/;
if (!phoneReg.test(phone)) {
showSnackbar({
color: "error",
text: "请输入正确的手机号",
});
showSnackbar({ color: "error", text: "请输入正确的手机号" });
return;
}
const actionType = await tryGetCaptcha(phone);
if (!actionType) return;
showSnackbar({
text: `已发送验证码到 ${phone}`,
});
showSnackbar({ text: `已发送验证码到 ${phone}` });
const captcha = await showConfirm({
mode: "input",
title: "请输入验证码",
@@ -105,15 +137,13 @@ async function tryCaptchaLogin(): Promise<void> {
otcancel: false,
});
if (!captcha) {
showSnackbar({
color: "error",
text: "输入验证码为空",
});
showSnackbar({ color: "error", text: "输入验证码为空" });
return;
}
const loginResp = await tryLoginByCaptcha(phone, captcha, actionType);
if (!loginResp) return;
userStore.cookie.value = {
loading.value = true;
const ck: TGApp.App.Account.Cookie = {
account_id: loginResp.user_info.aid,
ltuid: loginResp.user_info.aid,
stuid: loginResp.user_info.aid,
@@ -122,34 +152,84 @@ async function tryCaptchaLogin(): Promise<void> {
stoken: loginResp.token.token,
ltoken: "",
};
showSnackbar({
text: "登录成功,即将刷新用户信息",
color: "success",
});
setTimeout(() => {
refreshUser();
}, 1000);
}
async function refreshUser() {
const ck = userStore.cookie.value;
if (ck === undefined || JSON.stringify(ck) === "{}") {
await TGLogger.Error("[tc-userBadge][refreshUser] cookie 不存在");
showSnackbar({
color: "error",
text: "登录后才能刷新用户信息!",
});
appStore.isLogin = false;
emits("loadOuter", { show: true, title: "正在获取 LToken" });
const ltokenRes = await TGRequest.User.bySToken.getLToken(ck.mid, ck.stoken);
if (typeof ltokenRes !== "string") {
showSnackbar({ text: `[${ltokenRes.retcode}]${ltokenRes.message}`, color: "error" });
await TGLogger.Error(`获取LToken失败${ltokenRes.retcode}-${ltokenRes.message}`);
loading.value = false;
emits("loadOuter", { show: false });
return;
}
ck.ltoken = ltokenRes;
emits("loadOuter", { show: true, title: "正在获取 cookieToken " });
const cookieTokenRes = await TGRequest.User.bySToken.getCookieToken(ck.mid, ck.stoken);
if (typeof cookieTokenRes !== "string") {
showSnackbar({ text: `[${cookieTokenRes.retcode}]${cookieTokenRes.message}`, color: "error" });
await TGLogger.Error(
`获取CookieToken失败${cookieTokenRes.retcode}-${cookieTokenRes.message}`,
);
loading.value = false;
emits("loadOuter", { show: false });
return;
}
ck.cookie_token = cookieTokenRes;
emits("loadOuter", { show: true, title: "正在获取用户信息" });
const briefRes = await TGRequest.User.byCookie.getUserInfo(ck.cookie_token, ck.account_id);
if ("retcode" in briefRes) {
showSnackbar({ text: `[${briefRes.retcode}]${briefRes.message}` });
await TGLogger.Error(`获取用户数据失败:${briefRes.retcode}-${briefRes.message}`);
loading.value = false;
emits("loadOuter", { show: false });
return;
}
const briefInfo: TGApp.App.Account.BriefInfo = {
nickname: briefRes.nickname,
uid: briefRes.uid,
avatar: briefRes.avatar_url,
desc: briefRes.introduce,
};
emits("loadOuter", { show: true, title: "正在保存并切换用户" });
await TSUserAccount.account.saveAccount({
uid: briefInfo.uid,
cookie: ck,
brief: briefInfo,
updated: "",
});
userStore.uid.value = briefInfo.uid;
userStore.briefInfo.value = briefInfo;
userStore.cookie.value = ck;
emits("loadOuter", { show: true, title: "正在获取游戏账号" });
const gameRes = await TGRequest.User.bySToken.getAccounts(ck.stoken, ck.stuid);
if (!Array.isArray(gameRes)) {
loading.value = false;
emits("loadOuter", { show: false });
showSnackbar({ text: `[${gameRes.retcode}]${gameRes.message}` });
return;
}
await TSUserAccount.game.saveAccounts(briefInfo.uid, gameRes);
const curAccount = await TSUserAccount.game.getCurAccount(briefInfo.uid);
if (!curAccount) {
showSnackbar({ text: "未检测到游戏账号,请重新刷新", color: "warn" });
loading.value = false;
emits("loadOuter", { show: false });
return;
}
userStore.account.value = curAccount;
loading.value = false;
emits("loadOuter", { show: false });
showSnackbar({ text: "成功加载用户数据!" });
}
async function refreshUser(uid: string) {
let account = await TSUserAccount.account.getAccount(uid);
if (!account) {
showSnackbar({ text: `未获取到${userStore.uid.value}账号数据,请重新登录!`, color: "error" });
return;
}
let ck = account.cookie;
loading.value = true;
emits("loadOuter", { show: true, title: "正在刷新用户信息" });
const deviceInfo = appStore.deviceInfo;
if (deviceInfo.device_fp === "00000000000") {
appStore.deviceInfo = await getDeviceFp(appStore.deviceInfo);
await TGLogger.Warn("[tc-userBadge][refreshUser] 刷新设备信息");
}
let failCount = 0;
emits("loadOuter", { show: true, title: "正在验证 LToken" });
const verifyLTokenRes = await TGRequest.User.byLToken.verify(ck.ltoken, ck.ltuid);
if (typeof verifyLTokenRes === "string") {
@@ -176,7 +256,6 @@ async function refreshUser() {
await TGLogger.Error(
`[tc-userBadge][refreshUser] ${ltokenRes.retcode}: ${ltokenRes.message}`,
);
failCount++;
}
}
emits("loadOuter", { show: true, title: "正在获取 CookieToken" });
@@ -199,93 +278,74 @@ async function refreshUser() {
await TGLogger.Error(
`[tc-userBadge][refreshUser] ${cookieTokenRes.retcode}: ${cookieTokenRes.message}`,
);
failCount++;
}
userStore.cookie.value = ck;
await TGSqlite.saveAppData("cookie", JSON.stringify(ck));
failCount = await refreshUserInfo();
if (failCount > 0) {
showSnackbar({
color: "error",
text: "刷新失败!重试或者重新扫码登录!",
});
} else {
showSnackbar({ text: "刷新成功!" });
appStore.isLogin = true;
}
loading.value = false;
emits("loadOuter", { show: false });
}
async function refreshUserInfo(): Promise<number> {
let failCount = 0;
const ck = userStore.cookie.value;
if (ck === undefined) {
showSnackbar({
text: "未获取到用户 ck!",
color: "error",
});
await TGLogger.Error("[tc-userBadge][refreshUserInfo] 未获取到用户 ck");
return 0;
}
account.cookie = ck;
emits("loadOuter", { show: true, title: "正在获取用户信息" });
const infoRes = await TGRequest.User.byCookie.getUserInfo(ck.cookie_token, ck.account_id);
if ("retcode" in infoRes) {
emits("loadOuter", { show: true, title: "正在获取用户信息", text: "获取用户信息失败!" });
await TGLogger.Error("[tc-userBadge][refreshUserInfo] 获取用户信息失败");
await TGLogger.Error(`[tc-userBadge][refreshUserInfo] ${infoRes.retcode}: ${infoRes.message}`);
failCount++;
} else {
emits("loadOuter", { show: true, title: "正在获取用户信息", text: "获取用户信息成功!" });
const briefInfo: TGApp.App.Account.BriefInfo = {
account.brief = {
nickname: infoRes.nickname,
uid: infoRes.uid,
avatar: infoRes.avatar_url,
desc: infoRes.introduce,
};
userStore.briefInfo.value = briefInfo;
await TGSqlite.saveAppData("userInfo", JSON.stringify(briefInfo));
await TGLogger.Info("[tc-userBadge][refreshUserInfo] 获取用户信息成功");
}
await TSUserAccount.account.saveAccount(account);
emits("loadOuter", { show: true, title: "正在获取账号信息" });
const accountRes = await TGRequest.User.byCookie.getAccounts(ck.cookie_token, ck.account_id);
if (Array.isArray(accountRes)) {
emits("loadOuter", { show: true, title: "正在获取账号信息", text: "获取账号信息成功!" });
await TGLogger.Info("[tc-userBadge][refreshUserInfo] 获取账号信息成功");
await TGSqlite.saveAccount(accountRes);
const curAccount = await TGSqlite.getCurAccount();
if (curAccount) userStore.account.value = curAccount;
await TSUserAccount.game.saveAccounts(account.uid, accountRes);
} else {
emits("loadOuter", { show: true, title: "正在获取账号信息", text: "获取账号信息失败!" });
await TGLogger.Error("[tc-userBadge][refreshUserInfo] 获取账号信息失败");
await TGLogger.Error(
`[tc-userBadge][refreshUserInfo] ${accountRes.retcode}: ${accountRes.message}`,
);
failCount++;
}
return failCount;
loading.value = false;
emits("loadOuter", { show: false });
}
async function confirmRefreshUser(): Promise<void> {
const res = await showConfirm({
title: "确认刷新用户信息吗?",
text: "将会重新获取用户信息",
});
async function loadAccount(uid: string): Promise<void> {
if (userStore.uid.value && uid === userStore.uid.value) {
showSnackbar({ text: "该账户已经登录,无需切换", color: "warn" });
return;
}
const account = await TSUserAccount.account.getAccount(uid);
if (!account) {
showSnackbar({ text: `无法获取${uid}的账号信息`, color: "warn" });
return;
}
userStore.uid.value = uid;
userStore.briefInfo.value = account.brief;
userStore.cookie.value = account.cookie;
const gameAccount = await TSUserAccount.game.getCurAccount(uid);
if (!gameAccount) {
showSnackbar({ text: `无法获取${uid}的游戏信息`, color: "warn" });
return;
}
userStore.account.value = gameAccount;
showSnackbar({ text: `成功切换到用户${uid}` });
}
async function confirmRefreshUser(uid: string): Promise<void> {
const res = await showConfirm({ title: "确认刷新用户信息吗?", text: "将会重新获取用户信息" });
if (!res) {
showSnackbar({
color: "cancel",
text: "已取消刷新",
});
showSnackbar({ color: "cancel", text: "已取消刷新" });
return;
}
if (!userStore.cookie) {
showSnackbar({
color: "error",
text: "请先登录",
});
return;
}
await refreshUser();
await refreshUser(uid);
const confirm = await showConfirm({ title: "是否切换用户?", text: `将切换到用户${uid}` });
if (!confirm) return;
await loadAccount(uid);
}
async function confirmCopyCookie(): Promise<void> {
@@ -294,35 +354,23 @@ async function confirmCopyCookie(): Promise<void> {
text: "将会复制当前登录的 Cookie",
});
if (!res) {
showSnackbar({
color: "cancel",
text: "已取消复制",
});
showSnackbar({ color: "cancel", text: "已取消复制" });
return;
}
if (!userStore.cookie) {
showSnackbar({
color: "error",
text: "请先登录",
});
if (!userStore.cookie.value) {
showSnackbar({ color: "error", text: "请先登录" });
return;
}
const ckText = useUserStore().getAllCookie();
const ckText = TSUserAccount.account.copy(userStore.cookie.value);
await navigator.clipboard.writeText(ckText);
showSnackbar({
text: "已复制 Cookie!",
color: "success",
});
showSnackbar({ text: "已复制 Cookie!", color: "success" });
}
async function tryGetCaptcha(phone: string, aigis?: string): Promise<string | false> {
const captchaResp = await Mys.User.getCaptcha(phone, aigis);
if ("retcode" in captchaResp) {
if (!captchaResp.data || captchaResp.data === "") {
showSnackbar({
text: `[${captchaResp.retcode}] ${captchaResp.message}`,
color: "error",
});
showSnackbar({ text: `[${captchaResp.retcode}] ${captchaResp.message}`, color: "error" });
return false;
}
const aigisResp: TGApp.Plugins.Mys.CaptchaLogin.CaptchaAigis = JSON.parse(captchaResp.data);
@@ -342,10 +390,7 @@ async function tryLoginByCaptcha(
const loginResp = await Mys.User.login(phone, captcha, actionType, aigis);
if ("retcode" in loginResp) {
if (!loginResp.data || loginResp.data === "") {
showSnackbar({
text: `[${loginResp.retcode}] ${loginResp.message}`,
color: "error",
});
showSnackbar({ text: `[${loginResp.retcode}] ${loginResp.message}`, color: "error" });
return false;
}
const aigisResp: TGApp.Plugins.Mys.CaptchaLogin.CaptchaAigis = JSON.parse(loginResp.data);
@@ -356,9 +401,29 @@ async function tryLoginByCaptcha(
return loginResp;
}
onUnmounted(() => {
if (signListener) signListener();
});
async function showMenu(): Promise<void> {
accounts.value = await TSUserAccount.account.getAllAccount();
}
async function showAccounts(): Promise<void> {
if (!userStore.uid.value) return;
gameAccounts.value = await TSUserAccount.game.getAccount(userStore.uid.value);
}
async function switchGameAccount(account: TGApp.Sqlite.Account.Game): Promise<void> {
if (account.gameUid === userStore.account.value.gameUid) {
showSnackbar({ text: "已经登录,无需切换!", color: "warn" });
return;
}
await TSUserAccount.game.switchAccount(account.uid, account.gameUid);
const gameAccount = await TSUserAccount.game.getCurAccount(account.uid);
if (!gameAccount) {
showSnackbar({ text: `无法获取${account.uid}的游戏信息`, color: "warn" });
return;
}
userStore.account.value = gameAccount;
showSnackbar({ text: "成功切换游戏账户!", color: "success" });
}
</script>
<style lang="css" scoped>
.tcu-box {

View File

@@ -1,10 +1,10 @@
<template>
<TItemBox :model-value="box" />
<TItemBox :model-value="box" v-if="box" />
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import TGSqlite from "../../plugins/Sqlite/index.js";
import { AppCharacterData } from "../../data/index.js";
import TItemBox from "../main/t-itembox.vue";
import type { TItemBoxData } from "../main/t-itembox.vue";
@@ -13,10 +13,11 @@ interface TibAbyssDetailProps {
}
const props = defineProps<TibAbyssDetailProps>();
const box = ref<TItemBoxData>(<TItemBoxData>{});
const box = ref<TItemBoxData>();
onMounted(async () => {
const res = await TGSqlite.getAppCharacter(props.modelValue.id);
const res = AppCharacterData.find((a) => a.id === props.modelValue.id);
if (res === undefined) return;
if (props.modelValue.id === 10000005 || props.modelValue.id === 10000007) {
box.value = {
clickable: false,

View File

@@ -1,10 +1,10 @@
<template>
<TItemBox v-model="box" />
<TItemBox v-model="box" v-if="box" />
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import TGSqlite from "../../plugins/Sqlite/index.js";
import { AppCharacterData } from "../../data/index.js";
import TItemBox from "../main/t-itembox.vue";
import type { TItemBoxData } from "../main/t-itembox.vue";
@@ -13,10 +13,11 @@ interface TibAbyssOverviewProps {
}
const props = defineProps<TibAbyssOverviewProps>();
const box = ref<TItemBoxData>(<TItemBoxData>{});
const box = ref<TItemBoxData>();
onMounted(async () => {
const res = await TGSqlite.getAppCharacter(props.modelValue.id);
onMounted(() => {
const res = AppCharacterData.find((a) => a.id === props.modelValue.id);
if (res === undefined) return;
box.value = {
height: "80px",
ltSize: "20px",

View File

@@ -4,7 +4,7 @@
<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import TGSqlite from "../../plugins/Sqlite/index.js";
import { AppCharacterData } from "../../data/index.js";
import TItemBox, { type TItemBoxData } from "../main/t-itembox.vue";
interface TibWikiAbyssProps {
@@ -12,33 +12,24 @@ interface TibWikiAbyssProps {
}
const props = defineProps<TibWikiAbyssProps>();
const defaultAvatar = <TGApp.Sqlite.Character.AppData>{
birthday: "",
element: "",
id: Number(props.modelValue),
name: "旅行者",
nameCard: "",
star: 5,
title: "",
updated: "",
weapon: "单手剑",
};
const avatar = ref<TGApp.Sqlite.Character.AppData>(defaultAvatar);
const avatar = ref<TGApp.App.Character.WikiBriefInfo>();
const box = computed<TItemBoxData>(() => {
return {
bg: `/icon/bg/${avatar.value?.star}-Star.webp`,
bg: `/icon/bg/${avatar.value?.star ?? 5}-Star.webp`,
clickable: false,
display: "outer",
height: "80px",
icon: `/WIKI/character/${avatar.value?.id}.webp`,
icon: `/WIKI/character/${props.modelValue}.webp`,
innerHeight: 20,
innerText: avatar.value.name,
innerText: avatar.value?.name ?? "旅行者",
lt:
avatar.value.element !== ""
? `/icon/element/${avatar.value.element}元素.webp`
: `/icon/weapon/${avatar.value.weapon}.webp`,
avatar.value === undefined
? ""
: avatar.value.element !== ""
? `/icon/element/${avatar.value.element}元素.webp`
: `/icon/weapon/${avatar.value.weapon}.webp`,
ltSize: "20px",
size: "80px",
};
@@ -49,6 +40,6 @@ onMounted(async () => {
if (props.modelValue === "10000005" || props.modelValue === "10000007") {
return;
}
avatar.value = await TGSqlite.getAppCharacter(Number(props.modelValue));
avatar.value = AppCharacterData.find((a) => a.id === props.modelValue)!;
});
</script>

View File

@@ -4,7 +4,7 @@
<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import TGSqlite from "../../plugins/Sqlite/index.js";
import { AppCharacterData } from "../../data/index.js";
import TItemBox, { type TItemBoxData } from "../main/t-itembox.vue";
interface TibWikiAbyssProps {
@@ -15,18 +15,8 @@ interface TibWikiAbyssProps {
}
const props = defineProps<TibWikiAbyssProps>();
const defaultAvatar = <TGApp.Sqlite.Character.AppData>{
birthday: "",
element: "",
id: props.modelValue.Item,
name: "旅行者",
nameCard: "",
star: 5,
title: "",
updated: "",
weapon: "单手剑",
};
const avatar = ref<TGApp.Sqlite.Character.AppData>(defaultAvatar);
const avatar = ref<TGApp.App.Character.WikiBriefInfo>();
const box = computed<TItemBoxData>(() => {
return {
@@ -38,12 +28,14 @@ const box = computed<TItemBoxData>(() => {
innerHeight: 20,
innerText: (props.modelValue.Rate * 100).toFixed(3) + "%",
lt:
avatar.value.element !== ""
? `/icon/element/${avatar.value.element}元素.webp`
: `/icon/weapon/${avatar.value.weapon}.webp`,
avatar.value === undefined
? ""
: avatar.value.element !== ""
? `/icon/element/${avatar.value.element}元素.webp`
: `/icon/weapon/${avatar.value.weapon}.webp`,
ltSize: "20px",
outerHeight: 20,
outerText: avatar.value.name,
outerText: avatar.value?.name ?? "旅行者",
size: "80px",
};
});
@@ -53,6 +45,6 @@ onMounted(async () => {
if (props.modelValue.Item === 10000005 || props.modelValue.Item === 10000007) {
return;
}
avatar.value = await TGSqlite.getAppCharacter(props.modelValue.Item);
avatar.value = AppCharacterData.find((a) => a.id === props.modelValue.Item);
});
</script>

View File

@@ -1,236 +0,0 @@
<template>
<TOverlay v-model="visible" hide blur-val="20px" :to-click="onCancel">
<div class="tog-box">
<div class="tog-top">
<div class="tog-title">请使用米游社APP进行操作</div>
<div class="tog-subtitle">所需米游社版本 >= 2.57.1</div>
</div>
<div class="tog-mid">
<qrcode-vue
class="tog-qr"
:value="qrCode"
render-as="svg"
:background="'var(--box-bg-1)'"
foreground="var(--box-text-1)"
/>
</div>
</div>
</TOverlay>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import QrcodeVue from "qrcode.vue";
import { computed, onUnmounted, reactive, ref, watch } from "vue";
import Mys from "../../plugins/Mys/index.js";
import { useUserStore } from "../../store/modules/user.js";
import TGLogger from "../../utils/TGLogger.js";
import TGRequest from "../../web/request/TGRequest.js";
import showSnackbar from "../func/snackbar.js";
import TOverlay from "../main/t-overlay.vue";
interface ToWebLoginProps {
modelValue: boolean;
}
type ToWebLoginEmits = {
(e: "update:modelValue", value: boolean): void;
(e: "success"): void;
};
const props = withDefaults(defineProps<ToWebLoginProps>(), {
modelValue: false,
});
const emits = defineEmits<ToWebLoginEmits>();
const visible = computed({
get: () => props.modelValue,
set: (value) => {
emits("update:modelValue", value);
},
});
// eslint-disable-next-line no-undef
let cycleTimer: NodeJS.Timeout | null = null;
const qrCode = ref<string>("");
const ticket = ref<string>("");
const cookie = reactive<TGApp.User.Account.Cookie>({
account_id: "",
ltuid: "",
stuid: "",
mid: "",
cookie_token: "",
stoken: "",
ltoken: "",
});
const userStore = storeToRefs(useUserStore());
watch(visible, async (value) => {
if (value) {
await freshQr();
cycleTimer = setInterval(cycleGetData, 1000);
}
});
function onCancel(): void {
visible.value = false;
showSnackbar({
text: "已取消登录",
color: "cancel",
});
if (cycleTimer !== null) {
clearInterval(cycleTimer);
cycleTimer = null;
}
}
async function freshQr(): Promise<void> {
const res = await Mys.User.getQr();
if ("retcode" in res) {
showSnackbar({
text: `[${res.retcode}] ${res.message}`,
color: "error",
});
return;
}
qrCode.value = res.url;
const ticketReg = /ticket=(\w+)/;
const ticketRes = ticketReg.exec(res.url);
if (ticketRes) {
ticket.value = ticketRes[1];
} else {
showSnackbar({
text: "获取ticket失败",
color: "error",
});
}
}
async function cycleGetData() {
if (cycleTimer === null) return;
const res = await Mys.User.getData(ticket.value);
console.log(res);
if ("retcode" in res) {
showSnackbar({
text: `[${res.retcode}] ${res.message}`,
color: "error",
});
if (res.retcode === -106) {
await freshQr();
} else {
clearInterval(cycleTimer);
cycleTimer = null;
visible.value = false;
}
return;
}
if (res.stat === "Init" || res.stat === "Scanned") {
return;
}
if (res.stat === "Confirmed") {
clearInterval(cycleTimer);
cycleTimer = null;
if (res.payload.proto !== "OpenToken" && res.payload.proto !== "Account") {
await TGLogger.Warn(`[to-gameLogin] 检测到意外协议:${res.payload.proto}`);
showSnackbar({
text: "请使用米游社APP进行扫码操作",
color: "error",
});
visible.value = false;
return;
}
if (res.payload.proto === "OpenToken") {
const data: TGApp.Plugins.Mys.GameLogin.StatusPayloadRawOpen = JSON.parse(res.payload.raw);
cookie.account_id = data.open_id;
cookie.ltuid = data.open_id;
cookie.stuid = data.open_id;
await getTokens(data.open_token);
} else {
const data: TGApp.Plugins.Mys.GameLogin.StatusPayloadRawAccount = JSON.parse(res.payload.raw);
cookie.account_id = data.uid;
cookie.ltuid = data.uid;
cookie.stuid = data.uid;
await getTokens(data.token, true);
}
showSnackbar({
text: "登录成功",
color: "success",
});
visible.value = false;
setTimeout(() => {
emits("success");
}, 1000);
}
}
async function getTokens(game_token: string, isGT: boolean = false): Promise<void> {
const stokenRes = await TGRequest.User.bgGameToken.getStoken(cookie.account_id, game_token, isGT);
if (!("retcode" in stokenRes)) {
cookie.stoken = stokenRes.token.token;
cookie.mid = stokenRes.user_info.mid;
} else {
await TGLogger.Error("[to-gameLogin] 获取stoken失败");
}
const cookieTokenRes = await TGRequest.User.bgGameToken.getCookieToken(
cookie.account_id,
game_token,
);
if (typeof cookieTokenRes === "string") cookie.cookie_token = cookieTokenRes;
else await TGLogger.Error("[to-gameLogin] 获取cookieToken失败");
const ltokenRes = await TGRequest.User.bySToken.getLToken(cookie.mid, cookie.stoken);
if (typeof ltokenRes === "string") cookie.ltoken = ltokenRes;
else await TGLogger.Error("[to-gameLogin] 获取ltoken失败");
userStore.cookie.value = cookie;
}
onUnmounted(() => {
if (cycleTimer !== null) clearInterval(cycleTimer);
cycleTimer = null;
});
</script>
<style lang="css" scoped>
.tog-box {
display: flex;
flex-direction: column;
padding: 10px;
border-radius: 5px;
background-color: var(--box-bg-1);
color: var(--app-page-content);
gap: 10px;
}
.tog-top {
border-bottom: 1px solid var(--common-shadow-4);
font-family: var(--font-title);
text-align: center;
}
.tog-title {
color: var(--common-text-title);
font-size: 20px;
}
.tog-subtitle {
font-size: 14px;
opacity: 0.6;
}
.tog-mid {
display: flex;
width: 100%;
align-items: center;
justify-content: center;
padding: 10px;
border: 1px solid var(--common-shadow-2);
border-radius: 5px;
aspect-ratio: 1;
background: var(--box-bg-2);
}
.tog-qr {
width: 256px;
height: 256px;
}
</style>

View File

@@ -109,16 +109,8 @@ watch(
);
async function loadData(): Promise<void> {
if (props.modelValue.cid === 10000005 || props.modelValue.cid === 10000007) {
bg.value = "url('/source/nameCard/profile/原神·印象.webp')";
} else {
const card = await TSUserAvatar.getAvatarCard(props.modelValue.cid);
if (card !== false) {
bg.value = `url("/source/nameCard/profile/${card}.webp")`;
} else {
bg.value = "url('/source/nameCard/profile/原神·印象.webp')";
}
}
const card = TSUserAvatar.getAvatarCard(props.modelValue.cid);
bg.value = `url("/source/nameCard/profile/${card}.webp")`;
if (!avatar.value.startsWith("blob:")) {
avatar.value = await saveImgLocal(props.modelValue.avatar.image);
}

View File

@@ -87,16 +87,8 @@ watch(
);
async function loadData(): Promise<void> {
if (props.modelValue.cid === 10000005 || props.modelValue.cid === 10000007) {
nameCard.value = "/source/nameCard/profile/原神·印象.webp";
} else {
const card = await TSUserAvatar.getAvatarCard(props.modelValue.cid);
if (card !== false) {
nameCard.value = `/source/nameCard/profile/${card}.webp`;
} else {
nameCard.value = false;
}
}
const card = TSUserAvatar.getAvatarCard(props.modelValue.cid);
nameCard.value = `/source/nameCard/profile/${card}.webp`;
}
async function share(): Promise<void> {

View File

@@ -160,7 +160,7 @@ async function refreshAbyss(): Promise<void> {
return;
}
if (uidCur.value && uidCur.value !== user.value.gameUid) {
const confirm = showConfirm({
const confirm = await showConfirm({
title: "确定刷新?",
text: `用户UID-${user.value.gameUid}与当前深渊UID-${uidCur.value}不一致`,
});

View File

@@ -7,7 +7,7 @@
</template>
<template #append>
<div class="uc-top-btns">
<v-btn @click="refresh()" rounded variant="outlined" v-model:loading="loadData">
<v-btn @click="refresh()" :rounded="true" variant="outlined" v-model:loading="loadData">
<template #prepend>
<v-icon>mdi-refresh</v-icon>
</template>
@@ -16,7 +16,7 @@
<v-btn
:disabled="enableShare"
@click="share()"
rounded
:rounded="true"
variant="outlined"
v-model:loading="loadShare"
>
@@ -35,7 +35,7 @@
v-model="showMode"
:items="modeList"
label="详情视图模式"
hide-details
:hide-details="true"
item-title="label"
item-value="value"
variant="outlined"
@@ -126,7 +126,7 @@ const modeList = [
const enableShare = computed<boolean>(() => {
if (showOverlay.value) return true;
return !!showSelect.value;
return showSelect.value;
});
onBeforeMount(() => {

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: "",
};
}

View File

@@ -1,7 +1,7 @@
/**
* @file store/modules/user.ts
* @description 用户信息模块
* @since Beta v0.5.5
* @since Beta v0.6.0
*/
import { defineStore } from "pinia";
@@ -17,6 +17,7 @@ export const useUserStore = defineStore(
desc: "",
});
const account = ref<TGApp.Sqlite.Account.Game>({
uid: "",
gameBiz: "",
gameUid: "",
isChosen: 0,
@@ -25,67 +26,32 @@ export const useUserStore = defineStore(
nickname: "",
region: "",
regionName: "",
updated: "",
});
const cookie = ref<TGApp.User.Account.Cookie>();
const uid = ref<string>();
const cookie = ref<TGApp.App.Account.Cookie>();
const propMap = ref<TGApp.Game.Avatar.PropMap>();
function getAllCookie(): string {
let res = "";
if (!cookie.value) return res;
if (cookie.value.ltuid && cookie.value.ltuid !== "") {
res += `ltuid=${cookie.value.ltuid};`;
}
if (cookie.value.ltoken && cookie.value.ltoken !== "") {
res += `ltoken=${cookie.value.ltoken};`;
}
if (cookie.value.mid && cookie.value.mid !== "") {
res += `mid=${cookie.value.mid};`;
}
if (cookie.value.cookie_token && cookie.value.cookie_token !== "") {
res += `cookie_token=${cookie.value.cookie_token};`;
}
if (cookie.value.stoken && cookie.value.stoken !== "") {
res += `stoken=${cookie.value.stoken};`;
}
if (cookie.value.stuid && cookie.value.stuid !== "") {
res += `stuid=${cookie.value.stuid};`;
}
if (cookie.value.account_id && cookie.value.account_id !== "") {
res += `account_id=${cookie.value.account_id};`;
}
return res;
}
function getProp(prop: number): TGApp.Game.Avatar.PropMapItem | false {
if (!propMap.value) return false;
return propMap.value[prop.toString()] || false;
}
return {
uid,
cookie,
briefInfo,
account,
propMap,
getAllCookie,
getProp,
};
},
{
persist: [
{
key: "cookie",
key: "curAccount",
storage: window.localStorage,
pick: ["cookie"],
},
{
key: "briefInfo",
storage: window.localStorage,
pick: ["briefInfo"],
},
{
key: "account",
storage: window.localStorage,
pick: ["account"],
pick: ["uid", "briefInfo", "cookie", "account"],
},
{
key: "propMap",

View File

@@ -1,11 +1,33 @@
/**
* @file types App Account.d.ts
* @file types/App/Account.d.ts
* @description App 账号相关类型定义文件
* @author BTMuli<bt-muli@outlook.com>
* @since Alpha v0.2.0
* @since Beta v0.6.0
*/
/**
* @description 应用账户类型声明
* @since Beta v0.6.0
* @namespace TGApp.App.Account
* @memberof TGApp.App
*/
declare namespace TGApp.App.Account {
/**
* @description 用户数据
* @since Beta v0.6.0
* @interface User
* @property {string} uid - 米社UID
* @property {BriefInfo} brief - 简略信息
* @property {Cookie} cookie - 用户cookie
* @property {string} updated - 更新时间
* @returns User
*/
interface User {
uid: string;
brief: BriefInfo;
cookie: Cookie;
updated: string;
}
/**
* @description 用户简略信息
* @since Alpha v0.2.0
@@ -16,10 +38,32 @@ declare namespace TGApp.App.Account {
* @property {string} desc 用户简介
* @return BriefInfo
*/
export interface BriefInfo {
interface BriefInfo {
nickname: string;
uid: string;
avatar: string;
desc: string;
}
/**
* @description 用户cookie
* @since Beta v0.6.0
* @interface Cookie
* @property {string} account_id 账号 ID
* @property {string} cookie_token Cookie Token
* @property {string} ltoken LToken
* @property {string} ltuid LTUID
* @property {string} mid MID
* @property {string} stoken SToken_v2
* @return Cookie
*/
interface Cookie {
account_id: string;
cookie_token: string;
ltoken: string;
ltuid: string;
mid: string;
stoken: string;
stuid: string;
}
}

View File

@@ -1,12 +1,12 @@
/**
* @file types/BBS/Account.d.ts
* @description BBS 账户相关类型定义文件
* @since Beta v0.3.4
* @since Beta v0.6.0
*/
/**
* @description 米游社账户信息
* @since Beta v0.3.4
* @since Beta v0.6.0
* @namespace TGApp.BBS.Account
* @memberof TGApp.BBS
*/
@@ -145,4 +145,29 @@ declare namespace TGApp.BBS.Account {
tap_name: string;
reactivate_ticket: string;
}
/**
* @description 游戏账号类型
* @interface GameAccount
* @since Beta v0.6.0
* @property {string} game_biz 游戏 biz例如 hk4e_cn
* @property {string} game_uid 游戏 uid
* @property {boolean} is_chosen 是否为当前选中账号
* @property {boolean} is_official 是否为官服账号
* @property {string} level 游戏等级
* @property {string} nickname 游戏昵称
* @property {string} region 游戏区域
* @property {string} region_name 游戏区域名称
* @return Game
*/
interface GameAccount {
game_biz: string;
game_uid: string;
is_chosen: boolean;
is_official: boolean;
level: string;
nickname: string;
region: string;
region_name: string;
}
}

View File

@@ -1,12 +1,12 @@
/**
* @file types/BBS/Response.d.ts
* @description BBS 返回数据类型定义文件
* @since Beta v0.4.3
* @since Beta v0.6.0
*/
/**
* @description BBS 返回数据类型定义
* @since Beta v0.4.3
* @since Beta v0.6.0
* @namespace TGApp.BBS.Response
* @memberof TGApp.BBS
*/
@@ -209,4 +209,18 @@ declare namespace TGApp.BBS.Response {
msg: string;
};
}
/**
* @description 获取游戏账户数据
* @interface getGameAccounts
* @since Beta v0.6.0
* @extends BaseWithData
* @property {TGApp.BBS.Account.GameAccount[]} data.list - 返回数据
* @returns getGameAccounts
*/
interface getGameAccounts extends BaseWithData {
data: {
list: TGApp.BBS.Account.GameAccount[];
};
}
}

View File

@@ -1,15 +1,32 @@
/**
* @file types Sqlite Account.d.ts
* @file types/Sqlite/Account.d.ts
* @description Sqlite Account 类型定义文件
* @author BTMuli<bt-muli@outlook.com>
* @since Alpha v0.1.5
* @since Beta v0.6.0
*/
declare namespace TGApp.Sqlite.Account {
/**
* @description UserAccount 表数据类型
* @since Beta v0.6.0
* @interface User
* @property {string} uid - 米社UID
* @property {string} brief - 用户信息
* @property {string} cookie - 用户cookie
* @property {string} updated - 更新时间
* @returns User
*/
interface User {
uid: string;
brief: string;
cookie: string;
updated: string;
}
/**
* @description 游戏账号类型
* @since Alpha v0.1.5
* @since Beta v0.6.0
* @interface Game
* @property {string} uid 米社UID
* @property {string} gameBiz 游戏 biz例如 hk4e_cn
* @property {string} gameUid 游戏 uid
* @property {number} isChosen 是否为当前选中账号
@@ -18,9 +35,11 @@ declare namespace TGApp.Sqlite.Account {
* @property {string} nickname 游戏昵称
* @property {string} region 游戏区域
* @property {string} regionName 游戏区域名称
* @property {string} updated 更新时间
* @return Game
*/
export interface Game {
interface Game {
uid: string;
gameBiz: string;
gameUid: string;
isChosen: 0 | 1;
@@ -29,5 +48,6 @@ declare namespace TGApp.Sqlite.Account {
nickname: string;
region: string;
regionName: string;
updated: string;
}
}

View File

@@ -1,75 +0,0 @@
/**
* @file types/User/Account.d.ts
* @description 用户账号相关类型定义文件
* @since Beta v0.4.3
*/
/**
* @description 用户账号相关类型定义命名空间
* @since Beta v0.4.3
* @namespace TGApp.User.Account
* @memberof TGApp.User
*/
declare namespace TGApp.User.Account {
/**
* @description 游戏账号返回类型
* @interface GameResponse
* @since Alpha v0.1.5
* @extends TGApp.BBS.Response.BaseWithData
* @property {Game[]} data.list 游戏账号列表
* @return GameResponse
*/
interface GameResponse extends TGApp.BBS.Response.BaseWithData {
data: {
list: Game[];
};
}
/**
* @description 游戏账号类型
* @interface Game
* @since Alpha v0.1.5
* @property {string} game_biz 游戏 biz例如 hk4e_cn
* @property {string} game_uid 游戏 uid
* @property {boolean} is_chosen 是否为当前选中账号
* @property {boolean} is_official 是否为官服账号
* @property {string} level 游戏等级
* @property {string} nickname 游戏昵称
* @property {string} region 游戏区域
* @property {string} region_name 游戏区域名称
* @return Game
*/
interface Game {
game_biz: string;
game_uid: string;
is_chosen: boolean;
is_official: boolean;
level: string;
nickname: string;
region: string;
region_name: string;
}
/**
* @description 用户 Cookie 类型
* @since Beta v0.4.3
* @interface Cookie
* @memberof TGApp.User.Account
* @property {string} account_id 账号 ID
* @property {string} cookie_token Cookie Token
* @property {string} ltoken LToken
* @property {string} ltuid LTUID
* @property {string} mid MID
* @property {string} stoken SToken_v2
* @return Cookie
*/
interface Cookie {
account_id: string;
cookie_token: string;
ltoken: string;
ltuid: string;
mid: string;
stoken: string;
stuid: string;
}
}

View File

@@ -1,7 +1,7 @@
/**
* @file web/request/getGameAccounts.ts
* @description 获取游戏账号信息相关请求函数
* @since Beta v0.5.0
* @since Beta v0.6.0
*/
import TGHttp from "../../utils/TGHttp.js";
@@ -14,12 +14,12 @@ import TGUtils from "../utils/TGUtils.js";
* @since Alpha v0.1.5
* @param {string} stoken stoken
* @param {string} stuid 登录用户 uid
* @returns {Promise<TGApp.User.Game.Account[]|TGApp.BBS.Response.Base>}
* @returns {Promise<TGApp.BBS.Account.GameAccount[]|TGApp.BBS.Response.Base>}
*/
export async function getGameAccountsBySToken(
stoken: string,
stuid: string,
): Promise<TGApp.User.Account.Game[] | TGApp.BBS.Response.Base> {
): Promise<TGApp.BBS.Account.GameAccount[] | TGApp.BBS.Response.Base> {
const url = TGApi.GameData.bySToken.getAccounts;
const cookie = { stuid, stoken };
const params = { stoken, stuid, game_biz: TGConstant.Utils.GAME_BIZ };
@@ -31,12 +31,12 @@ export async function getGameAccountsBySToken(
* @since Alpha v0.1.5
* @param {string} cookie_token cookie_token
* @param {string} account_id 游戏账号 id
* @returns {Promise<TGApp.User.Account.Game[]|TGApp.BBS.Response.Base>}
* @returns {Promise<TGApp.BBS.Account.GameAccount[]|TGApp.BBS.Response.Base>}
*/
export async function getGameAccountsByCookie(
cookie_token: string,
account_id: string,
): Promise<TGApp.User.Account.Game[] | TGApp.BBS.Response.Base> {
): Promise<TGApp.BBS.Account.GameAccount[] | TGApp.BBS.Response.Base> {
const url = TGApi.GameData.byCookie.getAccounts;
const cookie = { account_id, cookie_token };
const params = { game_biz: TGConstant.Utils.GAME_BIZ };
@@ -49,15 +49,15 @@ export async function getGameAccountsByCookie(
* @param {string} url 请求地址
* @param {Record<string, string>} cookie cookie
* @param {Record<string, string>} params 请求参数
* @returns {Promise<TGApp.User.Account.Game[]|TGApp.BBS.Response.Base>}
* @returns {Promise<TGApp.BBS.Account.GameAccount[]|TGApp.BBS.Response.Base>}
*/
async function getGameAccounts(
url: string,
cookie: Record<string, string>,
params: Record<string, string>,
): Promise<TGApp.BBS.Response.Base | TGApp.User.Account.Game[]> {
): Promise<TGApp.BBS.Response.Base | TGApp.BBS.Account.GameAccount[]> {
const header = TGUtils.User.getHeader(cookie, "GET", params, "common");
const resp = await TGHttp<TGApp.User.Account.GameResponse | TGApp.BBS.Response.Base>(url, {
const resp = await TGHttp<TGApp.BBS.Response.getGameAccounts | TGApp.BBS.Response.Base>(url, {
method: "GET",
headers: header,
query: params,