v6d3music/v6d3music/html/main.js
2022-08-05 00:05:42 +03:00

95 lines
2.6 KiB
JavaScript

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
const sessionStr = () => {
if (!localStorage.getItem('session'))
localStorage.setItem('session', genRanHex(64));
return localStorage.getItem('session');
};
const sessionState = async () => {
const response = await fetch(
`/state/?session=${sessionStr()}`
);
return await response.json();
};
const sessionStatus = (
() => {
let task;
return (async () => {
if (task === undefined) {
task = (async () => {
const response = await fetch(
`/status/?session=${sessionStr()}`
);
return await response.json();
})();
}
return await task;
})
}
)();
const root = document.querySelector('#root');
const logEl = (msg) => {
const el = document.createElement('pre');
el.innerText = msg;
root.append(el);
};
const sessionClient = async () => {
const session = await sessionStatus();
return session && session['client'];
};
const sessionUser = async () => {
const client = await sessionClient();
return client && client['user'];
};
const userAvatarUrl = async () => {
const user = await sessionUser();
return user && user['avatar'];
};
const userUsername = async () => {
const user = await sessionUser();
return user && user['username'];
};
const userAvatarImg = async () => {
const avatar = await userAvatarUrl();
if (avatar) {
const img = document.createElement('img');
img.src = avatar;
img.width = 64;
img.height = 64;
img.alt = await userUsername();
return img;
} else {
return baseEl('span');
}
};
const userId = async () => {
const user = await sessionUser();
return user && user['id'];
};
const baseEl = (tag, ...appended) => {
const element = document.createElement(tag);
element.append(...appended);
return element;
};
const aLogin = () => {
const a = document.createElement('a');
a.href = '/login/';
a.innerText = 'login';
return a;
};
const pageHome = async () => {
return baseEl(
'div',
baseEl('div', aLogin()),
baseEl('div', await userAvatarImg()),
baseEl('div', await userId()),
baseEl('div', await userUsername()),
)
};
let authbase;
const aAuth = async () => {
const a = document.createElement('a');
a.href = authbase + '&state=' + await sessionState();
a.innerText = 'auth';
return a;
};