41 lines
1.4 KiB
JavaScript
41 lines
1.4 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const mime = require('mime-types');
|
|
const { getContainerContext, resolveContainerPath } = require('./container_bridge');
|
|
|
|
function resolvePath(workspace, p) {
|
|
if (path.isAbsolute(p)) return p;
|
|
return path.join(workspace, p);
|
|
}
|
|
|
|
function readMediafileTool(workspace, args) {
|
|
const ctx = getContainerContext();
|
|
let target = resolvePath(workspace, args.path);
|
|
let displayPath = target;
|
|
if (ctx) {
|
|
const resolved = resolveContainerPath(workspace, args.path || '.', ctx);
|
|
if (resolved.error) return { success: false, error: resolved.error };
|
|
target = resolved.hostPath;
|
|
displayPath = resolved.containerPath;
|
|
}
|
|
try {
|
|
const stat = fs.statSync(target);
|
|
if (!stat.isFile()) return { success: false, error: '不是文件' };
|
|
const mt = mime.lookup(target);
|
|
if (!mt) return { success: false, error: '无法识别文件类型' };
|
|
if (!mt.startsWith('image/') && !mt.startsWith('video/')) {
|
|
return { success: false, error: '禁止的文件类型' };
|
|
}
|
|
const data = fs.readFileSync(target);
|
|
const b64 = data.toString('base64');
|
|
const type = mt.startsWith('image/') ? 'image' : 'video';
|
|
return { success: true, path: displayPath, mime: mt, type, b64 };
|
|
} catch (err) {
|
|
return { success: false, error: err.message || String(err) };
|
|
}
|
|
}
|
|
|
|
module.exports = { readMediafileTool };
|