Добавить смену профилей, пока не работает

This commit is contained in:
AidarKC
2026-09-03 12:51:46 +04:00
parent ebc9143593
commit e0295eebde
8 changed files with 227 additions and 43 deletions
+108 -13
View File
@@ -1206,14 +1206,23 @@ export async function switchToSavedProfile(login) {
if (!target) throw new Error('Профиль не найден на этом устройстве');
if (targetLogin === normalizeProfileLogin(state.session.login)) return target;
const origin = {
login: String(state.session.login || '').trim(),
sessionId: String(state.session.sessionId || '').trim(),
isLocalDemo: Boolean(state.session.isLocalDemo),
server: String(state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim(),
};
const targetServer = String(target?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
const probe = new AuthService(targetServer);
// В каждый момент времени держим только один WebSocket: сначала полностью
// закрываем transport активного профиля, затем создаём новый для target.
authService.resetConnection(targetServer, { clearSessionContext: true });
try {
await probe.reconnect(targetServer);
const resumed = await probe.resumeSession(target.login, target.sessionId);
const resumed = await authService.resumeSession(target.login, target.sessionId);
target.login = resumed.login || target.login;
target.sessionId = resumed.sessionId || target.sessionId;
target.updatedAtMs = Date.now();
authService.setActiveSessionContext({ login: target.login, sessionId: target.sessionId });
persistProfileStoreRaw(loadProfileStoreRaw().map((item) => (
normalizeProfileLogin(item.login) === targetLogin ? target : item
)));
@@ -1223,8 +1232,23 @@ export async function switchToSavedProfile(login) {
persistEntrySettings({ ...state.entrySettings, ...target.entrySettings });
}
return target;
} finally {
probe.close();
} catch (switchError) {
// Если новый профиль не поднялся — создаём новый socket обратно для старого.
try {
authService.resetConnection(origin.server, { clearSessionContext: true });
if (origin.login && origin.sessionId && !origin.isLocalDemo) {
const restored = await authService.resumeSession(origin.login, origin.sessionId);
authService.setActiveSessionContext({
login: restored?.login || origin.login,
sessionId: restored?.sessionId || origin.sessionId,
});
} else if (origin.login) {
authService.setActiveSessionContext({ login: origin.login, sessionId: origin.sessionId });
}
} catch (restoreError) {
console.warn('[profiles] failed to restore previous profile connection after switch failure', restoreError);
}
throw switchError;
}
}
@@ -1233,20 +1257,40 @@ async function closeSavedProfileSessionBestEffort(profile) {
const cleanSessionId = String(profile.sessionId || '').trim();
if (!cleanSessionId) return;
const normalized = normalizeProfileLogin(profile.login);
if (normalized === normalizeProfileLogin(state.session.login) && state.session.isAuthorized) {
const activeNormalized = normalizeProfileLogin(state.session.login);
if (normalized === activeNormalized && state.session.isAuthorized) {
try { await authService.closeSession(cleanSessionId); } catch {}
return;
}
const origin = {
login: String(state.session.login || '').trim(),
sessionId: String(state.session.sessionId || '').trim(),
isLocalDemo: Boolean(state.session.isLocalDemo),
server: String(state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim(),
};
const targetServer = String(profile?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
const probe = new AuthService(targetServer);
try {
await probe.reconnect(targetServer);
await probe.resumeSession(profile.login, cleanSessionId);
await probe.closeSession(cleanSessionId);
authService.resetConnection(targetServer, { clearSessionContext: true });
await authService.resumeSession(profile.login, cleanSessionId);
await authService.closeSession(cleanSessionId);
} catch {
// Закрытие профиля на устройстве не блокируем из-за недоступного сервера.
} finally {
probe.close();
try {
authService.resetConnection(origin.server, { clearSessionContext: true });
if (origin.login && origin.sessionId && !origin.isLocalDemo) {
const restored = await authService.resumeSession(origin.login, origin.sessionId);
authService.setActiveSessionContext({
login: restored?.login || origin.login,
sessionId: restored?.sessionId || origin.sessionId,
});
} else if (origin.login) {
authService.setActiveSessionContext({ login: origin.login, sessionId: origin.sessionId });
}
} catch (error) {
console.warn('[profiles] failed to restore active profile after closing another profile', error);
}
}
}
@@ -1281,8 +1325,16 @@ export async function closeSavedProfile(login) {
export async function closeAllSavedProfiles() {
const items = loadProfileStoreRaw();
for (const item of items) {
await closeSavedProfileSessionBestEffort(item);
await clearStoredMessages(item.login).catch(() => {});
if (item.isLocalDemo || !String(item.sessionId || '').trim()) continue;
const targetServer = String(item?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
try {
authService.resetConnection(targetServer, { clearSessionContext: true });
await authService.resumeSession(item.login, item.sessionId);
await authService.closeSession(item.sessionId);
} catch {
// Все локальные профили всё равно закрываем, даже если один сервер недоступен.
}
}
persistProfileStoreRaw([]);
setActiveProfileLoginRaw('');
@@ -1291,10 +1343,53 @@ export async function closeAllSavedProfiles() {
authService.clearActiveSessionContext();
}
export function prepareAddProfileLogin() {
export function isAddingProfileLogin() {
return state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
}
export async function prepareAddProfileLogin() {
state.loginDraft.login = '';
state.loginDraft.password = '';
clearAuthMessages();
// While an existing profile stays authorized, PRE_AUTH login pages are normally
// blocked by app.js. This return target also acts as an explicit add-profile mode.
state.authReturnHash = '/profiles';
// Не пытаемся авторизовать второй login через уже authenticated socket.
// Старую серверную сессию НЕ закрываем: закрываем только локальный transport.
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
}
export async function cancelAddProfileLogin() {
const wasAddingProfile = isAddingProfileLogin();
const shouldRestoreActiveConnection = wasAddingProfile
&& state.session.isAuthorized
&& Boolean(String(state.session.login || '').trim())
&& Boolean(String(state.session.sessionId || '').trim());
state.authReturnHash = '';
state.loginDraft.login = '';
state.loginDraft.password = '';
resetRegistrationFlow();
clearAuthMessages();
if (shouldRestoreActiveConnection) {
try {
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
await authService.resumeSession(state.session.login, state.session.sessionId);
authService.setActiveSessionContext({ login: state.session.login, sessionId: state.session.sessionId });
} catch (error) {
console.warn('[profiles] failed to restore active profile connection after cancelling add-profile flow', error);
}
}
return wasAddingProfile;
}
export function consumeAuthReturnPage(fallback = 'profile-view') {
const nextHash = String(state.authReturnHash || '').trim();
state.authReturnHash = '';
if (nextHash.startsWith('/')) return nextHash.slice(1) || fallback;
return fallback;
}
export function refreshRegistrationBalance() {