52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
/**
|
|
* TODO: this code should maybe be the constructor of a session model
|
|
*/
|
|
import pickRandomFile from './pickRandomFile.js';
|
|
import UserSession from '../../models/UserSession.js';
|
|
import {randomBytes} from '../../helpers/utils.js';
|
|
import {client} from '../../helpers/idb.js';
|
|
import {MAX_SESSION_TIME, TAGS} from '../../R.js';
|
|
|
|
// /**
|
|
// * @typedef {import('../../models/IDBSession.js')} IDBSession
|
|
// */
|
|
|
|
|
|
/**
|
|
* @param {string} websiteKey
|
|
* @param {Object} cookies
|
|
* @return {Promise<UserSession>}
|
|
*/
|
|
export default async function initializeSession(websiteKey, cookies) {
|
|
let randomSessionId;
|
|
|
|
if (cookies[websiteKey]) {
|
|
randomSessionId = cookies[websiteKey];
|
|
} else {
|
|
randomSessionId = randomBytes(8);
|
|
}
|
|
|
|
const image = await pickRandomFile();
|
|
|
|
const imageTagId = 1; // TODO: Change later to be dynamic based on `image`
|
|
const session = new UserSession();
|
|
|
|
session.setSessionId(randomSessionId);
|
|
session.setWebsiteKey(websiteKey);
|
|
session.setImageTag(TAGS[imageTagId]);
|
|
|
|
/** @type {import('../../models/IDBSession.js')} */
|
|
const idbPayload = {
|
|
sessionId: session.getSessionId(),
|
|
websiteKey: session.getWebsiteKey(),
|
|
image,
|
|
obj: imageTagId,
|
|
score: 0.5,
|
|
};
|
|
|
|
client.setex(
|
|
session.getSessionId(), MAX_SESSION_TIME, JSON.stringify(idbPayload));
|
|
|
|
return session;
|
|
};
|