mirror of
https://github.com/christianvidalwolf-prog/Craze-Data-check.git
synced 2026-08-03 11:05:24 +02:00
fix(dropbox): use direct raw fallback
This commit is contained in:
+38
-13
@@ -1,23 +1,47 @@
|
||||
import { applyCors, isAllowedOrigin } from './_cors.js';
|
||||
|
||||
const DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY;
|
||||
const DROPBOX_APP_SECRET = process.env.DROPBOX_APP_SECRET;
|
||||
const DROPBOX_REFRESH_TOKEN = process.env.DROPBOX_REFRESH_TOKEN;
|
||||
const DROPBOX_SHARED_URL = 'https://www.dropbox.com/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
||||
const DEFAULT_DROPBOX_SHARED_URL = 'https://www.dropbox.com/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
||||
|
||||
function getDropboxConfig() {
|
||||
return {
|
||||
appKey: process.env.DROPBOX_APP_KEY,
|
||||
appSecret: process.env.DROPBOX_APP_SECRET,
|
||||
refreshToken: process.env.DROPBOX_REFRESH_TOKEN,
|
||||
sharedUrl: process.env.DROPBOX_SHARED_URL || DEFAULT_DROPBOX_SHARED_URL,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeDropboxSharedUrl(sharedUrl) {
|
||||
const url = new URL(sharedUrl);
|
||||
url.searchParams.delete('dl');
|
||||
url.searchParams.delete('raw');
|
||||
url.searchParams.delete('st');
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function buildDropboxDownloadUrl(sharedUrl) {
|
||||
const url = new URL(normalizeDropboxSharedUrl(sharedUrl));
|
||||
url.searchParams.set('raw', '1');
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function setCors(req, res) {
|
||||
applyCors(req, res, 'GET, OPTIONS');
|
||||
}
|
||||
|
||||
async function getAccessToken() {
|
||||
const { appKey, appSecret, refreshToken } = getDropboxConfig();
|
||||
if (!appKey || !appSecret || !refreshToken) {
|
||||
throw new Error('Dropbox auth env vars are not configured.');
|
||||
}
|
||||
const response = await fetch('https://api.dropboxapi.com/oauth2/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: DROPBOX_REFRESH_TOKEN,
|
||||
client_id: DROPBOX_APP_KEY,
|
||||
client_secret: DROPBOX_APP_SECRET,
|
||||
refresh_token: refreshToken,
|
||||
client_id: appKey,
|
||||
client_secret: appSecret,
|
||||
})
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -46,11 +70,12 @@ export default async function handler(req, res) {
|
||||
return res.json({ rev: 'new-url-v1', size: 0, server_modified: new Date().toISOString() });
|
||||
}
|
||||
|
||||
// Strip dl=1 for the authenticated API call (browser-redirect hint, not needed for API).
|
||||
const sharingUrlForApi = DROPBOX_SHARED_URL.replace(/[&?]dl=1/, '');
|
||||
const { sharedUrl } = getDropboxConfig();
|
||||
const sharingUrlForApi = normalizeDropboxSharedUrl(sharedUrl);
|
||||
const downloadUrl = buildDropboxDownloadUrl(sharedUrl);
|
||||
|
||||
// Try authenticated Dropbox API first — bypasses CDN cache so we always get the latest version.
|
||||
// Falls back to DROPBOX_SHARED_URL if credentials are not configured.
|
||||
// Falls back to the shared URL if credentials are not configured.
|
||||
let upstream = null;
|
||||
let usedAuth = false;
|
||||
|
||||
@@ -73,12 +98,12 @@ export default async function handler(req, res) {
|
||||
console.warn('Dropbox API download failed, falling back to sharing link:', apiRes.status, errText.substring(0, 200));
|
||||
}
|
||||
} catch (authErr) {
|
||||
console.warn('Dropbox auth unavailable, falling back to sharing link:', authErr.message);
|
||||
console.warn('Dropbox auth unavailable, falling back to sharing link:', authErr?.message || String(authErr));
|
||||
}
|
||||
|
||||
try {
|
||||
if (!upstream) {
|
||||
upstream = await fetch(DROPBOX_SHARED_URL, {
|
||||
upstream = await fetch(downloadUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache',
|
||||
@@ -110,6 +135,6 @@ export default async function handler(req, res) {
|
||||
res.send(Buffer.from(buffer));
|
||||
} catch (err) {
|
||||
console.error('Dropbox proxy error:', err);
|
||||
res.status(500).send('Proxy error: ' + err.message);
|
||||
res.status(500).send('Proxy error: ' + (err?.message || String(err)));
|
||||
}
|
||||
}
|
||||
|
||||
+6
-8
@@ -56,6 +56,8 @@ const FORCED_ZERO_STOCK_SKUS = new Set([
|
||||
|
||||
const BC_SYNC_QUEUE_STORAGE_KEY = 'craze_bc_sync_queue';
|
||||
const LEGACY_CPNP_INDEX = 77;
|
||||
const DROPBOX_PROXY_URL = '/api/dropbox-proxy';
|
||||
const DROPBOX_FILE_URL = '/dropbox-file/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
||||
|
||||
type BcSyncStatus = 'queued' | 'previewed' | 'preview_only' | 'syncing' | 'synced' | 'failed';
|
||||
|
||||
@@ -216,19 +218,15 @@ export default function App() {
|
||||
return arrayBuffer.byteLength;
|
||||
};
|
||||
|
||||
const dropboxSources = import.meta.env.DEV
|
||||
? [
|
||||
'/api/dropbox-proxy',
|
||||
`/dropbox-file/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0&t=${Date.now()}`
|
||||
]
|
||||
: [
|
||||
'/api/dropbox-proxy'
|
||||
const dropboxSources = [
|
||||
DROPBOX_PROXY_URL,
|
||||
`${DROPBOX_FILE_URL}&t=${Date.now()}`
|
||||
];
|
||||
|
||||
let lastError: unknown = null;
|
||||
for (const source of dropboxSources) {
|
||||
try {
|
||||
console.log(`Fetching Data-Matrix.xlsx from ${source.includes('/api/') ? 'proxy' : 'Dropbox'}...`);
|
||||
console.log(`Fetching Data-Matrix.xlsx from ${source}...`);
|
||||
const size = await loadWorkbookFromUrl(source);
|
||||
fileMeta = { rev: source, size };
|
||||
lastError = null;
|
||||
|
||||
+24
-14
@@ -29,25 +29,18 @@ async function readJsonBody(req: any): Promise<any> {
|
||||
});
|
||||
}
|
||||
|
||||
export default defineConfig(({mode}) => {
|
||||
const env = loadEnv(mode, '.', '');
|
||||
const prodEnv = loadEnv('production', '.', '');
|
||||
return {
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
{
|
||||
name: 'bc-local-api',
|
||||
configureServer(server) {
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
function createLocalApiMiddleware(env: Record<string, string>, prodEnv: Record<string, string>) {
|
||||
return async (req: any, res: any, next: any) => {
|
||||
try {
|
||||
const url = new URL(req.url || '/', 'http://localhost');
|
||||
const config = getBcConfig(env);
|
||||
|
||||
// Populate process.env with loaded env variables for serverless handlers
|
||||
// Populate process.env with loaded env variables for serverless handlers.
|
||||
// The Dropbox proxy reads env at request time so preview/dev/production
|
||||
// can share the same handler implementation.
|
||||
Object.assign(process.env, prodEnv, env);
|
||||
|
||||
// Helper to adapt Node.js req/res to Vercel signature
|
||||
// Helper to adapt Node.js req/res to Vercel signature.
|
||||
const adaptVercelHandler = async (handler: any) => {
|
||||
(req as any).query = Object.fromEntries(url.searchParams.entries());
|
||||
try {
|
||||
@@ -170,7 +163,24 @@ export default defineConfig(({mode}) => {
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig(({mode}) => {
|
||||
const env = loadEnv(mode, '.', '');
|
||||
const prodEnv = loadEnv('production', '.', '');
|
||||
const localApiMiddleware = createLocalApiMiddleware(env, prodEnv);
|
||||
return {
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
{
|
||||
name: 'bc-local-api',
|
||||
configureServer(server) {
|
||||
server.middlewares.use(localApiMiddleware);
|
||||
},
|
||||
configurePreviewServer(server) {
|
||||
server.middlewares.use(localApiMiddleware);
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user