dragonflight/services/premiere-plugin-uxp/src/import-flow.js

167 lines
7.1 KiB
JavaScript
Raw Normal View History

// import-flow.js — v2.1.4
// Root cause of "Cannot read properties of undefined (reading)":
// response.body is null when redirect:'manual' is used — that fetch option
// is NOT supported in UXP. UXP auto-follows redirects and does NOT expose
// manual redirect control. Dropping redirect:'manual' entirely.
//
// Download strategy:
// response.arrayBuffer() → write entire buffer via fs.writeFile()
// Simpler than fd-based chunked write, works for proxy files (typically <2GB).
// Progress reporting is approximate (0% → 100% on completion).
(function () {
const Import = {};
const fs = require('fs');
// window.path is a UXP global (v6.4+) — no require('path')
// os.tmpdir() not in UXP — use env.TEMP or uxp storage
let os; try { os = require('os'); } catch (_) { os = {}; }
let uxpFs; try { uxpFs = require('uxp').storage.localFileSystem; } catch (_) { uxpFs = null; }
// ── Temp folder ──────────────────────────────────────────────────
async function _getTempBase() {
if (uxpFs && uxpFs.getTemporaryFolder) {
try {
const tmp = await uxpFs.getTemporaryFolder();
if (tmp && tmp.nativePath) return tmp.nativePath;
} catch (_) {}
}
try {
const e = (typeof process !== 'undefined' && process.env) || {};
if (e.TEMP && e.TEMP.length) return e.TEMP;
if (e.TMP && e.TMP.length) return e.TMP;
if (e.LOCALAPPDATA) return e.LOCALAPPDATA + '\\Temp';
} catch (_) {}
try {
if (os.homedir) {
const h = os.homedir();
if (h) return h + '\\AppData\\Local\\Temp';
}
} catch (_) {}
throw new Error('Cannot find writable temp folder');
}
Import._tempPath = async function (safeName) {
const base = await _getTempBase();
return path.join(base, 'dragonflight-' + safeName);
};
// ── Write ArrayBuffer to disk ────────────────────────────────────
// fs.writeFile with flag:'w' creates/overwrites the file.
Import._writeBuffer = async function (destPath, arrayBuffer) {
await fs.writeFile(destPath, arrayBuffer);
return destPath;
};
// ── Fetch with auth — UXP-safe ───────────────────────────────────
// UXP auto-follows redirects. 'redirect' option is NOT supported.
// We only add Authorization for same-origin requests (server URL base).
// For S3 presigned URLs (off-origin) we do NOT add Bearer — that would
// break the presigned signature.
async function _fetch(url, addAuth) {
const headers = {};
if (addAuth && API.state.apiToken) {
headers['Authorization'] = 'Bearer ' + API.state.apiToken;
}
const r = await fetch(url, { headers });
if (!r.ok) throw new Error('HTTP ' + r.status + ' from ' + url);
return r;
}
// ── premierepro lazy require ─────────────────────────────────────
function _ppro() {
if (Import._ppro_mod) return Import._ppro_mod;
try { Import._ppro_mod = require('premierepro'); }
catch (e) { throw new Error('UXP premierepro unavailable: ' + e.message); }
return Import._ppro_mod;
}
// Import a file already on disk into the active Premiere project.
// project.importFiles() is async (it actually imports the file).
Import.importIntoProject = async function (filePath) {
const P = _ppro();
const project = P.Project.getActiveProject(); // sync
if (!project) throw new Error('No active Premiere project');
const root = project.getRootItem(); // sync
const ok = await project.importFiles([filePath], true, root, false);
if (!ok) throw new Error('Premiere refused to import file');
return true;
};
// ── Proxy import ─────────────────────────────────────────────────
Import.proxy = async function (asset) {
const safeName = UI.sanitizeFilename((asset.display_name || asset.filename || asset.id) + '.mp4');
const dest = await Import._tempPath(safeName);
UI.showProgress('Resolving proxy URL…', 4);
const { url } = await API.getProxyUrl(asset.id);
UI.showProgress('Downloading ' + safeName + '…', 10);
// Same-origin proxy URL — add auth
const r = await _fetch(url, true);
UI.showProgress('Writing to disk…', 70);
const buf = await r.arrayBuffer();
await Import._writeBuffer(dest, buf);
UI.showProgress('Importing into Premiere…', 92);
await Import.importIntoProject(dest);
UI.hideProgress();
UI.toast('Imported: ' + safeName, 'ok');
return { localPath: dest, safeName };
};
// ── Hi-Res import ────────────────────────────────────────────────
Import.hires = async function (asset) {
UI.showProgress('Resolving hi-res URL…', 4);
const info = await API.getHiresInfo(asset.id);
const safeName = UI.sanitizeFilename(info.filename || (asset.display_name || asset.id) + '.' + (info.ext || 'mxf'));
const dest = await Import._tempPath(safeName);
UI.showProgress('Downloading ' + safeName + ' (' + UI.formatBytes(Number(info.file_size || 0)) + ')…', 8);
// Presigned S3 URL — no auth header (would break signature)
const r = await _fetch(info.url, false);
UI.showProgress('Writing to disk…', 75);
const buf = await r.arrayBuffer();
await Import._writeBuffer(dest, buf);
UI.showProgress('Importing into Premiere…', 92);
await Import.importIntoProject(dest);
UI.hideProgress();
UI.toast('Hi-res imported: ' + safeName, 'ok');
return { localPath: dest, safeName };
};
// Expose for timeline.js batch relink (it downloads hi-res files too)
Import._streamToFile = async function (response, destPath, onProgress) {
// In UXP, response.body may be null — fall back to arrayBuffer()
if (response.body && response.body.getReader) {
const total = Number(response.headers.get('content-length') || 0);
const reader = response.body.getReader();
const fd = await fs.open(destPath, 'w');
let received = 0, filePos = 0;
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
const buf = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
const { bytesWritten } = await fs.write(fd, buf, 0, buf.byteLength, filePos);
filePos += bytesWritten;
received += value.byteLength;
if (onProgress) onProgress({ received, total });
}
} finally { await fs.close(fd); }
} else {
// Fallback: buffer entire response
if (onProgress) onProgress({ received: 0, total: 0 });
const buf = await response.arrayBuffer();
await Import._writeBuffer(destPath, buf);
if (onProgress) onProgress({ received: buf.byteLength, total: buf.byteLength });
}
return destPath;
};
window.Import = Import;
})();