48 lines
1.1 KiB
JavaScript
48 lines
1.1 KiB
JavaScript
import pickRandomFile from './pickRandomFile.js';
|
|
import utils from './utils.js';
|
|
import db from '../helpers/db/index.js';
|
|
import {TAGS, MAX_SESSION_TIME} from '../R.js';
|
|
|
|
/** @typedef {import('../models/Session.js').Session} Session */
|
|
/** @typedef {import('../models/Session.js').DbSession} DbSession */
|
|
|
|
|
|
/**
|
|
* @param {string} websiteKey
|
|
* @param {Object} cookies
|
|
* @return {Promise<Session>}
|
|
*/
|
|
export default async function initializeSession(websiteKey, cookies) {
|
|
const image = (await pickRandomFile()).split('.')[0];
|
|
const sessionId = cookies[websiteKey] || utils.randomBytes(8);
|
|
|
|
const dbSession = await db.getSession(sessionId);
|
|
|
|
// TODO: Change later to be dynamic based on `image`
|
|
const imageTagId = (dbSession || {}).obj || 1;
|
|
|
|
|
|
if (!dbSession) {
|
|
/** @type {DbSession} */
|
|
const dbPayload = {
|
|
sessionId,
|
|
websiteKey,
|
|
image: image,
|
|
obj: imageTagId,
|
|
score: 0.5,
|
|
expiry: Date.now() + MAX_SESSION_TIME,
|
|
};
|
|
|
|
await db.setSession(dbPayload);
|
|
}
|
|
|
|
/** @type {Session} */
|
|
const session = {
|
|
sessionId,
|
|
websiteKey,
|
|
imageTag: TAGS[imageTagId],
|
|
};
|
|
|
|
return session;
|
|
};
|