| |
| |
| |
| |
| |
| |
| |
|
|
| const fs = require('fs'); |
| const path = require('path'); |
| const { exec } = require('child_process'); |
|
|
| |
| const NodeStrategy = require('../strategies/NodeStrategy'); |
| const PythonStrategy = require('../strategies/PythonStrategy'); |
| const JavaStrategy = require('../strategies/JavaStrategy'); |
| const ApiStrategy = require('../strategies/ApiStrategy'); |
| const ButtonGenerator = require('./button-generator'); |
|
|
| class SystemDetector { |
| constructor() { |
| |
| this.strategies = { |
| node: new NodeStrategy(), |
| python: new PythonStrategy(), |
| java: new JavaStrategy(), |
| api: new ApiStrategy(), |
| |
| |
| executable_project: new NodeStrategy(), |
| batch_project: new NodeStrategy() |
| }; |
| |
| this.detectionRules = this.initializeDetectionRules(); |
| |
| |
| this.buttonGenerator = new ButtonGenerator(); |
| this.projectsWithButtons = new Map(); |
| |
| console.log(' SystemDetector initialized with Smart Button System'); |
| } |
|
|
| |
| |
| |
| initializeDetectionRules() { |
| return { |
| node: { |
| files: ['package.json', 'node_modules/', 'yarn.lock', 'package-lock.json'], |
| extensions: ['.js', '.ts', '.json'], |
| commands: ['node', 'npm', 'yarn'], |
| priority: 10 |
| }, |
| python: { |
| files: ['requirements.txt', 'setup.py', 'pyproject.toml', 'Pipfile', 'main.py', 'app.py'], |
| extensions: ['.py', '.pyx', '.ipynb'], |
| commands: ['python', 'python3', 'pip', 'pip3'], |
| priority: 9 |
| }, |
| java: { |
| files: ['pom.xml', 'build.gradle', 'gradlew', 'build.xml'], |
| extensions: ['.java', '.class', '.jar'], |
| commands: ['java', 'javac', 'mvn', 'gradle'], |
| priority: 8 |
| }, |
| |
| executable_project: { |
| files: [], |
| extensions: ['.exe'], |
| commands: [], |
| priority: 12 |
| }, |
| |
| batch_project: { |
| files: [], |
| extensions: ['.bat', '.cmd'], |
| commands: [], |
| priority: 11 |
| }, |
| api: { |
| |
| files: [], |
| extensions: [], |
| commands: [], |
| priority: 5, |
| special: 'url-based' |
| } |
| }; |
| } |
|
|
| |
| |
| |
| |
| async detect(projectPath = process.cwd(), context = {}) { |
| console.log(`[SystemDetector V2] Using Checklist-based detection for: ${path.basename(projectPath)}`); |
| try { |
| |
| if (context.command && this.isUrl(context.command)) { |
| console.log(' URL detected, using API strategy'); |
| return { |
| type: 'api', |
| strategy: this.strategies.api, |
| confidence: 100, |
| reason: 'URL detected in command' |
| }; |
| } |
| |
| |
| if (context.forceType && this.strategies[context.forceType]) { |
| console.log(` Forced type detected: ${context.forceType}`); |
| return { |
| type: context.forceType, |
| strategy: this.strategies[context.forceType], |
| confidence: 100, |
| reason: 'Force type specified in context' |
| }; |
| } |
|
|
| if (!fs.existsSync(projectPath)) { |
| throw new Error(`Project path not found: ${projectPath}`); |
| } |
|
|
| const files = fs.readdirSync(projectPath).map(f => f.toLowerCase()); |
| let detectedType = 'unknown'; |
|
|
| |
|
|
| |
| if (files.some(f => f.endsWith('.bat') || f.endsWith('.cmd'))) { |
| detectedType = 'batch_project'; |
| console.log(` -> Priority 1: Found .bat/.cmd file. Type set to [${detectedType}]`); |
| |
| |
| } else if (files.some(f => f.endsWith('.exe'))) { |
| detectedType = 'executable_project'; |
| console.log(` -> Priority 2: Found .exe file. Type set to [${detectedType}]`); |
| |
| |
| } else if (files.includes('package.json')) { |
| detectedType = 'node'; |
| console.log(` -> Priority 3: Found package.json. Type set to [${detectedType}]`); |
| |
| |
| } else if (files.includes('requirements.txt') || files.includes('main.py') || files.includes('app.py')) { |
| detectedType = 'python'; |
| console.log(` -> Priority 4: Found Python indicators. Type set to [${detectedType}]`); |
| |
| |
| } else if (files.includes('pom.xml') || files.includes('build.gradle')) { |
| detectedType = 'java'; |
| console.log(` -> Priority 5: Found Java indicators. Type set to [${detectedType}]`); |
| |
| |
| } else if (files.some(f => f.endsWith('.html'))) { |
| detectedType = 'html'; |
| console.log(` -> Priority 6: Found .html file. Type set to [${detectedType}]`); |
| } |
| |
| |
|
|
| if (detectedType === 'unknown') { |
| console.log(` -> No specific project type detected. Marked as 'unknown'.`); |
| |
| |
| const { app } = require('electron'); |
| if (app.isPackaged) { |
| detectedType = 'executable_project'; |
| console.log(` -> [Fallback] Set to executable_project for production mode`); |
| } |
| } |
|
|
| |
| if (detectedType !== 'unknown') { |
| const detectionResult = { |
| type: detectedType, |
| confidence: 100 |
| }; |
| await this.generateProjectButtons(projectPath, detectionResult); |
| } |
|
|
| return { |
| type: detectedType, |
| confidence: detectedType !== 'unknown' ? 100 : 0, |
| reason: `Checklist-based detection: Priority rule for [${detectedType}] triggered.`, |
| strategy: this.strategies[detectedType] || this.strategies.node |
| }; |
|
|
| } catch (error) { |
| console.error(` Detection failed for ${projectPath}: ${error.message}`); |
| return { |
| type: 'unknown', |
| confidence: 0, |
| error: error.message, |
| strategy: this.strategies.node |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async runDetectionTests(projectPath) { |
| const results = {}; |
| |
| for (const [strategyName, rules] of Object.entries(this.detectionRules)) { |
| if (rules.special === 'url-based') { |
| |
| continue; |
| } |
| |
| console.log(` Testing ${strategyName} detection...`); |
| |
| const score = await this.calculateDetectionScore(projectPath, rules, strategyName); |
| |
| results[strategyName] = { |
| type: strategyName, |
| strategy: this.strategies[strategyName], |
| score: score, |
| confidence: Math.min(score * 10, 100), |
| rules: rules |
| }; |
| |
| console.log(` ${strategyName} detection score: ${score}/10 (${results[strategyName].confidence}%)`); |
| } |
| |
| return results; |
| } |
|
|
| |
| |
| |
| async calculateDetectionScore(projectPath, rules, strategyName) { |
| let score = 0; |
| const maxScore = 10; |
| |
| |
| const fileScore = this.checkFiles(projectPath, rules.files); |
| score += fileScore * 0.4; |
| |
| |
| const extensionScore = this.checkExtensions(projectPath, rules.extensions); |
| score += extensionScore * 0.3; |
| |
| |
| const commandScore = await this.checkCommands(rules.commands); |
| score += commandScore * 0.3; |
| |
| return Math.round(score * 10) / 10; |
| } |
|
|
| |
| |
| |
| checkFiles(projectPath, requiredFiles) { |
| if (!requiredFiles.length) return 0; |
| |
| let foundCount = 0; |
| |
| for (const file of requiredFiles) { |
| const filePath = path.join(projectPath, file); |
| if (fs.existsSync(filePath)) { |
| foundCount++; |
| console.log(` Found indicator file: ${file}`); |
| } |
| } |
| |
| return foundCount / requiredFiles.length * 10; |
| } |
|
|
| |
| |
| |
| checkExtensions(projectPath, extensions) { |
| if (!extensions.length) return 0; |
| |
| const files = this.getFilesRecursive(projectPath, 2); |
| let foundCount = 0; |
| |
| for (const ext of extensions) { |
| const hasExtension = files.some(file => file.endsWith(ext)); |
| if (hasExtension) { |
| foundCount++; |
| console.log(` Found files with extension: ${ext}`); |
| } |
| } |
| |
| return foundCount / extensions.length * 10; |
| } |
|
|
| |
| |
| |
| async checkCommands(commands) { |
| if (!commands.length) return 0; |
| |
| let availableCount = 0; |
| |
| for (const command of commands) { |
| const isAvailable = await this.isCommandAvailable(command); |
| if (isAvailable) { |
| availableCount++; |
| console.log(` Command available: ${command}`); |
| } |
| } |
| |
| return availableCount / commands.length * 10; |
| } |
|
|
| |
| |
| |
| async isCommandAvailable(command) { |
| return new Promise((resolve) => { |
| const testCommand = process.platform === 'win32' ? `where ${command}` : `which ${command}`; |
| |
| exec(testCommand, (error, stdout, stderr) => { |
| resolve(!error && stdout.trim().length > 0); |
| }); |
| }); |
| } |
|
|
| |
| |
| |
| selectBestStrategy(detectionResults) { |
| const strategies = Object.values(detectionResults); |
| |
| |
| strategies.sort((a, b) => { |
| if (a.confidence !== b.confidence) { |
| return b.confidence - a.confidence; |
| } |
| return b.rules.priority - a.rules.priority; |
| }); |
| |
| const bestStrategy = strategies[0]; |
| |
| return { |
| type: bestStrategy.type, |
| strategy: bestStrategy.strategy, |
| confidence: bestStrategy.confidence, |
| reason: `Best match based on detection tests`, |
| allResults: detectionResults |
| }; |
| } |
|
|
| |
| |
| |
| isUrl(str) { |
| try { |
| new URL(str); |
| return str.startsWith('http://') || str.startsWith('https://'); |
| } catch { |
| return false; |
| } |
| } |
|
|
| |
| |
| |
| getFilesRecursive(dirPath, maxDepth = 2) { |
| const files = []; |
| |
| const scanDir = (currentPath, depth) => { |
| if (depth > maxDepth) return; |
| |
| try { |
| const items = fs.readdirSync(currentPath); |
| |
| for (const item of items) { |
| const fullPath = path.join(currentPath, item); |
| const stat = fs.lstatSync(fullPath); |
| |
| if (stat.isFile()) { |
| files.push(fullPath); |
| } else if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') { |
| scanDir(fullPath, depth + 1); |
| } |
| } |
| } catch (error) { |
| |
| } |
| }; |
| |
| scanDir(dirPath, 0); |
| return files; |
| } |
|
|
| |
| async generateProjectButtons(projectPath, detectionResult) { |
| try { |
| console.log(` Generating buttons for project at: ${projectPath}`); |
| |
| |
| const features = await this.analyzeProjectFeatures(projectPath, detectionResult); |
| |
| |
| const previewImage = await this.generatePluginPreview(projectPath, detectionResult); |
| |
| |
| const strategy = this.strategies[detectionResult.type]; |
| if (!strategy) { |
| console.warn(` No strategy found for project type "${detectionResult.type}". Skipping button generation.`); |
| |
| const fallbackStrategy = this.strategies.node; |
| if (!fallbackStrategy) return []; |
| } |
| |
| |
| |
| const projectInfo = { |
| name: path.basename(projectPath), |
| path: projectPath, |
| type: detectionResult.type, |
| confidence: detectionResult.confidence, |
| strategy: strategy ? strategy.constructor.name : 'Unknown', |
| previewImage: previewImage |
| }; |
| |
| |
| const buttons = this.buttonGenerator.generateProjectButtons(projectInfo, features); |
| |
| |
| this.projectsWithButtons.set(projectPath, { |
| projectInfo, |
| buttons, |
| generated: new Date().toISOString() |
| }); |
| |
| console.log(` Generated ${buttons.length} buttons for ${projectInfo.name}`); |
| return buttons; |
| |
| } catch (error) { |
| console.warn(` Failed to generate buttons for ${projectPath}:`, error.message); |
| return []; |
| } |
| } |
|
|
| |
| async generatePluginPreview(projectPath, detectionResult) { |
| try { |
| console.log(` Generating preview for plugin: ${path.basename(projectPath)}`); |
| |
| const previewsDir = this.getPreviewsDirectory(); |
| const pluginName = path.basename(projectPath); |
| const previewFileName = `${pluginName}_preview.png`; |
| const previewPath = path.join(previewsDir, previewFileName); |
| |
| |
| if (fs.existsSync(previewPath)) { |
| console.log(` Preview already exists: ${previewFileName}`); |
| return `file://${previewPath.replace(/\\/g, '/')}`; |
| } |
| |
| |
| const success = await this.createPreviewImage(projectPath, detectionResult, previewPath); |
| |
| if (success) { |
| console.log(` Preview created: ${previewFileName}`); |
| return `file://${previewPath.replace(/\\/g, '/')}`; |
| } else { |
| console.warn(` Failed to create preview for ${pluginName}`); |
| return this.getDefaultPreviewImage(detectionResult.type); |
| } |
| |
| } catch (error) { |
| console.error(` Error generating preview: ${error.message}`); |
| return this.getDefaultPreviewImage(detectionResult.type); |
| } |
| } |
|
|
| |
| getPreviewsDirectory() { |
| const { app } = require('electron'); |
| let previewsDir; |
| |
| if (app.isPackaged) { |
| previewsDir = path.join(path.dirname(app.getPath('exe')), 'previews'); |
| } else { |
| previewsDir = path.join(process.cwd(), 'previews'); |
| } |
| |
| |
| if (!fs.existsSync(previewsDir)) { |
| fs.mkdirSync(previewsDir, { recursive: true }); |
| console.log(` Created previews directory: ${previewsDir}`); |
| } |
| |
| return previewsDir; |
| } |
|
|
| |
| async createPreviewImage(projectPath, detectionResult, outputPath) { |
| try { |
| const { type } = detectionResult; |
| |
| switch (type) { |
| case 'executable_project': |
| return await this.createExecutablePreview(projectPath, outputPath); |
| case 'batch_project': |
| return await this.createBatchPreview(projectPath, outputPath); |
| case 'node': |
| return await this.createNodePreview(projectPath, outputPath); |
| case 'python': |
| return await this.createPythonPreview(projectPath, outputPath); |
| case 'html': |
| return await this.createWebPreview(projectPath, outputPath); |
| default: |
| return await this.createGenericPreview(projectPath, outputPath, type); |
| } |
| } catch (error) { |
| console.error(` Error creating preview image: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createExecutablePreview(projectPath, outputPath) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#4A5568'); |
| gradient.addColorStop(1, '#2D3748'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#E2E8F0'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#CBD5E0'; |
| ctx.fillText('Executable Application', 200, 210); |
| |
| |
| ctx.fillStyle = '#4FD1C7'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText('EXE', 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating executable preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createBatchPreview(projectPath, outputPath) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#38A169'); |
| gradient.addColorStop(1, '#2F855A'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#F0FFF4'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#C6F6D5'; |
| ctx.fillText('Batch Script', 200, 210); |
| |
| |
| ctx.fillStyle = '#68D391'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText('BAT', 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating batch preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createNodePreview(projectPath, outputPath) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#68D391'); |
| gradient.addColorStop(1, '#48BB78'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#F0FFF4'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#C6F6D5'; |
| ctx.fillText('Node.js Project', 200, 210); |
| |
| |
| ctx.fillStyle = '#9AE6B4'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText('NODE', 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating node preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createPythonPreview(projectPath, outputPath) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#4FD1C7'); |
| gradient.addColorStop(1, '#38B2AC'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#E6FFFA'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#B2F5EA'; |
| ctx.fillText('Python Project', 200, 210); |
| |
| |
| ctx.fillStyle = '#81E6D9'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText('PY', 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating python preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createWebPreview(projectPath, outputPath) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#90CDF4'); |
| gradient.addColorStop(1, '#63B3ED'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#EBF8FF'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#BEE3F8'; |
| ctx.fillText('Web Application', 200, 210); |
| |
| |
| ctx.fillStyle = '#A3BFFA'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText('WEB', 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating web preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| async createGenericPreview(projectPath, outputPath, type) { |
| try { |
| const canvas = this.createCanvas(400, 300); |
| const ctx = canvas.getContext('2d'); |
| |
| |
| const gradient = ctx.createLinearGradient(0, 0, 400, 300); |
| gradient.addColorStop(0, '#A0AEC0'); |
| gradient.addColorStop(1, '#718096'); |
| ctx.fillStyle = gradient; |
| ctx.fillRect(0, 0, 400, 300); |
| |
| |
| ctx.font = 'bold 60px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| ctx.textAlign = 'center'; |
| ctx.fillText('', 200, 120); |
| |
| |
| ctx.font = 'bold 24px Arial'; |
| ctx.fillStyle = '#F7FAFC'; |
| const pluginName = path.basename(projectPath); |
| ctx.fillText(pluginName, 200, 180); |
| |
| |
| ctx.font = '16px Arial'; |
| ctx.fillStyle = '#E2E8F0'; |
| ctx.fillText(`${type.toUpperCase()} Plugin`, 200, 210); |
| |
| |
| ctx.fillStyle = '#CBD5E0'; |
| ctx.fillRect(150, 230, 100, 25); |
| ctx.fillStyle = '#1A202C'; |
| ctx.font = '12px Arial'; |
| ctx.fillText(type.substring(0, 8).toUpperCase(), 200, 247); |
| |
| return await this.saveCanvas(canvas, outputPath); |
| } catch (error) { |
| console.error(` Error creating generic preview: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| createCanvas(width, height) { |
| try { |
| |
| const { createCanvas } = require('canvas'); |
| return createCanvas(width, height); |
| } catch (error) { |
| |
| console.warn(' node-canvas not available, using fallback'); |
| return this.createMockCanvas(width, height); |
| } |
| } |
|
|
| |
| createMockCanvas(width, height) { |
| return { |
| width, |
| height, |
| getContext: () => ({ |
| fillStyle: '', |
| font: '', |
| textAlign: '', |
| fillRect: () => {}, |
| fillText: () => {}, |
| createLinearGradient: () => ({ |
| addColorStop: () => {} |
| }) |
| }), |
| toBuffer: () => Buffer.from('') |
| }; |
| } |
|
|
| |
| async saveCanvas(canvas, outputPath) { |
| try { |
| const buffer = canvas.toBuffer('image/png'); |
| fs.writeFileSync(outputPath, buffer); |
| return true; |
| } catch (error) { |
| console.error(` Error saving canvas: ${error.message}`); |
| |
| return this.createPlaceholderImage(outputPath); |
| } |
| } |
|
|
| |
| createPlaceholderImage(outputPath) { |
| try { |
| |
| const svgContent = ` |
| <svg width="400" height="300" xmlns="http://www.w3.org/2000/svg"> |
| <rect width="400" height="300" fill="#718096"/> |
| <text x="200" y="150" font-family="Arial" font-size="20" fill="white" text-anchor="middle"> Plugin Preview</text> |
| <text x="200" y="180" font-family="Arial" font-size="14" fill="#E2E8F0" text-anchor="middle">Preview Generation Failed</text> |
| </svg> |
| `; |
| |
| |
| const svgPath = outputPath.replace('.png', '.svg'); |
| fs.writeFileSync(svgPath, svgContent); |
| console.log(` Created SVG placeholder: ${path.basename(svgPath)}`); |
| return true; |
| } catch (error) { |
| console.error(` Error creating placeholder: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| getDefaultPreviewImage(type) { |
| const defaultImages = { |
| 'executable_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM0QTU1NjgiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0UyRThGMCI+8J+agDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5FeGVjdXRhYmxlPC90ZXh0Pgo8L3N2Zz4=', |
| 'batch_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2l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DAiIGZpbGw9IiM3MTgwOTYiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0Y3RkFGQyI+8J+UjDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QbHVnaW48L3RleHQ+Cjwvc3ZnPg==' |
| }; |
| |
| return defaultImages[type] || defaultImages['default']; |
| } |
|
|
| |
| async analyzeProjectFeatures(projectPath, detectionResult) { |
| const features = { |
| hasPackageJson: false, |
| hasNodeModules: false, |
| hasRequirementsTxt: false, |
| hasMainPy: false, |
| hasAppPy: false, |
| hasIndexHtml: false, |
| hasElectron: false, |
| hasTypeScript: false, |
| hasLinter: false, |
| hasTests: false, |
| hasFlask: false, |
| hasDjango: false, |
| hasJupyter: false, |
| hasCSS: false, |
| hasJS: false, |
| hasDocker: false, |
| projectType: detectionResult.type |
| }; |
|
|
| try { |
| const files = fs.readdirSync(projectPath); |
| |
| |
| features.hasPackageJson = files.includes('package.json'); |
| features.hasNodeModules = files.includes('node_modules'); |
| features.hasRequirementsTxt = files.includes('requirements.txt'); |
| features.hasMainPy = files.includes('main.py'); |
| features.hasAppPy = files.includes('app.py'); |
| features.hasIndexHtml = files.includes('index.html'); |
| features.hasDocker = files.includes('Dockerfile') || files.includes('docker-compose.yml'); |
|
|
| |
| if (features.hasPackageJson) { |
| const packagePath = path.join(projectPath, 'package.json'); |
| try { |
| const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8')); |
| const allDeps = { ...packageData.dependencies, ...packageData.devDependencies }; |
| |
| features.hasElectron = 'electron' in allDeps; |
| features.hasTypeScript = 'typescript' in allDeps || files.some(f => f.endsWith('.ts')); |
| features.hasLinter = 'eslint' in allDeps || 'tslint' in allDeps; |
| features.hasTests = 'jest' in allDeps || 'mocha' in allDeps || 'jasmine' in allDeps; |
| } catch (error) { |
| console.warn('Could not parse package.json:', error.message); |
| } |
| } |
|
|
| |
| if (features.hasRequirementsTxt) { |
| const requirementsPath = path.join(projectPath, 'requirements.txt'); |
| try { |
| const requirements = fs.readFileSync(requirementsPath, 'utf8'); |
| features.hasFlask = requirements.includes('Flask'); |
| features.hasDjango = requirements.includes('Django'); |
| features.hasJupyter = requirements.includes('jupyter') || requirements.includes('notebook'); |
| } catch (error) { |
| console.warn('Could not parse requirements.txt:', error.message); |
| } |
| } |
|
|
| |
| const webFiles = files.filter(f => f.endsWith('.css') || f.endsWith('.js') || f.endsWith('.html')); |
| features.hasCSS = webFiles.some(f => f.endsWith('.css')); |
| features.hasJS = webFiles.some(f => f.endsWith('.js')); |
|
|
| } catch (error) { |
| console.warn(` Error analyzing features for ${projectPath}:`, error.message); |
| } |
|
|
| return features; |
| } |
|
|
| |
| getProjectsWithButtons() { |
| return Array.from(this.projectsWithButtons.values()); |
| } |
|
|
| |
| getProjectButtons(projectPath) { |
| const projectData = this.projectsWithButtons.get(projectPath); |
| return projectData ? projectData.buttons : []; |
| } |
|
|
| |
| generateProjectsUI() { |
| const projects = this.getProjectsWithButtons(); |
| const uiInterface = { |
| sections: [], |
| totalProjects: projects.length, |
| totalButtons: 0, |
| lastUpdated: new Date().toISOString() |
| }; |
|
|
| for (const projectData of projects) { |
| const { projectInfo, buttons, features } = projectData; |
| |
| const section = { |
| projectName: projectInfo.name, |
| projectType: projectInfo.type, |
| projectPath: projectInfo.path, |
| confidence: projectInfo.confidence, |
| buttons: buttons, |
| features: features, |
| buttonCount: buttons.length |
| }; |
| |
| uiInterface.sections.push(section); |
| uiInterface.totalButtons += buttons.length; |
| } |
|
|
| return uiInterface; |
| } |
|
|
| |
| |
| |
| |
| async scanProjects() { |
| console.log('[SystemDetector] ==========================================='); |
| console.log('[SystemDetector] Starting a full project scan...'); |
| this.projectsWithButtons.clear(); |
|
|
| const { app } = require('electron'); |
| const isPackaged = app.isPackaged; |
|
|
| |
| let pluginsPath; |
| if (isPackaged) { |
| |
| pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| |
| |
| const basePath = app.getAppPath(); |
| pluginsPath = path.join(basePath, 'plugins'); |
| } |
|
|
| const scanLocations = [ |
| pluginsPath |
| ]; |
|
|
| for (const location of scanLocations) { |
| console.log(`[SystemDetector] Scanning location: ${location}`); |
| if (fs.existsSync(location)) { |
| await this.scanDirectoryRecursive(location, 0, 3); |
| } else { |
| console.warn(`[SystemDetector] -> Location not found, skipping.`); |
| } |
| } |
| |
| console.log(`[SystemDetector] Scan complete. Found ${this.projectsWithButtons.size} actionable projects.`); |
| console.log('[SystemDetector] ==========================================='); |
| |
| const uiData = this.generateProjectsUI(); |
| return { |
| success: true, |
| projects: uiData.sections, |
| count: uiData.totalProjects |
| }; |
| } |
|
|
| |
| |
| |
| async scanDirectoryRecursive(dirPath, currentDepth = 0, maxDepth = 3) { |
| |
| if (currentDepth > maxDepth) { |
| return; |
| } |
|
|
| try { |
| const items = fs.readdirSync(dirPath, { withFileTypes: true }); |
|
|
| for (const item of items) { |
| const fullPath = path.join(dirPath, item.name); |
| |
| |
| if (item.name === 'node_modules' || |
| item.name.startsWith('.') || |
| item.name === 'vendor' || |
| item.name === 'logs' || |
| item.name === 'cache') { |
| continue; |
| } |
|
|
| if (item.isDirectory()) { |
| |
| const detectionResult = await this.detect(fullPath); |
| if (detectionResult.confidence > 30) { |
| console.log(`[SystemDetector] -> Project detected: ${item.name} (Type: ${detectionResult.type}, Confidence: ${detectionResult.confidence}%)`); |
| await this.generateProjectButtons(fullPath, detectionResult); |
| } else { |
| |
| await this.scanDirectoryRecursive(fullPath, currentDepth + 1, maxDepth); |
| } |
| } |
| } |
| } catch (error) { |
| console.warn(`[SystemDetector] Error scanning directory ${dirPath}:`, error.message); |
| } |
| } |
|
|
| |
| async refreshProjectScans() { |
| console.log(' Refreshing project scans and button generation...'); |
| |
| this.projectsWithButtons.clear(); |
| this.buttonGenerator.reset(); |
| |
| const { app } = require('electron'); |
| const isPackaged = app.isPackaged; |
|
|
| |
| let pluginsPath; |
| if (isPackaged) { |
| |
| pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| |
| const basePath = app.getAppPath(); |
| pluginsPath = path.join(basePath, 'plugins'); |
| } |
| |
| |
| const projectDirs = [ |
| pluginsPath, |
| path.join(pluginsPath, 'Chahuadev_Studio_V.10.0.0'), |
| path.join(pluginsPath, 'Chahuadev_Engine_ระบบต้นแบบ') |
| ]; |
|
|
| for (const dir of projectDirs) { |
| if (fs.existsSync(dir)) { |
| await this.scanProjectDirectory(dir); |
| } |
| } |
|
|
| console.log(` Refresh complete! Found ${this.projectsWithButtons.size} projects with buttons`); |
| return this.generateProjectsUI(); |
| } |
|
|
| |
| async scanProjectDirectory(dirPath) { |
| try { |
| if (fs.statSync(dirPath).isFile()) { |
| return; |
| } |
|
|
| const items = fs.readdirSync(dirPath, { withFileTypes: true }); |
| |
| for (const item of items) { |
| if (item.isDirectory()) { |
| const fullPath = path.join(dirPath, item.name); |
| |
| |
| const detectionResult = await this.detect(fullPath); |
| |
| if (detectionResult.confidence > 30) { |
| await this.generateProjectButtons(fullPath, detectionResult); |
| } |
| } |
| } |
| } catch (error) { |
| console.warn(` Error scanning directory ${dirPath}:`, error.message); |
| } |
| } |
|
|
| |
| |
| |
| async getStatus() { |
| const strategiesStatus = {}; |
| |
| for (const [name, strategy] of Object.entries(this.strategies)) { |
| strategiesStatus[name] = await strategy.getStatus(); |
| } |
| |
| return { |
| detector: 'SystemDetector', |
| status: 'READY', |
| supportedStrategies: Object.keys(this.strategies), |
| detectionRules: this.detectionRules, |
| projectsWithButtons: this.projectsWithButtons.size, |
| totalButtons: this.buttonGenerator.getAllButtons().length, |
| strategies: strategiesStatus, |
| timestamp: Date.now() |
| }; |
| } |
| } |
|
|
| module.exports = SystemDetector; |