Fix Graph token initialization order and progressive job loading
This commit is contained in:
@@ -60,7 +60,7 @@
|
||||
</div>
|
||||
<h1 class="m-0 mb-3 text-center text-blue-600 text-[33px] font-bold">Job Info</h1>
|
||||
|
||||
<div class="w-full bg-blue-50 h-1.5 rounded overflow-hidden mb-3">
|
||||
<div class="hidden w-full bg-blue-50 h-1.5 rounded overflow-hidden mb-3">
|
||||
<div id="progressBar" class="h-full w-0 bg-blue-600 transition-all duration-300 ease-out"></div>
|
||||
</div>
|
||||
|
||||
@@ -244,21 +244,10 @@
|
||||
const authed = await ensureAuth();
|
||||
if (!authed) return;
|
||||
|
||||
// Make sure a Graph token is available before proceeding; this may refresh silently
|
||||
try {
|
||||
await ensureGraphToken();
|
||||
} catch (err) {
|
||||
console.warn('Graph token missing after refresh; continuing. Preview may prompt for auth.', err?.message || err);
|
||||
}
|
||||
|
||||
// --- Utility ---
|
||||
const fetchNoCache = (url, options={}) => {
|
||||
const headers = { ...(options.headers||{}), ...authHeaders() };
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return fetch(url + `${separator}_ts=${Date.now()}`, { ...options, headers });
|
||||
};
|
||||
// --- Constants and helpers ---
|
||||
const GRAPH_TOKEN_KEY = 'graphAccessToken';
|
||||
const GRAPH_REAUTH_FLAG = 'graphReauthAttempted';
|
||||
|
||||
const extractGraphToken = (metaObj={}) => (
|
||||
metaObj.graphAccessToken ||
|
||||
metaObj.graph_token ||
|
||||
@@ -270,6 +259,7 @@
|
||||
metaObj?.authData?.access_token ||
|
||||
''
|
||||
);
|
||||
|
||||
const getGraphToken = () => {
|
||||
// Prefer runtime token already present in PB model/meta, then localStorage
|
||||
const model = pb?.authStore?.model || {};
|
||||
@@ -285,6 +275,55 @@
|
||||
''
|
||||
);
|
||||
};
|
||||
|
||||
const refreshGraphToken = async () => {
|
||||
try {
|
||||
const authData = await pb.collection('users').authRefresh();
|
||||
const meta = authData?.meta || pb?.authStore?.model?.meta || {};
|
||||
const token = extractGraphToken(meta);
|
||||
if (token) localStorage.setItem(GRAPH_TOKEN_KEY, token);
|
||||
return token || '';
|
||||
} catch(err){
|
||||
console.warn('Graph token refresh failed:', err?.message||err);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
const ensureGraphToken = async () => {
|
||||
let token = getGraphToken();
|
||||
if(token) return token;
|
||||
// If PB session is valid, try to refresh; if still missing, redirect to reauth once
|
||||
if (pb?.authStore?.isValid) {
|
||||
token = await refreshGraphToken();
|
||||
if (token) return token;
|
||||
const attempted = localStorage.getItem(GRAPH_REAUTH_FLAG) === '1';
|
||||
if (!attempted) {
|
||||
localStorage.setItem(GRAPH_REAUTH_FLAG, '1');
|
||||
console.warn('Graph token unavailable after refresh; redirecting once to sign-in to obtain a new token.');
|
||||
window.location.href = 'signin.html?reauth=1';
|
||||
throw new Error('GRAPH_TOKEN missing');
|
||||
}
|
||||
console.warn('Graph token unavailable after refresh; reauth already attempted. Proceeding without token.');
|
||||
return '';
|
||||
}
|
||||
// PB session invalid: redirect to signin
|
||||
window.location.href = 'signin.html';
|
||||
throw new Error('GRAPH_TOKEN missing');
|
||||
}
|
||||
|
||||
// Make sure a Graph token is available before proceeding
|
||||
try {
|
||||
await ensureGraphToken();
|
||||
} catch (err) {
|
||||
console.warn('Graph token missing after refresh; continuing. Preview may prompt for auth.', err?.message || err);
|
||||
}
|
||||
|
||||
// --- Utility ---
|
||||
const fetchNoCache = (url, options={}) => {
|
||||
const headers = { ...(options.headers||{}), ...authHeaders() };
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return fetch(url + `${separator}_ts=${Date.now()}`, { ...options, headers });
|
||||
};
|
||||
const PB_COLLECTION_URL = "https://pocketbase.ccllc.pro/api/collections/pbc_1407612689/records";
|
||||
const NOTES_COLLECTION_URL = "https://pocketbase.ccllc.pro/api/collections/notes/records";
|
||||
const PREFS_COLLECTION_URL = "https://pocketbase.ccllc.pro/api/collections/user_preferences/records";
|
||||
@@ -333,42 +372,6 @@
|
||||
if(userEmailEl && currentUserEmail) userEmailEl.textContent = currentUserEmail;
|
||||
|
||||
|
||||
// Ensure Graph token is present; refresh if missing; redirect to signin if still absent
|
||||
async function refreshGraphToken(){
|
||||
try {
|
||||
const authData = await pb.collection('users').authRefresh();
|
||||
const meta = authData?.meta || pb?.authStore?.model?.meta || {};
|
||||
const token = extractGraphToken(meta);
|
||||
if (token) localStorage.setItem(GRAPH_TOKEN_KEY, token);
|
||||
return token || '';
|
||||
} catch(err){
|
||||
console.warn('Graph token refresh failed:', err?.message||err);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureGraphToken(){
|
||||
let token = getGraphToken();
|
||||
if(token) return token;
|
||||
// If PB session is valid, try to refresh; if still missing, redirect to reauth once
|
||||
if (pb?.authStore?.isValid) {
|
||||
token = await refreshGraphToken();
|
||||
if (token) return token;
|
||||
const attempted = localStorage.getItem(GRAPH_REAUTH_FLAG) === '1';
|
||||
if (!attempted) {
|
||||
localStorage.setItem(GRAPH_REAUTH_FLAG, '1');
|
||||
console.warn('Graph token unavailable after refresh; redirecting once to sign-in to obtain a new token.');
|
||||
window.location.href = 'signin.html?reauth=1';
|
||||
throw new Error('GRAPH_TOKEN missing');
|
||||
}
|
||||
console.warn('Graph token unavailable after refresh; reauth already attempted. Proceeding without token.');
|
||||
return '';
|
||||
}
|
||||
// PB session invalid: redirect to signin
|
||||
window.location.href = 'signin.html';
|
||||
throw new Error('GRAPH_TOKEN missing');
|
||||
}
|
||||
|
||||
if (signOutBtn) {
|
||||
signOutBtn.addEventListener('click', () => {
|
||||
try { pb?.authStore?.clear?.(); } catch {}
|
||||
@@ -395,50 +398,27 @@
|
||||
}
|
||||
}
|
||||
loadVersion();
|
||||
|
||||
let progTimer=null;
|
||||
function startProgress(){
|
||||
progressBar.style.width='0%';
|
||||
if(progTimer) clearInterval(progTimer);
|
||||
let simulatedProg=0;
|
||||
progTimer=setInterval(()=>{
|
||||
if(simulatedProg<65){ simulatedProg+=0.8; progressBar.style.width=Math.min(65,simulatedProg).toFixed(1)+'%'; }
|
||||
},150);
|
||||
}
|
||||
function finishProgress(){ if(progTimer) clearInterval(progTimer); progressBar.style.width='100%'; setTimeout(()=>{progressBar.parentElement.classList.add('hidden');},400); }
|
||||
// Progress bar removed - jobs load instantly from cache
|
||||
|
||||
// --- Fetch all jobs ---
|
||||
async function fetchAllJobs(){
|
||||
startProgress();
|
||||
clearJobsCache('Loading…');
|
||||
const startTime = performance.now();
|
||||
let pollCount = 0;
|
||||
async function pollJobs(){
|
||||
try{
|
||||
const url = `/api/jobs-all`;
|
||||
const res = await fetchNoCache(url);
|
||||
if(!res.ok) throw new Error(`Fetch failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const items = data.items || [];
|
||||
if (pollCount === 0 || jobsCache.length === 0) {
|
||||
jobsCache.length = 0;
|
||||
jobsCache.push(...items);
|
||||
progressBar.style.width='95%';
|
||||
applyFiltersAndRender();
|
||||
}
|
||||
if (data.partial) {
|
||||
// If partial, poll again after short delay
|
||||
pollCount++;
|
||||
if (pollCount < 10) setTimeout(pollJobs, 600);
|
||||
else finishProgress();
|
||||
} else {
|
||||
finishProgress();
|
||||
const loadTime = Math.round(performance.now() - startTime);
|
||||
console.log(`✓ Loaded ${items.length} jobs from API in ${loadTime}ms`);
|
||||
}
|
||||
}catch(err){ finishProgress(); alert('Failed to fetch jobs: '+err.message); console.error(err); }
|
||||
try {
|
||||
const url = `/api/jobs-all`;
|
||||
const res = await fetchNoCache(url);
|
||||
if(!res.ok) throw new Error(`Fetch failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const items = data.items || [];
|
||||
jobsCache.length = 0;
|
||||
jobsCache.push(...items);
|
||||
applyFiltersAndRender();
|
||||
const loadTime = Math.round(performance.now() - startTime);
|
||||
console.log(`✓ Loaded ${items.length} jobs in ${loadTime}ms`);
|
||||
} catch(err) {
|
||||
alert('Failed to fetch jobs: '+err.message);
|
||||
console.error(err);
|
||||
}
|
||||
pollJobs();
|
||||
}
|
||||
|
||||
function renderInitialBatch(jobs){
|
||||
|
||||
Reference in New Issue
Block a user