2023-08-20 11:51:39 +01:00
|
|
|
import Cookie from './cookie.js';
|
|
|
|
import { readFile, writeFile } from 'fs/promises';
|
|
|
|
import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
|
|
|
|
|
|
|
|
const WRITE_INTERVAL = 60000,
|
2023-08-20 11:58:04 +01:00
|
|
|
cookiePath = process.env.cookiePath,
|
2023-08-20 11:51:39 +01:00
|
|
|
COUNTER = Symbol('counter');
|
|
|
|
|
|
|
|
let cookies = {}, dirty = false, intervalId;
|
|
|
|
|
|
|
|
const setup = async () => {
|
|
|
|
try {
|
2023-08-20 11:58:04 +01:00
|
|
|
if (!cookiePath) return;
|
2023-08-20 11:51:39 +01:00
|
|
|
|
2023-08-20 11:58:04 +01:00
|
|
|
cookies = await readFile(cookiePath, 'utf8');
|
2023-08-20 11:51:39 +01:00
|
|
|
cookies = JSON.parse(cookies);
|
|
|
|
intervalId = setInterval(writeChanges, WRITE_INTERVAL)
|
|
|
|
} catch { /* no cookies for you */ }
|
|
|
|
}
|
|
|
|
|
|
|
|
setup();
|
|
|
|
|
|
|
|
function writeChanges() {
|
|
|
|
if (!dirty) return;
|
|
|
|
dirty = false;
|
|
|
|
|
2023-08-20 11:58:04 +01:00
|
|
|
writeFile(cookiePath, JSON.stringify(cookies, null, 4)).catch(() => {
|
2023-08-20 11:51:39 +01:00
|
|
|
clearInterval(intervalId)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getCookie(service) {
|
|
|
|
if (!cookies[service] || !cookies[service].length) return;
|
|
|
|
|
|
|
|
let n;
|
|
|
|
if (cookies[service][COUNTER] === undefined) {
|
|
|
|
n = cookies[service][COUNTER] = 0
|
|
|
|
} else {
|
|
|
|
++cookies[service][COUNTER]
|
|
|
|
n = (cookies[service][COUNTER] %= cookies[service].length)
|
|
|
|
}
|
|
|
|
|
|
|
|
const cookie = cookies[service][n];
|
|
|
|
if (typeof cookie === 'string') cookies[service][n] = Cookie.fromString(cookie);
|
|
|
|
|
|
|
|
return cookies[service][n]
|
|
|
|
}
|
|
|
|
|
|
|
|
export function updateCookie(cookie, headers) {
|
2023-08-20 14:27:49 +01:00
|
|
|
if (!cookie) return;
|
|
|
|
|
2023-08-20 11:51:39 +01:00
|
|
|
const parsed = parseSetCookie(splitCookiesString(headers.get('set-cookie'))),
|
|
|
|
values = {}
|
|
|
|
|
|
|
|
cookie.unset(parsed.filter(c => c.expires < new Date()).map(c => c.name));
|
|
|
|
parsed.filter(c => c.expires > new Date()).forEach(c => values[c.name] = c.value);
|
|
|
|
|
|
|
|
cookie.set(values);
|
|
|
|
if (Object.keys(values).length) dirty = true
|
|
|
|
}
|