@xuda.io/drive_module 1.1.1500 → 1.1.1501
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.mjs +479 -32
- package/index_ms.mjs +12 -0
- package/index_msa.mjs +12 -0
- package/package.json +1 -1
package/index.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import fse from 'fs-extra';
|
|
|
5
5
|
import unzipper from 'unzipper';
|
|
6
6
|
import fs from 'fs';
|
|
7
7
|
import os from 'os';
|
|
8
|
+
import child_process from 'child_process';
|
|
8
9
|
import tesseract from 'node-tesseract-ocr';
|
|
9
10
|
import countryLanguage from 'country-language';
|
|
10
11
|
import url from 'url';
|
|
@@ -226,13 +227,15 @@ export const get_drive_files = async (req) => {
|
|
|
226
227
|
}
|
|
227
228
|
try {
|
|
228
229
|
files.sizeInBytes += doc.size;
|
|
230
|
+
const access_link = `https://${domain}/${drive_type}-drive/${datasource_id || app_id_reference || uid}/${doc._id}${ts}`;
|
|
229
231
|
files.children.push({
|
|
230
232
|
name: doc.originalname,
|
|
231
233
|
sizeInBytes: doc.size,
|
|
232
234
|
size: formatBytes(doc.size),
|
|
233
235
|
extension: doc?.file_ext?.substr(1),
|
|
234
236
|
type: doc.type,
|
|
235
|
-
access_link
|
|
237
|
+
access_link,
|
|
238
|
+
...preview_links_for(doc, access_link),
|
|
236
239
|
is_archive: doc.is_archive,
|
|
237
240
|
public: doc.public,
|
|
238
241
|
path: doc.file_path,
|
|
@@ -676,6 +679,9 @@ export const update_drive_file = async (req, job_id, headers, file_obj) => {
|
|
|
676
679
|
|
|
677
680
|
doc = { ...doc, ...(await get_file_info(tempPath)) };
|
|
678
681
|
|
|
682
|
+
// New bytes, so any preview on the doc now shows the old content. Re-queue it.
|
|
683
|
+
if (is_office_preview_ext(doc.file_ext)) doc.preview_stat = 1;
|
|
684
|
+
|
|
679
685
|
let save_ret;
|
|
680
686
|
let ref;
|
|
681
687
|
switch (drive_type) {
|
|
@@ -726,6 +732,10 @@ export const update_drive_file = async (req, job_id, headers, file_obj) => {
|
|
|
726
732
|
|
|
727
733
|
let file_url = get_file_url(drive_type, file_name, ref);
|
|
728
734
|
|
|
735
|
+
if (doc.preview_stat === 1) {
|
|
736
|
+
generate_drive_file_preview({ app_id, drive_type, uid, doc_id: doc._id }).catch(() => {});
|
|
737
|
+
}
|
|
738
|
+
|
|
729
739
|
return {
|
|
730
740
|
code: 760,
|
|
731
741
|
data: {
|
|
@@ -1892,6 +1902,9 @@ export const upload_drive_file = async (req, job_id, headers = {}, file_obj) =>
|
|
|
1892
1902
|
drive_type,
|
|
1893
1903
|
mime: file_obj.mimetype,
|
|
1894
1904
|
ocr_stat: ['image', 'application', 'text'].includes(file_obj.mimetype.split('/')[0]) ? 1 : 0,
|
|
1905
|
+
// studio drive keeps its files on local disk rather than in a bucket, and the
|
|
1906
|
+
// preview reader fetches from the bucket, so it is not a candidate.
|
|
1907
|
+
preview_stat: is_office_preview_ext(ext) && drive_type !== 'studio' ? 1 : 0,
|
|
1895
1908
|
target_file,
|
|
1896
1909
|
file_path: file_path || '/',
|
|
1897
1910
|
size: stat.isFile() ? stat.size : 0,
|
|
@@ -2020,6 +2033,13 @@ export const upload_drive_file = async (req, job_id, headers = {}, file_obj) =>
|
|
|
2020
2033
|
|
|
2021
2034
|
await fs_module.unlink(tempPath);
|
|
2022
2035
|
|
|
2036
|
+
// Office files get a rendered preview. Fire and forget: converting takes seconds and
|
|
2037
|
+
// an upload must not wait for it, nor fail because of it. The doc already carries
|
|
2038
|
+
// preview_stat 1, so if this box never gets to it the sweep will.
|
|
2039
|
+
if (doc.preview_stat === 1) {
|
|
2040
|
+
generate_drive_file_preview({ app_id: req.app_id, drive_type, uid, doc_id: doc._id }).catch(() => {});
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2023
2043
|
return {
|
|
2024
2044
|
code: 760,
|
|
2025
2045
|
data: {
|
|
@@ -2351,19 +2371,100 @@ export const check_drive_file = async (req, job_id, headers, file_obj) => {
|
|
|
2351
2371
|
return ret.files[0];
|
|
2352
2372
|
};
|
|
2353
2373
|
|
|
2354
|
-
|
|
2355
|
-
|
|
2374
|
+
// Which languages tesseract on THIS box actually has traineddata for. Asked once and
|
|
2375
|
+
// cached: it shells out, and the answer cannot change while the process lives.
|
|
2376
|
+
let _tesseract_langs_cache;
|
|
2377
|
+
const tesseract_langs = () => {
|
|
2378
|
+
if (_tesseract_langs_cache) return _tesseract_langs_cache;
|
|
2379
|
+
try {
|
|
2380
|
+
const out = child_process.execFileSync('tesseract', ['--list-langs'], { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
2381
|
+
// First line is a "List of available languages (N):" header, which has spaces in it.
|
|
2382
|
+
const langs = out.split('\n').map((s) => s.trim()).filter((s) => s && !s.includes(' '));
|
|
2383
|
+
_tesseract_langs_cache = new Set(langs.length ? langs : ['eng']);
|
|
2384
|
+
} catch (err) {
|
|
2385
|
+
console.warn('[drive_module] tesseract --list-langs failed, assuming eng only:', err.message);
|
|
2386
|
+
_tesseract_langs_cache = new Set(['eng']);
|
|
2387
|
+
}
|
|
2388
|
+
return _tesseract_langs_cache;
|
|
2389
|
+
};
|
|
2390
|
+
|
|
2391
|
+
// Pick the OCR languages for a file, from the country its upload came from.
|
|
2392
|
+
//
|
|
2393
|
+
// Two traps, both of which used to fail the whole OCR run:
|
|
2394
|
+
// - country-language's getCountry REQUIRES a callback and throws "cb is not a function"
|
|
2395
|
+
// for a missing or unknown code. doc.country comes from the cf-ipcountry header, which
|
|
2396
|
+
// is absent on EVERY server-side write (AI output, plugin saves, restores), so this
|
|
2397
|
+
// threw for most files and marked them ocr_stat 4.
|
|
2398
|
+
// - a language whose traineddata is not installed makes tesseract exit with "Error during
|
|
2399
|
+
// processing", losing the English pass along with it. So only offer what is on the box.
|
|
2400
|
+
const detectLanguageByCountry = (cfCountry) => {
|
|
2401
|
+
const have = tesseract_langs();
|
|
2402
|
+
const langs = ['eng'];
|
|
2403
|
+
try {
|
|
2404
|
+
const code = String(cfCountry || '').trim().toUpperCase();
|
|
2405
|
+
const countryData = code ? countryLanguage.getCountry(code) : null;
|
|
2406
|
+
for (const language of countryData?.languages || []) {
|
|
2407
|
+
const iso = language?.iso639_2;
|
|
2408
|
+
if (iso && have.has(iso) && !langs.includes(iso)) langs.push(iso);
|
|
2409
|
+
}
|
|
2410
|
+
} catch (err) {
|
|
2411
|
+
// Unknown or missing country: English only, which is the right default and is what
|
|
2412
|
+
// the caller wanted all along.
|
|
2413
|
+
}
|
|
2414
|
+
// Each extra language costs real time on every page, and the tail of a country's list
|
|
2415
|
+
// is rarely what the document is written in.
|
|
2416
|
+
return langs.slice(0, 4).join('+');
|
|
2417
|
+
};
|
|
2418
|
+
|
|
2419
|
+
// Put a drive file's bytes on local disk and hand back the path. EVERY OCR reader below
|
|
2420
|
+
// wants a real file: tesseract streams one, mammoth and node-xlsx take a `path`, pdf2image
|
|
2421
|
+
// rasterises one. They were being handed a URL instead, and a wrong URL at that (built
|
|
2422
|
+
// with the uid where the route wants the project id, and with the folder baked into the
|
|
2423
|
+
// filename), so the fetch 404'd and tesseract failed with "Error during processing" while
|
|
2424
|
+
// the text branch quietly stored an ENOENT string as the document's OCR text.
|
|
2425
|
+
//
|
|
2426
|
+
// The bytes are already in the region bucket, so read them straight from there and skip
|
|
2427
|
+
// HTTP entirely. Only a drive with no bucket entry (a datacenter workspace drive, whose
|
|
2428
|
+
// files are scp'd to the hosting box) still needs the round trip, and that one now uses a
|
|
2429
|
+
// URL built the same way the drive listing builds it.
|
|
2430
|
+
const ocr_file_to_tmp = async (app_id, doc) => {
|
|
2431
|
+
const write_tmp = async (buffer) => {
|
|
2432
|
+
const tmp_path = path.join(os.tmpdir(), `xuda_ocr_${await _common.xuda_get_uuid('tmp')}${doc.file_ext || path.extname(doc.originalname || '') || ''}`);
|
|
2433
|
+
await fs.promises.writeFile(tmp_path, buffer);
|
|
2434
|
+
return tmp_path;
|
|
2435
|
+
};
|
|
2356
2436
|
|
|
2357
|
-
|
|
2437
|
+
const region = _pick_file_region(doc);
|
|
2438
|
+
const { Bucket, Key } = _drive_bucket_for(doc, region);
|
|
2439
|
+
const s3 = region ? _drive_s3_for(region) : null;
|
|
2358
2440
|
|
|
2359
|
-
|
|
2360
|
-
const
|
|
2361
|
-
|
|
2362
|
-
return parsedUrl.toString();
|
|
2441
|
+
if (s3 && Bucket && Key) {
|
|
2442
|
+
const obj = await s3.send(new GetObjectCommand({ Bucket, Key }));
|
|
2443
|
+
return await write_tmp(await _stream_to_buffer(obj.Body));
|
|
2363
2444
|
}
|
|
2364
2445
|
|
|
2365
|
-
|
|
2446
|
+
const ref = doc.drive_type === 'user' ? await get_account_default_project_id(doc.uid) : await _common.get_project_app_id(app_id);
|
|
2447
|
+
const target = new url.URL(get_file_url(doc.drive_type, doc._id, ref));
|
|
2448
|
+
target.searchParams.set('xuda_internal_request_code', _conf.xuda_internal_request_code);
|
|
2449
|
+
|
|
2450
|
+
const res = await fetch(target.toString());
|
|
2451
|
+
if (!res.ok) throw new Error(`file unavailable (${res.status})`);
|
|
2452
|
+
return await write_tmp(Buffer.from(await res.arrayBuffer()));
|
|
2453
|
+
};
|
|
2454
|
+
|
|
2455
|
+
// read_file answers { code, data } and puts the ERROR MESSAGE in data when it fails, so
|
|
2456
|
+
// reading it blindly stored strings like "ENOENT: no such file" as the document's own
|
|
2457
|
+
// searchable text. A failed read has no text in it, and saying so is the honest answer.
|
|
2458
|
+
const read_text_for_ocr = async (file_path) => {
|
|
2459
|
+
const ret = await fs_module.read_file(file_path);
|
|
2460
|
+
if (!ret || ret.code < 0) throw new Error(`could not read file for ocr: ${ret?.data || 'unknown error'}`);
|
|
2461
|
+
return String(ret.data || '');
|
|
2462
|
+
};
|
|
2463
|
+
|
|
2464
|
+
const ocr_drive_file = async (app_id, doc) => {
|
|
2465
|
+
const { drive_type, uid, file_path, originalname } = doc;
|
|
2366
2466
|
|
|
2467
|
+
let target_file;
|
|
2367
2468
|
let save_ret;
|
|
2368
2469
|
try {
|
|
2369
2470
|
doc.ocr_stat = 2;
|
|
@@ -2372,24 +2473,19 @@ const ocr_drive_file = async (app_id, doc) => {
|
|
|
2372
2473
|
|
|
2373
2474
|
doc = await get_drive_doc('file', drive_type, app_id, uid, path.join(file_path, originalname));
|
|
2374
2475
|
|
|
2375
|
-
|
|
2476
|
+
target_file = await ocr_file_to_tmp(app_id, doc);
|
|
2376
2477
|
|
|
2377
|
-
|
|
2378
|
-
const countryData = countryLanguage.getCountry(cfCountry);
|
|
2379
|
-
let lang = 'eng';
|
|
2380
|
-
if (countryData && countryData.languages && countryData.languages.length > 0) {
|
|
2381
|
-
for (let language of countryData.languages) {
|
|
2382
|
-
lang += `+${language.iso639_2}`;
|
|
2383
|
-
}
|
|
2384
|
-
}
|
|
2385
|
-
return lang;
|
|
2386
|
-
}
|
|
2478
|
+
let ocr = '';
|
|
2387
2479
|
|
|
2388
2480
|
let lang = detectLanguageByCountry(doc.country);
|
|
2389
2481
|
|
|
2390
2482
|
const generalConfig = { oem: 1, psm: 3, lang };
|
|
2391
2483
|
|
|
2392
|
-
|
|
2484
|
+
// A doc written before mime was recorded would throw on .split here and be marked
|
|
2485
|
+
// failed for ever. Fall back to the extension, which every drive doc carries.
|
|
2486
|
+
const mime = doc.mime || _drive_content_type_for(doc.originalname || '') || '';
|
|
2487
|
+
|
|
2488
|
+
switch (mime.split('/')[0]) {
|
|
2393
2489
|
case 'image': {
|
|
2394
2490
|
ocr = await tesseract.recognize(target_file, generalConfig);
|
|
2395
2491
|
|
|
@@ -2397,7 +2493,7 @@ const ocr_drive_file = async (app_id, doc) => {
|
|
|
2397
2493
|
}
|
|
2398
2494
|
|
|
2399
2495
|
case 'application': {
|
|
2400
|
-
switch (
|
|
2496
|
+
switch (mime.split('/')[1]) {
|
|
2401
2497
|
case 'pdf': {
|
|
2402
2498
|
const images = await convertPDF(target_file);
|
|
2403
2499
|
for await (const imageData of images) {
|
|
@@ -2411,7 +2507,10 @@ const ocr_drive_file = async (app_id, doc) => {
|
|
|
2411
2507
|
break;
|
|
2412
2508
|
}
|
|
2413
2509
|
|
|
2510
|
+
// 'nd.ms-excel' was a typo for the real .xls mime, so no legacy spreadsheet
|
|
2511
|
+
// ever reached this branch. Both spellings kept, the wrong one costs nothing.
|
|
2414
2512
|
case 'nd.ms-excel':
|
|
2513
|
+
case 'vnd.ms-excel':
|
|
2415
2514
|
case 'vnd.openxmlformats-officedocument.spreadsheetml.sheet': {
|
|
2416
2515
|
const sheets = xlsx.parse(target_file);
|
|
2417
2516
|
sheets.forEach((sheet) => {
|
|
@@ -2429,7 +2528,7 @@ const ocr_drive_file = async (app_id, doc) => {
|
|
|
2429
2528
|
break;
|
|
2430
2529
|
|
|
2431
2530
|
default:
|
|
2432
|
-
ocr =
|
|
2531
|
+
ocr = await read_text_for_ocr(target_file);
|
|
2433
2532
|
break;
|
|
2434
2533
|
}
|
|
2435
2534
|
break;
|
|
@@ -2454,12 +2553,286 @@ const ocr_drive_file = async (app_id, doc) => {
|
|
|
2454
2553
|
doc.ocr_stat = 4;
|
|
2455
2554
|
doc.ocr_error = err.message;
|
|
2456
2555
|
} finally {
|
|
2556
|
+
// The bytes were copied here only so a reader could open them.
|
|
2557
|
+
if (target_file) await fs.promises.unlink(target_file).catch(() => {});
|
|
2457
2558
|
doc.ocr_stat_ts = Date.now();
|
|
2458
2559
|
|
|
2459
2560
|
save_ret = await save_drive_doc(drive_type, uid, app_id, doc, file_path);
|
|
2460
2561
|
}
|
|
2461
2562
|
};
|
|
2462
2563
|
|
|
2564
|
+
// ── Office previews ────────────────────────────────────────────────────────────
|
|
2565
|
+
// A deck, a document or a spreadsheet had no preview anywhere in the Drive: the
|
|
2566
|
+
// thumbnail was a grey category tile and the lightbox said "No preview available".
|
|
2567
|
+
// So render one. Each office file gets two derived assets stored beside it:
|
|
2568
|
+
//
|
|
2569
|
+
// pdf - the whole file, which the lightbox already knows how to show in an iframe
|
|
2570
|
+
// png - page/slide one, which every thumbnail in the app can draw as an image
|
|
2571
|
+
//
|
|
2572
|
+
// The conversion needs LibreOffice on the box. Where it is absent the file simply
|
|
2573
|
+
// keeps its category tile, exactly as before, and preview_stat records that so the
|
|
2574
|
+
// sweep does not retry a box that can never succeed.
|
|
2575
|
+
//
|
|
2576
|
+
// preview_stat: 0 not applicable / unsupported here, 1 queued, 2 running, 3 done, 4 failed.
|
|
2577
|
+
const PREVIEW_OFFICE_EXTS = ['.pptx', '.ppt', '.docx', '.doc', '.xlsx', '.xls', '.odp', '.odt', '.ods', '.rtf'];
|
|
2578
|
+
|
|
2579
|
+
const is_office_preview_ext = (ext) => PREVIEW_OFFICE_EXTS.includes(String(ext || '').toLowerCase());
|
|
2580
|
+
|
|
2581
|
+
// Resolved once per process. `null` means "looked and it is not here", which is a
|
|
2582
|
+
// real answer and must not be retried on every file.
|
|
2583
|
+
let _soffice_bin_cache;
|
|
2584
|
+
const soffice_bin = () => {
|
|
2585
|
+
if (_soffice_bin_cache !== undefined) return _soffice_bin_cache;
|
|
2586
|
+
_soffice_bin_cache = ['/usr/bin/soffice', '/usr/bin/libreoffice', '/usr/lib/libreoffice/program/soffice'].find((p) => {
|
|
2587
|
+
try {
|
|
2588
|
+
return fs.existsSync(p);
|
|
2589
|
+
} catch (_) {
|
|
2590
|
+
return false;
|
|
2591
|
+
}
|
|
2592
|
+
}) || null;
|
|
2593
|
+
if (!_soffice_bin_cache) console.warn('[drive_module] office previews disabled: no LibreOffice on this box');
|
|
2594
|
+
return _soffice_bin_cache;
|
|
2595
|
+
};
|
|
2596
|
+
|
|
2597
|
+
const run_cmd = (bin, args, { timeout_ms = 120000, cwd } = {}) =>
|
|
2598
|
+
new Promise((resolve, reject) => {
|
|
2599
|
+
const child = child_process.execFile(bin, args, { timeout: timeout_ms, cwd, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
2600
|
+
if (err) return reject(new Error(`${path.basename(bin)} failed: ${err.message} ${String(stderr || '').slice(0, 300)}`));
|
|
2601
|
+
resolve({ stdout, stderr });
|
|
2602
|
+
});
|
|
2603
|
+
child.on('error', reject);
|
|
2604
|
+
});
|
|
2605
|
+
|
|
2606
|
+
// Convert one office file into { pdf, png }. Runs entirely in a private temp dir so
|
|
2607
|
+
// two conversions of the same filename cannot collide, and so a partial run leaves
|
|
2608
|
+
// nothing behind.
|
|
2609
|
+
const render_office_preview = async (buffer, originalname) => {
|
|
2610
|
+
const bin = soffice_bin();
|
|
2611
|
+
if (!bin) return null;
|
|
2612
|
+
|
|
2613
|
+
const work_dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'xuda_preview_'));
|
|
2614
|
+
const src_path = path.join(work_dir, `src${path.extname(originalname) || '.bin'}`);
|
|
2615
|
+
|
|
2616
|
+
try {
|
|
2617
|
+
await fs.promises.writeFile(src_path, buffer);
|
|
2618
|
+
|
|
2619
|
+
// -env:UserInstallation gives this run its own profile dir. Without it concurrent
|
|
2620
|
+
// conversions share ~/.config/libreoffice and the second one exits doing nothing.
|
|
2621
|
+
await run_cmd(bin, [
|
|
2622
|
+
'--headless',
|
|
2623
|
+
'--norestore',
|
|
2624
|
+
'--nolockcheck',
|
|
2625
|
+
`-env:UserInstallation=file://${path.join(work_dir, 'lo_profile')}`,
|
|
2626
|
+
'--convert-to',
|
|
2627
|
+
'pdf',
|
|
2628
|
+
'--outdir',
|
|
2629
|
+
work_dir,
|
|
2630
|
+
src_path,
|
|
2631
|
+
]);
|
|
2632
|
+
|
|
2633
|
+
const pdf_path = path.join(work_dir, 'src.pdf');
|
|
2634
|
+
if (!fs.existsSync(pdf_path)) throw new Error('conversion produced no pdf');
|
|
2635
|
+
const pdf = await fs.promises.readFile(pdf_path);
|
|
2636
|
+
|
|
2637
|
+
// Page one only, capped on width so a poster-sized slide does not become a
|
|
2638
|
+
// multi-megabyte thumbnail. -singlefile keeps the output name predictable.
|
|
2639
|
+
await run_cmd('/usr/bin/pdftoppm', ['-png', '-f', '1', '-l', '1', '-singlefile', '-scale-to-x', '960', '-scale-to-y', '-1', pdf_path, path.join(work_dir, 'page1')]);
|
|
2640
|
+
|
|
2641
|
+
const png_path = path.join(work_dir, 'page1.png');
|
|
2642
|
+
if (!fs.existsSync(png_path)) throw new Error('conversion produced no page image');
|
|
2643
|
+
const png = await fs.promises.readFile(png_path);
|
|
2644
|
+
|
|
2645
|
+
return { pdf, png };
|
|
2646
|
+
} finally {
|
|
2647
|
+
await rimraf(work_dir).catch(() => {});
|
|
2648
|
+
}
|
|
2649
|
+
};
|
|
2650
|
+
|
|
2651
|
+
// Store one derived asset next to the file it came from, in the same bucket and region.
|
|
2652
|
+
const put_preview_asset = async (region, base_key, suffix, body, content_type) => {
|
|
2653
|
+
const Bucket = _conf.storage_bucket?.[region]?.name;
|
|
2654
|
+
const s3 = _drive_s3_for(region);
|
|
2655
|
+
if (!s3 || !Bucket) throw new Error(`no storage bucket for region ${region}`);
|
|
2656
|
+
const Key = `${base_key}.preview.${suffix}`;
|
|
2657
|
+
await s3.send(new PutObjectCommand({ Bucket, Key, Body: body, ContentType: content_type }));
|
|
2658
|
+
return { Bucket, Key, key: Key };
|
|
2659
|
+
};
|
|
2660
|
+
|
|
2661
|
+
// Build (or rebuild) the preview assets for one drive doc and record them on it.
|
|
2662
|
+
// Shaped like ocr_drive_file: takes the doc, mutates preview state, saves it back.
|
|
2663
|
+
const preview_drive_file = async (app_id, doc) => {
|
|
2664
|
+
const { drive_type, uid, file_path } = doc;
|
|
2665
|
+
|
|
2666
|
+
try {
|
|
2667
|
+
if (!soffice_bin()) {
|
|
2668
|
+
doc.preview_stat = 0;
|
|
2669
|
+
doc.preview_error = 'no converter on this box';
|
|
2670
|
+
doc.preview_stat_ts = Date.now();
|
|
2671
|
+
return await save_drive_doc(drive_type, uid, app_id, doc, file_path);
|
|
2672
|
+
}
|
|
2673
|
+
|
|
2674
|
+
doc.preview_stat = 2;
|
|
2675
|
+
doc.preview_stat_ts = Date.now();
|
|
2676
|
+
await save_drive_doc(drive_type, uid, app_id, doc, file_path);
|
|
2677
|
+
|
|
2678
|
+
const region = _pick_file_region(doc);
|
|
2679
|
+
const { Bucket, Key } = _drive_bucket_for(doc, region);
|
|
2680
|
+
const s3 = region ? _drive_s3_for(region) : null;
|
|
2681
|
+
if (!s3 || !Bucket || !Key) throw new Error('file bytes unavailable');
|
|
2682
|
+
|
|
2683
|
+
const obj = await s3.send(new GetObjectCommand({ Bucket, Key }));
|
|
2684
|
+
const buffer = await _stream_to_buffer(obj.Body);
|
|
2685
|
+
|
|
2686
|
+
const rendered = await render_office_preview(buffer, doc.originalname || 'file');
|
|
2687
|
+
if (!rendered) throw new Error('no converter on this box');
|
|
2688
|
+
|
|
2689
|
+
const [pdf_ref, png_ref] = await Promise.all([
|
|
2690
|
+
put_preview_asset(region, Key, 'pdf', rendered.pdf, 'application/pdf'),
|
|
2691
|
+
put_preview_asset(region, Key, 'png', rendered.png, 'image/png'),
|
|
2692
|
+
]);
|
|
2693
|
+
|
|
2694
|
+
doc.preview = { ...(doc.preview || {}), [region]: { pdf: pdf_ref, png: png_ref } };
|
|
2695
|
+
doc.preview_stat = 3;
|
|
2696
|
+
doc.preview_error = '';
|
|
2697
|
+
} catch (err) {
|
|
2698
|
+
doc.preview_stat = 4;
|
|
2699
|
+
doc.preview_error = err.message;
|
|
2700
|
+
console.error('[drive_module] preview failed for', doc?._id, err.message);
|
|
2701
|
+
} finally {
|
|
2702
|
+
doc.preview_stat_ts = Date.now();
|
|
2703
|
+
await save_drive_doc(drive_type, uid, app_id, doc, file_path).catch(() => {});
|
|
2704
|
+
}
|
|
2705
|
+
};
|
|
2706
|
+
|
|
2707
|
+
// Stat 2 means "a box is working on this right now", and the work is in-process. So a
|
|
2708
|
+
// pm2 restart mid-run (a deploy, a crash, an OOM) leaves the doc claimed by a process that
|
|
2709
|
+
// no longer exists, and nothing ever looks at stat 2 again: it is a dead end, not a state.
|
|
2710
|
+
// Anything that has been "running" for longer than the slowest plausible job is therefore
|
|
2711
|
+
// finished-by-death, and goes back in the queue. STALE_MS is generous on purpose, a big
|
|
2712
|
+
// deck with images is a slow convert and reclaiming a LIVE job would run it twice.
|
|
2713
|
+
const STRANDED_STAT_MS = 15 * 60 * 1000;
|
|
2714
|
+
|
|
2715
|
+
const reclaim_stranded = async (app_id, docType, stat_field, ts_field) => {
|
|
2716
|
+
try {
|
|
2717
|
+
const ret = await db_module.find_app_couch_query(app_id, {
|
|
2718
|
+
selector: { docType, type: 'file', [stat_field]: 2 },
|
|
2719
|
+
limit: 50,
|
|
2720
|
+
});
|
|
2721
|
+
const stale = (ret?.docs || []).filter((d) => !d[ts_field] || Date.now() - d[ts_field] > STRANDED_STAT_MS);
|
|
2722
|
+
for (const doc of stale) {
|
|
2723
|
+
doc[stat_field] = 1;
|
|
2724
|
+
await save_drive_doc(doc.drive_type, doc.uid, docType === 'user_drive' ? null : app_id, doc, doc.file_path).catch(() => {});
|
|
2725
|
+
console.warn(`[drive_module] reclaimed stranded ${stat_field}=2 on ${doc._id}`);
|
|
2726
|
+
}
|
|
2727
|
+
} catch (err) {
|
|
2728
|
+
console.error('[drive_module] reclaim_stranded failed', docType, stat_field, err.message);
|
|
2729
|
+
}
|
|
2730
|
+
};
|
|
2731
|
+
|
|
2732
|
+
// Same sweep shape as run_drive_pending_ocr, and the same region-ownership rule:
|
|
2733
|
+
// only the box that owns the app converts its files, so an active/standby pair does
|
|
2734
|
+
// not run the same conversion twice and race the write.
|
|
2735
|
+
export const run_drive_pending_previews = async () => {
|
|
2736
|
+
try {
|
|
2737
|
+
if (!soffice_bin()) return { code: 1, data: 'no converter on this box' };
|
|
2738
|
+
|
|
2739
|
+
const app_res = await db_module.find_couch_query('xuda_master', {
|
|
2740
|
+
selector: {
|
|
2741
|
+
docType: 'app',
|
|
2742
|
+
app_status_code: { $eq: 3 },
|
|
2743
|
+
$or: [{ app_type: 'master' }, { app_type: 'instance' }, { app_type: 'datacenter' }],
|
|
2744
|
+
},
|
|
2745
|
+
limit: 99999,
|
|
2746
|
+
});
|
|
2747
|
+
|
|
2748
|
+
let done = 0;
|
|
2749
|
+
for (let app of app_res.docs) {
|
|
2750
|
+
if (!_common.is_app_owned_by_local_box(app)) continue;
|
|
2751
|
+
|
|
2752
|
+
for (const docType of ['user_drive', 'workspace_drive']) {
|
|
2753
|
+
const owner = docType === 'user_drive' ? null : app._id;
|
|
2754
|
+
|
|
2755
|
+
await reclaim_stranded(app._id, docType, 'preview_stat', 'preview_stat_ts');
|
|
2756
|
+
|
|
2757
|
+
const queued = await db_module.find_app_couch_query(app._id, {
|
|
2758
|
+
selector: { docType, preview_stat: 1, stat: 3 },
|
|
2759
|
+
limit: 5,
|
|
2760
|
+
});
|
|
2761
|
+
for await (let doc of queued.docs) {
|
|
2762
|
+
await preview_drive_file(owner, doc);
|
|
2763
|
+
done++;
|
|
2764
|
+
}
|
|
2765
|
+
if (queued.docs?.length) continue;
|
|
2766
|
+
|
|
2767
|
+
// Backfill: every file that predates this feature has no preview_stat at all, so
|
|
2768
|
+
// the queued pass above can never see it. Filtered in JS rather than with $in on
|
|
2769
|
+
// file_ext, which no index can serve.
|
|
2770
|
+
const legacy = await db_module.find_app_couch_query(app._id, {
|
|
2771
|
+
selector: { docType, stat: 3, type: 'file', preview_stat: { $exists: false } },
|
|
2772
|
+
limit: 60,
|
|
2773
|
+
});
|
|
2774
|
+
const legacy_docs = legacy.docs || [];
|
|
2775
|
+
|
|
2776
|
+
// Stamp the ones that will never have a preview, so the batch above returns
|
|
2777
|
+
// different docs next tick. Without this a drive whose first 60 files are all
|
|
2778
|
+
// images hands back the same 60 for ever and the backfill never advances.
|
|
2779
|
+
for await (let doc of legacy_docs.filter((d) => !is_office_preview_ext(d.file_ext))) {
|
|
2780
|
+
doc.preview_stat = 0;
|
|
2781
|
+
await save_drive_doc(doc.drive_type, doc.uid, owner, doc, doc.file_path).catch(() => {});
|
|
2782
|
+
}
|
|
2783
|
+
|
|
2784
|
+
for await (let doc of legacy_docs.filter((d) => is_office_preview_ext(d.file_ext)).slice(0, 5)) {
|
|
2785
|
+
await preview_drive_file(owner, doc);
|
|
2786
|
+
done++;
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
return { code: 1, data: `previewed ${done}` };
|
|
2791
|
+
} catch (err) {
|
|
2792
|
+
return { code: -400, data: err.message };
|
|
2793
|
+
}
|
|
2794
|
+
};
|
|
2795
|
+
|
|
2796
|
+
// Called right after an upload so the preview is there in seconds rather than on the
|
|
2797
|
+
// next sweep. Deliberately tolerant: an unconvertible file must never fail its upload.
|
|
2798
|
+
export const generate_drive_file_preview = async (req) => {
|
|
2799
|
+
try {
|
|
2800
|
+
const { app_id, drive_type = 'user', uid, doc_id } = req || {};
|
|
2801
|
+
if (!doc_id) return { code: -1, data: 'doc_id required' };
|
|
2802
|
+
|
|
2803
|
+
const project_id = drive_type === 'user' ? await get_account_default_project_id(uid) : await _common.get_project_app_id(app_id);
|
|
2804
|
+
const ret = await db_module.get_app_couch_doc(project_id, doc_id);
|
|
2805
|
+
const doc = ret?.code >= 0 ? ret.data : null;
|
|
2806
|
+
if (!doc || doc.type !== 'file') return { code: -404, data: 'not_found' };
|
|
2807
|
+
if (!is_office_preview_ext(doc.file_ext)) return { code: 1, data: 'not previewable' };
|
|
2808
|
+
|
|
2809
|
+
await preview_drive_file(drive_type === 'user' ? null : app_id, doc);
|
|
2810
|
+
return { code: 1, data: { preview_stat: doc.preview_stat, preview_error: doc.preview_error || '' } };
|
|
2811
|
+
} catch (err) {
|
|
2812
|
+
return { code: -400, data: err.message };
|
|
2813
|
+
}
|
|
2814
|
+
};
|
|
2815
|
+
|
|
2816
|
+
// The links the UI needs, or nothing at all when there is no preview yet. Returned on
|
|
2817
|
+
// every drive row so a thumbnail and a lightbox can decide without a second call.
|
|
2818
|
+
//
|
|
2819
|
+
// preview_pending is the third answer, and it matters most right after an AI builds a
|
|
2820
|
+
// deck: the file is saved and its card renders in the chat within a second, while the
|
|
2821
|
+
// conversion behind it takes several. Without this the card can only say "no preview" and
|
|
2822
|
+
// mean "not yet", so it stayed a grey tile until the page was reloaded. Telling the client
|
|
2823
|
+
// a preview is coming lets it look again, and only for files that will actually get one.
|
|
2824
|
+
const preview_links_for = (doc, base_link) => {
|
|
2825
|
+
const region = doc?.preview ? _pick_file_region({ bucket: doc.preview }) || Object.keys(doc.preview)[0] : null;
|
|
2826
|
+
if (!region || !doc.preview[region]?.png) {
|
|
2827
|
+
return [1, 2].includes(doc?.preview_stat) ? { preview_pending: true } : {};
|
|
2828
|
+
}
|
|
2829
|
+
const sep = base_link.includes('?') ? '&' : '?';
|
|
2830
|
+
return {
|
|
2831
|
+
preview_link: `${base_link}${sep}preview=png`,
|
|
2832
|
+
preview_doc_link: `${base_link}${sep}preview=pdf`,
|
|
2833
|
+
};
|
|
2834
|
+
};
|
|
2835
|
+
|
|
2463
2836
|
const validate_drive_type = (drive_type) => {
|
|
2464
2837
|
if (!['studio', 'workspace', 'user'].includes(drive_type)) {
|
|
2465
2838
|
throw new Error('error - drive_type values allowed: studio, workspace or users');
|
|
@@ -2500,6 +2873,11 @@ export const run_drive_pending_ocr = async () => {
|
|
|
2500
2873
|
// active/standby master pair double-run expensive OCR and race the writes.
|
|
2501
2874
|
if (!_common.is_app_owned_by_local_box(app)) continue;
|
|
2502
2875
|
|
|
2876
|
+
// Same dead-end as the preview sweep: ocr_stat 2 survives the restart that killed
|
|
2877
|
+
// the run holding it, and nothing ever selects a 2 again.
|
|
2878
|
+
await reclaim_stranded(app._id, 'user_drive', 'ocr_stat', 'ocr_stat_date');
|
|
2879
|
+
await reclaim_stranded(app._id, 'workspace_drive', 'ocr_stat', 'ocr_stat_date');
|
|
2880
|
+
|
|
2503
2881
|
let opt = {
|
|
2504
2882
|
selector: { docType: 'user_drive', ocr_stat: 1, stat: 3 },
|
|
2505
2883
|
limit: 1,
|
|
@@ -3185,6 +3563,64 @@ export const get_user_drive_file = async function (uid, filename) {
|
|
|
3185
3563
|
return drive_ret;
|
|
3186
3564
|
};
|
|
3187
3565
|
|
|
3566
|
+
// Look a user-drive file up by the id in its access link, for surfaces that hold a
|
|
3567
|
+
// link and nothing else (an AI chat reply that produced a file, a pasted link). The
|
|
3568
|
+
// listing methods all key off a folder path, which a link does not carry.
|
|
3569
|
+
//
|
|
3570
|
+
// Returns the SAME row shape a listing child has, so a caller can hand it straight to
|
|
3571
|
+
// the drive thumbnail and lightbox. file_path is the point of the call: it is what
|
|
3572
|
+
// "Show in drive" needs to reveal the file, and it cannot be derived from the link.
|
|
3573
|
+
//
|
|
3574
|
+
// The lookup runs in the CALLER's own project (get_user_drive_file resolves the project
|
|
3575
|
+
// from the authenticated uid, never from anything the client sends), so a link into
|
|
3576
|
+
// someone else's drive answers not_found here. That is the honest answer: the file may
|
|
3577
|
+
// be readable over its link, but it is not in this user's drive and Show in drive has
|
|
3578
|
+
// nothing to reveal.
|
|
3579
|
+
export const get_user_drive_file_by_id = async (req) => {
|
|
3580
|
+
try {
|
|
3581
|
+
const uid = req.uid || req.token_ret?.data?.uid;
|
|
3582
|
+
if (!uid) return { code: -1, data: 'uid_required' };
|
|
3583
|
+
|
|
3584
|
+
// Links may carry a cache-buster (?ts=) and are often pasted URL-encoded.
|
|
3585
|
+
const raw = String(req.file_id || '').trim();
|
|
3586
|
+
const file_id = decodeURIComponent(raw.split('?')[0].split('/').filter(Boolean).pop() || '');
|
|
3587
|
+
if (!file_id) return { code: -1, data: 'file_id_required' };
|
|
3588
|
+
|
|
3589
|
+
const ret = await get_user_drive_file(uid, file_id);
|
|
3590
|
+
const doc = ret?.code >= 0 ? ret.data : null;
|
|
3591
|
+
if (!doc || doc.type !== 'file' || doc.stat === 4) return { code: -404, data: 'not_found' };
|
|
3592
|
+
|
|
3593
|
+
const app_id = await get_account_default_project_id(uid);
|
|
3594
|
+
const fmt = (b = 0) =>
|
|
3595
|
+
b < 1024 ? b + ' Bytes' : b < 1048576 ? (b / 1024).toFixed(2) + ' KB' : b < 1073741824 ? (b / 1048576).toFixed(2) + ' MB' : (b / 1073741824).toFixed(2) + ' GB';
|
|
3596
|
+
|
|
3597
|
+
const access_link = `https://${process.env.XUDA_HOSTNAME}/user-drive/${app_id}/${doc._id}`;
|
|
3598
|
+
|
|
3599
|
+
return {
|
|
3600
|
+
code: 200,
|
|
3601
|
+
data: {
|
|
3602
|
+
name: doc.originalname,
|
|
3603
|
+
sizeInBytes: doc.size,
|
|
3604
|
+
size: fmt(doc.size),
|
|
3605
|
+
extension: doc?.file_ext?.substr(1),
|
|
3606
|
+
type: doc.type,
|
|
3607
|
+
access_link,
|
|
3608
|
+
...preview_links_for(doc, access_link),
|
|
3609
|
+
is_archive: doc.is_archive,
|
|
3610
|
+
public: doc.public,
|
|
3611
|
+
path: doc.file_path,
|
|
3612
|
+
date_created: doc.date_created,
|
|
3613
|
+
date_modified: doc.date_modified,
|
|
3614
|
+
file_path: path.join(doc.file_path, doc.originalname),
|
|
3615
|
+
tags: doc.tags || [],
|
|
3616
|
+
starred: !!doc.starred,
|
|
3617
|
+
},
|
|
3618
|
+
};
|
|
3619
|
+
} catch (err) {
|
|
3620
|
+
return { code: -404, data: 'not_found' };
|
|
3621
|
+
}
|
|
3622
|
+
};
|
|
3623
|
+
|
|
3188
3624
|
// ── Static-site vibe: see + edit the site's source folder directly through the
|
|
3189
3625
|
// cpi (Spaces + CouchDB) — no temp dir, no server disk growth. The "folder" is
|
|
3190
3626
|
// the app's static_website.source.folder_path; files live in Spaces, hierarchy
|
|
@@ -3284,9 +3720,7 @@ export const read_site_file = async (req) => {
|
|
|
3284
3720
|
const d = ret?.docs?.[0];
|
|
3285
3721
|
if (!d) return { code: -1, data: `file not found: ${rel}` };
|
|
3286
3722
|
const region = _pick_file_region(d);
|
|
3287
|
-
const
|
|
3288
|
-
const Bucket = b.Bucket || b.bucket;
|
|
3289
|
-
const Key = b.Key || b.key;
|
|
3723
|
+
const { Bucket, Key } = _drive_bucket_for(d, region);
|
|
3290
3724
|
const s3 = region ? _drive_s3_for(region) : null;
|
|
3291
3725
|
if (!s3 || !Bucket || !Key) return { code: -1, data: 'file bytes unavailable' };
|
|
3292
3726
|
const obj = await s3.send(new GetObjectCommand({ Bucket, Key }));
|
|
@@ -3695,6 +4129,23 @@ const _pick_file_region = (doc) => {
|
|
|
3695
4129
|
return null;
|
|
3696
4130
|
};
|
|
3697
4131
|
|
|
4132
|
+
// Where a drive doc's bytes actually live, for a given region.
|
|
4133
|
+
//
|
|
4134
|
+
// The CONFIG's bucket name wins over the one stored on the doc. Docs written before the
|
|
4135
|
+
// DigitalOcean to R2 migration still carry the old Spaces bucket in doc.bucket[region],
|
|
4136
|
+
// which no longer exists, so trusting the doc fails with "The specified bucket does not
|
|
4137
|
+
// exist" on files that serve perfectly well over https. The router has always resolved the
|
|
4138
|
+
// bucket from config alone (_presign_get), which is exactly why it can still read them;
|
|
4139
|
+
// this keeps every other reader consistent with the one that works. The doc's own name is
|
|
4140
|
+
// kept as a fallback for a region that config does not describe.
|
|
4141
|
+
const _drive_bucket_for = (doc, region) => {
|
|
4142
|
+
const entry = (region && doc?.bucket?.[region]) || {};
|
|
4143
|
+
return {
|
|
4144
|
+
Bucket: (region && _conf.storage_bucket?.[region]?.name) || entry.Bucket || entry.bucket || null,
|
|
4145
|
+
Key: entry.Key || entry.key || null,
|
|
4146
|
+
};
|
|
4147
|
+
};
|
|
4148
|
+
|
|
3698
4149
|
const _stream_to_buffer = async (stream) => {
|
|
3699
4150
|
if (!stream) return Buffer.alloc(0);
|
|
3700
4151
|
// AWS SDK v3 Body is a Node Readable in this runtime.
|
|
@@ -3734,9 +4185,7 @@ export const read_user_drive_folder = async (req) => {
|
|
|
3734
4185
|
for (const d of docs) {
|
|
3735
4186
|
// Resolve the file's own region, then read from THAT region's bucket.
|
|
3736
4187
|
const region = _pick_file_region(d);
|
|
3737
|
-
const
|
|
3738
|
-
const Bucket = b.Bucket || b.bucket || (region && _conf.storage_bucket?.[region]?.name);
|
|
3739
|
-
const Key = b.Key || b.key;
|
|
4188
|
+
const { Bucket, Key } = _drive_bucket_for(d, region);
|
|
3740
4189
|
const s3 = region ? _drive_s3_for(region) : null;
|
|
3741
4190
|
if (!s3 || !Bucket || !Key) {
|
|
3742
4191
|
// No reachable region (e.g. datacenter-scp file with no Spaces
|
|
@@ -3841,9 +4290,7 @@ export const fetch_drive_file_to_tmp = async (req) => {
|
|
|
3841
4290
|
if (!doc) return { code: -1, data: `file not found: ${file_ref}` };
|
|
3842
4291
|
|
|
3843
4292
|
const region = _pick_file_region(doc);
|
|
3844
|
-
const
|
|
3845
|
-
const Bucket = b.Bucket || b.bucket || (region && _conf.storage_bucket?.[region]?.name);
|
|
3846
|
-
const Key = b.Key || b.key;
|
|
4293
|
+
const { Bucket, Key } = _drive_bucket_for(doc, region);
|
|
3847
4294
|
const s3 = region ? _drive_s3_for(region) : null;
|
|
3848
4295
|
if (!s3 || !Bucket || !Key) return { code: -1, data: 'file bytes unavailable' };
|
|
3849
4296
|
|
package/index_ms.mjs
CHANGED
|
@@ -121,6 +121,14 @@ export const check_drive_file = async function (...args) {
|
|
|
121
121
|
return await broker.send_to_queue("check_drive_file", ...args);
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
+
export const run_drive_pending_previews = async function (...args) {
|
|
125
|
+
return await broker.send_to_queue("run_drive_pending_previews", ...args);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export const generate_drive_file_preview = async function (...args) {
|
|
129
|
+
return await broker.send_to_queue("generate_drive_file_preview", ...args);
|
|
130
|
+
};
|
|
131
|
+
|
|
124
132
|
export const run_drive_pending_ocr = async function (...args) {
|
|
125
133
|
return await broker.send_to_queue("run_drive_pending_ocr", ...args);
|
|
126
134
|
};
|
|
@@ -153,6 +161,10 @@ export const update_drive_addons = async function (...args) {
|
|
|
153
161
|
return await broker.send_to_queue("update_drive_addons", ...args);
|
|
154
162
|
};
|
|
155
163
|
|
|
164
|
+
export const get_user_drive_file_by_id = async function (...args) {
|
|
165
|
+
return await broker.send_to_queue("get_user_drive_file_by_id", ...args);
|
|
166
|
+
};
|
|
167
|
+
|
|
156
168
|
export const list_site_files = async function (...args) {
|
|
157
169
|
return await broker.send_to_queue("list_site_files", ...args);
|
|
158
170
|
};
|
package/index_msa.mjs
CHANGED
|
@@ -121,6 +121,14 @@ export const check_drive_file = function (...args) {
|
|
|
121
121
|
broker.send_to_queue_async("check_drive_file", ...args);
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
+
export const run_drive_pending_previews = function (...args) {
|
|
125
|
+
broker.send_to_queue_async("run_drive_pending_previews", ...args);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export const generate_drive_file_preview = function (...args) {
|
|
129
|
+
broker.send_to_queue_async("generate_drive_file_preview", ...args);
|
|
130
|
+
};
|
|
131
|
+
|
|
124
132
|
export const run_drive_pending_ocr = function (...args) {
|
|
125
133
|
broker.send_to_queue_async("run_drive_pending_ocr", ...args);
|
|
126
134
|
};
|
|
@@ -153,6 +161,10 @@ export const update_drive_addons = function (...args) {
|
|
|
153
161
|
broker.send_to_queue_async("update_drive_addons", ...args);
|
|
154
162
|
};
|
|
155
163
|
|
|
164
|
+
export const get_user_drive_file_by_id = function (...args) {
|
|
165
|
+
broker.send_to_queue_async("get_user_drive_file_by_id", ...args);
|
|
166
|
+
};
|
|
167
|
+
|
|
156
168
|
export const list_site_files = function (...args) {
|
|
157
169
|
broker.send_to_queue_async("list_site_files", ...args);
|
|
158
170
|
};
|