Spaces:
Paused
Paused
File size: 5,911 Bytes
9de864e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const SESSION_DIR = path.join(__dirname, '..', '..', 'session');
const TOKEN_FILE = path.join(SESSION_DIR, 'auth_token.txt');
export function initSessionDirectory() {
if (!fs.existsSync(SESSION_DIR)) {
fs.mkdirSync(SESSION_DIR, { recursive: true });
console.log(`Создана директория для сессий: ${SESSION_DIR}`);
}
}
export async function saveSession(context, accountId = null) {
try {
initSessionDirectory();
const isPuppeteer = context && typeof context.goto === 'function';
const isPlaywright = context && typeof context.storageState === 'function';
if (isPuppeteer) {
const cookies = await context.cookies();
const sessionPath = accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'cookies.json')
: path.join(SESSION_DIR, 'cookies.json');
const sessionDir = path.dirname(sessionPath);
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
fs.writeFileSync(sessionPath, JSON.stringify(cookies, null, 2));
console.log('Сессия Puppeteer сохранена');
return true;
} else if (isPlaywright && context.browser()) {
const sessionPath = accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'state.json')
: path.join(SESSION_DIR, 'state.json');
const sessionDir = path.dirname(sessionPath);
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
await context.storageState({ path: sessionPath });
console.log('Сессия Playwright сохранена');
return true;
} else {
console.error('Неизвестный тип контекста браузера');
return false;
}
} catch (error) {
console.error('Ошибка при сохранении сессии:', error);
return false;
}
}
export async function loadSession(context, accountId = null) {
try {
const isPuppeteer = context && typeof context.goto === 'function';
const isPlaywright = context && typeof context.storageState === 'function';
if (isPuppeteer) {
const sessionPath = accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'cookies.json')
: path.join(SESSION_DIR, 'cookies.json');
if (fs.existsSync(sessionPath)) {
const cookies = JSON.parse(fs.readFileSync(sessionPath, 'utf8'));
await context.setCookie(...cookies);
console.log('Сессия Puppeteer загружена');
return true;
}
} else if (isPlaywright) {
const sessionPath = accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'state.json')
: path.join(SESSION_DIR, 'state.json');
if (fs.existsSync(sessionPath)) {
await context.storageState({ path: sessionPath });
console.log('Сессия Playwright загружена');
return true;
}
}
} catch (error) {
console.error('Ошибка при загрузке сессии:', error);
}
return false;
}
export function clearSession(accountId = null) {
try {
const sessionPaths = [
accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'state.json')
: path.join(SESSION_DIR, 'state.json'),
accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'cookies.json')
: path.join(SESSION_DIR, 'cookies.json')
];
let cleared = false;
for (const sessionPath of sessionPaths) {
if (fs.existsSync(sessionPath)) {
fs.unlinkSync(sessionPath);
cleared = true;
}
}
if (cleared) {
console.log('Сессия очищена');
return true;
}
} catch (error) {
console.error('Ошибка при очистке сессии:', error);
}
return false;
}
export function hasSession(accountId = null) {
const sessionPaths = [
accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'state.json')
: path.join(SESSION_DIR, 'state.json'),
accountId
? path.join(SESSION_DIR, 'accounts', accountId, 'cookies.json')
: path.join(SESSION_DIR, 'cookies.json')
];
return sessionPaths.some(path => fs.existsSync(path));
}
export function saveAuthToken(token) {
try {
initSessionDirectory();
if (token) {
fs.writeFileSync(TOKEN_FILE, token, 'utf8');
console.log('Токен авторизации сохранен');
return true;
}
} catch (error) {
console.error('Ошибка при сохранении токена авторизации:', error);
}
return false;
}
export function loadAuthToken() {
try {
if (fs.existsSync(TOKEN_FILE)) {
const token = fs.readFileSync(TOKEN_FILE, 'utf8');
console.log('Токен авторизации загружен');
return token;
}
} catch (error) {
console.error('Ошибка при загрузке токена авторизации:', error);
}
return null;
}
|