| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 |
- /**
- * @node image
- * @name Image
- * @category image
- * @version 1.0.0
- * @description Extract image information, metadata, and EXIF data using ImageMagick
- * @icon image
- */
- const configSchema = {
- type: 'object',
- properties: {
- operation: {
- type: 'string',
- title: 'Operation',
- enum: ['info', 'resize', 'crop', 'rotate', 'filter', 'convert'],
- enumLabels: ['Info', 'Resize', 'Crop', 'Rotate', 'Filter', 'Convert Format'],
- default: 'info',
- description: 'Image operation to perform'
- },
- inputSource: {
- type: 'string',
- title: 'Input Source',
- enum: ['auto', 'base64', 'filePath', 'url', 'storage'],
- enumLabels: ['Auto-detect', 'Base64 Data', 'File Path', 'URL', 'Storage Reference'],
- default: 'auto',
- description: 'Source type for the input image'
- },
- base64Data: {
- type: 'string',
- title: 'Base64 Image Data',
- description: 'Base64-encoded image data. Supports {{variable}} interpolation.',
- showWhen: { field: 'inputSource', value: 'base64' }
- },
- filePath: {
- type: 'string',
- title: 'File Path',
- description: 'Path to image file on runner filesystem. Supports {{variable}} interpolation.',
- showWhen: { field: 'inputSource', value: 'filePath' }
- },
- url: {
- type: 'string',
- title: 'Image URL',
- description: 'URL to download image from. Supports {{variable}} interpolation.',
- showWhen: { field: 'inputSource', value: 'url' }
- },
- storageCollection: {
- type: 'string',
- title: 'Storage Collection',
- description: 'Collection name for stored image',
- showWhen: { field: 'inputSource', value: 'storage' }
- },
- storageId: {
- type: 'string',
- title: 'Storage Document ID',
- description: 'Document ID in storage collection. Supports {{variable}} interpolation.',
- showWhen: { field: 'inputSource', value: 'storage' }
- },
- includeExif: {
- type: 'boolean',
- title: 'Include EXIF Metadata',
- default: true,
- description: 'Extract EXIF metadata (camera info, GPS, date taken, etc.)',
- showWhen: { field: 'operation', value: 'info' }
- },
- timeout: {
- type: 'number',
- title: 'Timeout (ms)',
- default: 30000,
- minimum: 1000,
- maximum: 120000,
- description: 'Maximum time to wait for image processing'
- }
- },
- required: ['operation']
- };
- const inputSchema = {
- type: 'object',
- properties: {
- data: {
- type: 'any',
- description: 'Input data. Can be base64 string, file path, URL, or binary object from another node.'
- },
- file: {
- type: 'object',
- description: 'Binary file object with type, data (base64), mimeType, filename'
- },
- storage: {
- type: 'object',
- description: 'Storage reference with collection and id'
- },
- base64: {
- type: 'string',
- description: 'Base64-encoded image data'
- },
- filePath: {
- type: 'string',
- description: 'Override file path from input'
- },
- url: {
- type: 'string',
- description: 'Override URL from input'
- }
- }
- };
- const outputSchema = {
- type: 'object',
- properties: {
- width: {
- type: 'number',
- description: 'Image width in pixels'
- },
- height: {
- type: 'number',
- description: 'Image height in pixels'
- },
- format: {
- type: 'string',
- description: 'Image format (JPEG, PNG, GIF, etc.)'
- },
- colorSpace: {
- type: 'string',
- description: 'Color space (sRGB, CMYK, Grayscale, etc.)'
- },
- depth: {
- type: 'number',
- description: 'Bit depth per channel'
- },
- fileSize: {
- type: 'number',
- description: 'File size in bytes'
- },
- dpi: {
- type: 'object',
- description: 'DPI/resolution information',
- properties: {
- x: { type: 'number' },
- y: { type: 'number' },
- unit: { type: 'string' }
- }
- },
- hasAlpha: {
- type: 'boolean',
- description: 'Whether image has alpha/transparency channel'
- },
- compression: {
- type: 'string',
- description: 'Compression type used'
- },
- exif: {
- type: 'object',
- description: 'EXIF metadata (if available)',
- properties: {
- camera: {
- type: 'object',
- properties: {
- make: { type: 'string' },
- model: { type: 'string' },
- software: { type: 'string' }
- }
- },
- datetime: {
- type: 'object',
- properties: {
- original: { type: 'string' },
- digitized: { type: 'string' },
- modified: { type: 'string' }
- }
- },
- gps: {
- type: 'object',
- properties: {
- latitude: { type: 'number' },
- longitude: { type: 'number' },
- altitude: { type: 'number' },
- latitudeRef: { type: 'string' },
- longitudeRef: { type: 'string' }
- }
- },
- exposure: {
- type: 'object',
- properties: {
- time: { type: 'string' },
- fNumber: { type: 'number' },
- iso: { type: 'number' },
- program: { type: 'string' },
- bias: { type: 'string' }
- }
- },
- lens: {
- type: 'object',
- properties: {
- focalLength: { type: 'string' },
- focalLength35mm: { type: 'number' },
- aperture: { type: 'number' },
- make: { type: 'string' },
- model: { type: 'string' }
- }
- },
- orientation: { type: 'number' },
- flash: { type: 'string' },
- whiteBalance: { type: 'string' },
- meteringMode: { type: 'string' }
- }
- },
- sourceType: {
- type: 'string',
- description: 'Source type used (base64, filePath, url, storage)'
- },
- sourcePath: {
- type: 'string',
- description: 'Temporary file path used for processing'
- }
- }
- };
- function interpolate(template, data) {
- if (typeof template !== 'string') return template;
- return template.replace(/\{\{([^}]+)\}\}/g, function(match, key) {
- var keys = key.trim().split('.');
- var value = data;
- for (var i = 0; i < keys.length; i++) {
- if (value && typeof value === 'object' && keys[i] in value) {
- value = value[keys[i]];
- } else {
- return match;
- }
- }
- return value !== undefined ? String(value) : match;
- });
- }
- function generateTempPath(extension) {
- var uuid = smartbotic.utils.uuid();
- return '/tmp/smartbotic-image-' + uuid + (extension ? '.' + extension : '');
- }
- function detectImageFormat(base64Data) {
- if (!base64Data || base64Data.length < 8) return null;
- var header = smartbotic.utils.base64Decode(base64Data.substring(0, 16));
- if (!header) return null;
- if (header.charCodeAt(0) === 0xFF && header.charCodeAt(1) === 0xD8 && header.charCodeAt(2) === 0xFF) {
- return 'jpg';
- }
- if (header.substring(0, 8) === '\x89PNG\r\n\x1a\n') {
- return 'png';
- }
- if (header.substring(0, 6) === 'GIF87a' || header.substring(0, 6) === 'GIF89a') {
- return 'gif';
- }
- if (header.substring(0, 4) === 'RIFF' && header.substring(8, 12) === 'WEBP') {
- return 'webp';
- }
- if (header.substring(0, 2) === 'BM') {
- return 'bmp';
- }
- if (header.substring(0, 4) === 'II*\x00' || header.substring(0, 4) === 'MM\x00*') {
- return 'tiff';
- }
- return null;
- }
- function resolveImageInput(config, input) {
- var inputSource = config.inputSource || 'auto';
- var result = { type: null, data: null, path: null, tempPath: null };
- if (inputSource === 'filePath' || (inputSource === 'auto' && input.filePath)) {
- var filePath = input.filePath || interpolate(config.filePath, input);
- if (filePath && smartbotic.fs.exists(filePath)) {
- result.type = 'filePath';
- result.path = filePath;
- return result;
- }
- }
- if (inputSource === 'base64' || (inputSource === 'auto' && (input.base64 || config.base64Data))) {
- var base64 = input.base64 || interpolate(config.base64Data, input);
- if (base64) {
- result.type = 'base64';
- result.data = base64;
- return result;
- }
- }
- if (inputSource === 'url' || (inputSource === 'auto' && (input.url || config.url))) {
- var url = input.url || interpolate(config.url, input);
- if (url) {
- result.type = 'url';
- result.data = url;
- return result;
- }
- }
- if (inputSource === 'storage' || (inputSource === 'auto' && input.storage)) {
- var collection = input.storage ? input.storage.collection : config.storageCollection;
- var id = input.storage ? input.storage.id : interpolate(config.storageId, input);
- if (collection && id) {
- result.type = 'storage';
- result.data = { collection: collection, id: id };
- return result;
- }
- }
- if (inputSource === 'auto') {
- if (input.file && input.file.type === 'binary' && input.file.data) {
- result.type = 'base64';
- result.data = input.file.data;
- return result;
- }
- if (typeof input.data === 'string') {
- if (input.data.match(/^[A-Za-z0-9+/]+=*$/) && input.data.length > 100) {
- result.type = 'base64';
- result.data = input.data;
- return result;
- }
- if (input.data.startsWith('http://') || input.data.startsWith('https://')) {
- result.type = 'url';
- result.data = input.data;
- return result;
- }
- if (smartbotic.fs.exists(input.data)) {
- result.type = 'filePath';
- result.path = input.data;
- return result;
- }
- }
- if (input.data && typeof input.data === 'object') {
- if (input.data.type === 'binary' && input.data.data) {
- result.type = 'base64';
- result.data = input.data.data;
- return result;
- }
- if (input.data.collection && input.data.id) {
- result.type = 'storage';
- result.data = input.data;
- return result;
- }
- }
- }
- return result;
- }
- function prepareImageFile(imageInput, timeout) {
- var tempPath = null;
- if (imageInput.type === 'filePath') {
- return { path: imageInput.path, tempPath: null };
- }
- if (imageInput.type === 'base64') {
- var ext = detectImageFormat(imageInput.data) || 'img';
- tempPath = generateTempPath(ext);
- var writeResult = smartbotic.fs.writeFile(tempPath, imageInput.data, 'base64');
- if (!writeResult.success) {
- throw new Error('Failed to write temp file: ' + (writeResult.error || 'Unknown error'));
- }
- return { path: tempPath, tempPath: tempPath };
- }
- if (imageInput.type === 'url') {
- smartbotic.log.info('Downloading image from URL: ' + imageInput.data);
- var response = smartbotic.http.request({
- method: 'GET',
- url: imageInput.data,
- timeout: timeout
- });
- if (response.status < 200 || response.status >= 300) {
- throw new Error('Failed to download image: HTTP ' + response.status);
- }
- var contentType = response.headers['content-type'] || '';
- var ext = 'img';
- if (contentType.includes('jpeg') || contentType.includes('jpg')) ext = 'jpg';
- else if (contentType.includes('png')) ext = 'png';
- else if (contentType.includes('gif')) ext = 'gif';
- else if (contentType.includes('webp')) ext = 'webp';
- tempPath = generateTempPath(ext);
- var base64Data = smartbotic.utils.base64Encode(response.data);
- var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
- if (!writeResult.success) {
- throw new Error('Failed to write downloaded image: ' + (writeResult.error || 'Unknown error'));
- }
- return { path: tempPath, tempPath: tempPath };
- }
- if (imageInput.type === 'storage') {
- var storageResult = smartbotic.storage.get(imageInput.data.collection, imageInput.data.id);
- if (!storageResult.found) {
- throw new Error('Image not found in storage: ' + imageInput.data.collection + '/' + imageInput.data.id);
- }
- var doc = storageResult.document;
- var base64Data = doc.data || doc.content || doc.base64;
- if (!base64Data) {
- throw new Error('Storage document does not contain image data');
- }
- var ext = detectImageFormat(base64Data) || 'img';
- tempPath = generateTempPath(ext);
- var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
- if (!writeResult.success) {
- throw new Error('Failed to write storage image: ' + (writeResult.error || 'Unknown error'));
- }
- return { path: tempPath, tempPath: tempPath };
- }
- throw new Error('No valid image input found');
- }
- function cleanupTempFile(tempPath) {
- if (tempPath) {
- try {
- smartbotic.fs.unlink(tempPath);
- } catch (e) {
- smartbotic.log.warn('Failed to cleanup temp file: ' + tempPath);
- }
- }
- }
- function parseImageMagickInfo(output) {
- var info = {};
- var lines = output.split('\n');
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i].trim();
- if (!line) continue;
- var colonIdx = line.indexOf(':');
- if (colonIdx > 0) {
- var key = line.substring(0, colonIdx).trim().toLowerCase();
- var value = line.substring(colonIdx + 1).trim();
- if (key === 'image' || key === 'format') {
- var formatMatch = value.match(/^(\w+)/);
- if (formatMatch) info.format = formatMatch[1].toUpperCase();
- }
- else if (key === 'geometry' || key === 'page geometry') {
- var geomMatch = value.match(/(\d+)x(\d+)/);
- if (geomMatch) {
- info.width = parseInt(geomMatch[1], 10);
- info.height = parseInt(geomMatch[2], 10);
- }
- }
- else if (key === 'colorspace') {
- info.colorSpace = value;
- }
- else if (key === 'depth') {
- var depthMatch = value.match(/(\d+)/);
- if (depthMatch) info.depth = parseInt(depthMatch[1], 10);
- }
- else if (key === 'channel depth' || key === 'channels') {
- if (value.toLowerCase().includes('alpha')) {
- info.hasAlpha = true;
- }
- }
- else if (key === 'alpha') {
- info.hasAlpha = value.toLowerCase() !== 'undefined' && value.toLowerCase() !== 'off';
- }
- else if (key === 'compression') {
- info.compression = value;
- }
- else if (key === 'resolution' || key === 'units') {
- if (!info.dpi) info.dpi = {};
- var resMatch = value.match(/([\d.]+)x([\d.]+)/);
- if (resMatch) {
- info.dpi.x = parseFloat(resMatch[1]);
- info.dpi.y = parseFloat(resMatch[2]);
- }
- if (value.includes('PixelsPerInch')) info.dpi.unit = 'dpi';
- else if (value.includes('PixelsPerCentimeter')) info.dpi.unit = 'dpcm';
- }
- else if (key === 'filesize') {
- var sizeMatch = value.match(/([\d.]+)\s*(\w+)/);
- if (sizeMatch) {
- var size = parseFloat(sizeMatch[1]);
- var unit = sizeMatch[2].toUpperCase();
- if (unit === 'B') info.fileSize = Math.round(size);
- else if (unit === 'KB' || unit === 'KIB') info.fileSize = Math.round(size * 1024);
- else if (unit === 'MB' || unit === 'MIB') info.fileSize = Math.round(size * 1024 * 1024);
- else if (unit === 'GB' || unit === 'GIB') info.fileSize = Math.round(size * 1024 * 1024 * 1024);
- }
- }
- }
- }
- if (info.hasAlpha === undefined) info.hasAlpha = false;
- return info;
- }
- function parseExifToolOutput(output) {
- var exif = {
- camera: {},
- datetime: {},
- gps: {},
- exposure: {},
- lens: {}
- };
- var lines = output.split('\n');
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i].trim();
- if (!line) continue;
- var colonIdx = line.indexOf(':');
- if (colonIdx <= 0) continue;
- var key = line.substring(0, colonIdx).trim().toLowerCase().replace(/\s+/g, '');
- var value = line.substring(colonIdx + 1).trim();
- if (!value || value === '-' || value === 'n/a') continue;
- if (key === 'make' || key === 'cameramake') exif.camera.make = value;
- else if (key === 'model' || key === 'cameramodel' || key === 'cameramodelname') exif.camera.model = value;
- else if (key === 'software') exif.camera.software = value;
- else if (key === 'datetimeoriginal' || key === 'createdate') exif.datetime.original = value;
- else if (key === 'datetimedigitized' || key === 'digitizeddate') exif.datetime.digitized = value;
- else if (key === 'modifydate' || key === 'datetime') exif.datetime.modified = value;
- else if (key === 'gpslatitude') {
- var latMatch = value.match(/([\d.]+)/);
- if (latMatch) {
- exif.gps.latitude = parseFloat(latMatch[1]);
- if (value.includes('S')) exif.gps.latitude = -exif.gps.latitude;
- exif.gps.latitudeRef = value.includes('S') ? 'S' : 'N';
- }
- }
- else if (key === 'gpslongitude') {
- var lonMatch = value.match(/([\d.]+)/);
- if (lonMatch) {
- exif.gps.longitude = parseFloat(lonMatch[1]);
- if (value.includes('W')) exif.gps.longitude = -exif.gps.longitude;
- exif.gps.longitudeRef = value.includes('W') ? 'W' : 'E';
- }
- }
- else if (key === 'gpsaltitude') {
- var altMatch = value.match(/([\d.]+)/);
- if (altMatch) exif.gps.altitude = parseFloat(altMatch[1]);
- }
- else if (key === 'exposuretime' || key === 'shutterspeed') exif.exposure.time = value;
- else if (key === 'fnumber' || key === 'aperture') {
- var fMatch = value.match(/([\d.]+)/);
- if (fMatch) exif.exposure.fNumber = parseFloat(fMatch[1]);
- }
- else if (key === 'iso' || key === 'isospeedratings') {
- var isoMatch = value.match(/(\d+)/);
- if (isoMatch) exif.exposure.iso = parseInt(isoMatch[1], 10);
- }
- else if (key === 'exposureprogram') exif.exposure.program = value;
- else if (key === 'exposurecompensation' || key === 'exposurebias') exif.exposure.bias = value;
- else if (key === 'focallength') exif.lens.focalLength = value;
- else if (key === 'focallengthin35mmformat' || key === 'focallength35efl') {
- var fl35Match = value.match(/(\d+)/);
- if (fl35Match) exif.lens.focalLength35mm = parseInt(fl35Match[1], 10);
- }
- else if (key === 'maxaperturevalue') {
- var apMatch = value.match(/([\d.]+)/);
- if (apMatch) exif.lens.aperture = parseFloat(apMatch[1]);
- }
- else if (key === 'lensmake') exif.lens.make = value;
- else if (key === 'lensmodel' || key === 'lens') exif.lens.model = value;
- else if (key === 'orientation') {
- var oriMatch = value.match(/(\d)/);
- if (oriMatch) exif.orientation = parseInt(oriMatch[1], 10);
- }
- else if (key === 'flash') exif.flash = value;
- else if (key === 'whitebalance') exif.whiteBalance = value;
- else if (key === 'meteringmode') exif.meteringMode = value;
- }
- var hasData = false;
- for (var section in exif) {
- if (typeof exif[section] === 'object') {
- for (var field in exif[section]) {
- if (exif[section][field] !== undefined) {
- hasData = true;
- break;
- }
- }
- } else if (exif[section] !== undefined) {
- hasData = true;
- }
- if (hasData) break;
- }
- return hasData ? exif : null;
- }
- function executeInfoOperation(imagePath, includeExif, timeout) {
- smartbotic.log.info('Running ImageMagick identify on: ' + imagePath);
- var identifyCmd = 'identify -verbose "' + imagePath.replace(/"/g, '\\"') + '"';
- var identifyResult = smartbotic.process.exec(identifyCmd, { timeout: timeout });
- if (!identifyResult.success) {
- throw new Error('ImageMagick identify failed: ' + (identifyResult.stderr || 'Unknown error'));
- }
- var info = parseImageMagickInfo(identifyResult.stdout);
- var stat = smartbotic.fs.stat(imagePath);
- if (stat.success && !info.fileSize) {
- info.fileSize = stat.size;
- }
- if (includeExif) {
- smartbotic.log.info('Extracting EXIF metadata');
- var exiftoolCmd = 'exiftool "' + imagePath.replace(/"/g, '\\"') + '"';
- var exifResult = smartbotic.process.exec(exiftoolCmd, { timeout: timeout });
- if (exifResult.success && exifResult.stdout) {
- var exifData = parseExifToolOutput(exifResult.stdout);
- if (exifData) {
- info.exif = exifData;
- }
- } else {
- smartbotic.log.debug('No EXIF data available or exiftool not installed');
- }
- }
- return info;
- }
- async function execute(config, input, context) {
- var operation = config.operation || 'info';
- var timeout = config.timeout || 30000;
- if (operation !== 'info') {
- throw new Error('Operation "' + operation + '" is not yet implemented. Only "info" is available in this version.');
- }
- var imageInput = resolveImageInput(config, input);
- if (!imageInput.type) {
- throw new Error('No valid image input found. Provide base64 data, file path, URL, or storage reference.');
- }
- smartbotic.log.info('Image input source: ' + imageInput.type);
- var fileInfo = null;
- try {
- fileInfo = prepareImageFile(imageInput, timeout);
- smartbotic.log.info('Processing image: ' + fileInfo.path);
- var result = executeInfoOperation(fileInfo.path, config.includeExif !== false, timeout);
- result.sourceType = imageInput.type;
- result.sourcePath = fileInfo.path;
- return result;
- } finally {
- if (fileInfo && fileInfo.tempPath) {
- cleanupTempFile(fileInfo.tempPath);
- }
- }
- }
- module.exports = { configSchema, inputSchema, outputSchema, execute };
|