chahuadev-framework-en / modules /system-detector.js
chahuadev
Update README
857cdcf
/**
* system-detector.js - Auto System Detection (Level 4)
* สำหรับ Chahuadev Framework
*
* ใช้: BaseStrategy และ concrete strategies จาก Level 3
* ตรวจสอบ: Project type, runtime environment, available tools
*/
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
// Import strategies จาก Level 3
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() {
// สร้าง strategy instances
this.strategies = {
node: new NodeStrategy(),
python: new PythonStrategy(),
java: new JavaStrategy(),
api: new ApiStrategy(),
// เพิ่ม strategies สำหรับ executable และ batch projects
// ใช้ NodeStrategy เพราะสามารถรันคำสั่งทั่วไปได้
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');
}
/**
* กำหนด detection rules สำหรับแต่ละ project type
*/
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
},
// เพิ่มประเภทใหม่สำหรับโปรเจกต์ .exe
executable_project: {
files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ
extensions: ['.exe'], // แค่มองหานามสกุล .exe ก็พอ
commands: [],
priority: 12 // ให้ความสำคัญสูงสุด เพราะชัดเจนที่สุด
},
// เพิ่มประเภทใหม่สำหรับโปรเจกต์ .bat
batch_project: {
files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ
extensions: ['.bat', '.cmd'], // หานามสกุล .bat และ .cmd
commands: [],
priority: 11 // ให้ความสำคัญรองจาก .exe
},
api: {
// API strategy ไม่ต้องมี files เพราะใช้ URL
files: [],
extensions: [],
commands: [],
priority: 5,
special: 'url-based' // ตรวจสอบจาก URL pattern
}
};
}
/**
* SystemDetector V2: Checklist-based Detection
* ตรวจสอบ project type ตามลำดับความสำคัญอย่างชัดเจน
*/
async detect(projectPath = process.cwd(), context = {}) {
console.log(`[SystemDetector V2] Using Checklist-based detection for: ${path.basename(projectPath)}`);
try {
// ถ้า context มี URL ให้ใช้ API strategy
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'
};
}
// ถ้า context ระบุ type มาแล้ว
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';
// --- ระบบ Checklist ตามลำดับความสำคัญ ---
// Priority 1: Batch Project (ชัดเจนที่สุด)
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}]`);
// Priority 2: Executable Project
} else if (files.some(f => f.endsWith('.exe'))) {
detectedType = 'executable_project';
console.log(` -> Priority 2: Found .exe file. Type set to [${detectedType}]`);
// Priority 3: Node.js Project
} else if (files.includes('package.json')) {
detectedType = 'node';
console.log(` -> Priority 3: Found package.json. Type set to [${detectedType}]`);
// Priority 4: Python Project
} 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}]`);
// Priority 5: Java Project
} else if (files.includes('pom.xml') || files.includes('build.gradle')) {
detectedType = 'java';
console.log(` -> Priority 5: Found Java indicators. Type set to [${detectedType}]`);
// Priority 6: Basic HTML Project
} else if (files.some(f => f.endsWith('.html'))) {
detectedType = 'html';
console.log(` -> Priority 6: Found .html file. Type set to [${detectedType}]`);
}
// --- จบระบบ Checklist ---
if (detectedType === 'unknown') {
console.log(` -> No specific project type detected. Marked as 'unknown'.`);
// เพิ่ม fallback สำหรับ production mode
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, // ถ้าเจอคือมั่นใจ 100%
reason: `Checklist-based detection: Priority rule for [${detectedType}] triggered.`,
strategy: this.strategies[detectedType] || this.strategies.node // Fallback to node strategy
};
} catch (error) {
console.error(` Detection failed for ${projectPath}: ${error.message}`);
return {
type: 'unknown',
confidence: 0,
error: error.message,
strategy: this.strategies.node
};
}
}
/**
* รัน detection tests สำหรับทุก strategy
*/
async runDetectionTests(projectPath) {
const results = {};
for (const [strategyName, rules] of Object.entries(this.detectionRules)) {
if (rules.special === 'url-based') {
// Skip API strategy สำหรับ file-based detection
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), // แปลง score เป็น percentage
rules: rules
};
console.log(` ${strategyName} detection score: ${score}/10 (${results[strategyName].confidence}%)`);
}
return results;
}
/**
* คำนวณ detection score สำหรับ strategy
*/
async calculateDetectionScore(projectPath, rules, strategyName) {
let score = 0;
const maxScore = 10;
// ตรวจสอบ files (40% ของคะแนน)
const fileScore = this.checkFiles(projectPath, rules.files);
score += fileScore * 0.4;
// ตรวจสอบ extensions (30% ของคะแนน)
const extensionScore = this.checkExtensions(projectPath, rules.extensions);
score += extensionScore * 0.3;
// ตรวจสอบ commands (30% ของคะแนน)
const commandScore = await this.checkCommands(rules.commands);
score += commandScore * 0.3;
return Math.round(score * 10) / 10; // ปัดเศษ 1 ตำแหน่ง
}
/**
* ตรวจสอบ files ที่บ่งบอกประเภท project
*/
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;
}
/**
* ตรวจสอบ file extensions
*/
checkExtensions(projectPath, extensions) {
if (!extensions.length) return 0;
const files = this.getFilesRecursive(projectPath, 2); // ค้นหา 2 levels
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;
}
/**
* ตรวจสอบ commands ว่ามีอยู่ในระบบหรือไม่
*/
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;
}
/**
* ตรวจสอบว่า command มีอยู่ในระบบหรือไม่
*/
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);
});
});
}
/**
* เลือก strategy ที่ดีที่สุด
*/
selectBestStrategy(detectionResults) {
const strategies = Object.values(detectionResults);
// เรียงลำดับตาม confidence และ priority
strategies.sort((a, b) => {
if (a.confidence !== b.confidence) {
return b.confidence - a.confidence; // เรียงจากมากไปน้อย
}
return b.rules.priority - a.rules.priority; // เรียงตาม priority
});
const bestStrategy = strategies[0];
return {
type: bestStrategy.type,
strategy: bestStrategy.strategy,
confidence: bestStrategy.confidence,
reason: `Best match based on detection tests`,
allResults: detectionResults
};
}
/**
* ตรวจสอบว่าเป็น URL หรือไม่
*/
isUrl(str) {
try {
new URL(str);
return str.startsWith('http://') || str.startsWith('https://');
} catch {
return false;
}
}
/**
* ค้นหาไฟล์แบบ recursive
*/
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) {
// Ignore permission errors
}
};
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);
// --- จุดแก้ไข: ตรวจสอบและดึง strategy ให้ถูกต้อง ---
const strategy = this.strategies[detectionResult.type];
if (!strategy) {
console.warn(` No strategy found for project type "${detectionResult.type}". Skipping button generation.`);
// ลองใช้ fallback strategy ถ้ามี
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', // ป้องกัน error
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);
}
}
// ดึง directory สำหรับเก็บภาพตัวอย่าง
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;
}
}
// สร้างภาพตัวอย่างสำหรับ Executable
async createExecutablePreview(projectPath, outputPath) {
try {
const canvas = this.createCanvas(400, 300);
const ctx = canvas.getContext('2d');
// Background gradient
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#E2E8F0';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#CBD5E0';
ctx.fillText('Executable Application', 200, 210);
// Type badge
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;
}
}
// สร้างภาพตัวอย่างสำหรับ Batch
async createBatchPreview(projectPath, outputPath) {
try {
const canvas = this.createCanvas(400, 300);
const ctx = canvas.getContext('2d');
// Background
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#F0FFF4';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#C6F6D5';
ctx.fillText('Batch Script', 200, 210);
// Type badge
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;
}
}
// สร้างภาพตัวอย่างสำหรับ Node.js
async createNodePreview(projectPath, outputPath) {
try {
const canvas = this.createCanvas(400, 300);
const ctx = canvas.getContext('2d');
// Background
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#F0FFF4';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#C6F6D5';
ctx.fillText('Node.js Project', 200, 210);
// Type badge
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;
}
}
// สร้างภาพตัวอย่างสำหรับ Python
async createPythonPreview(projectPath, outputPath) {
try {
const canvas = this.createCanvas(400, 300);
const ctx = canvas.getContext('2d');
// Background
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#E6FFFA';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#B2F5EA';
ctx.fillText('Python Project', 200, 210);
// Type badge
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;
}
}
// สร้างภาพตัวอย่างสำหรับ Web/HTML
async createWebPreview(projectPath, outputPath) {
try {
const canvas = this.createCanvas(400, 300);
const ctx = canvas.getContext('2d');
// Background
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#EBF8FF';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#BEE3F8';
ctx.fillText('Web Application', 200, 210);
// Type badge
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');
// Background
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);
// Icon
ctx.font = 'bold 60px Arial';
ctx.fillStyle = '#F7FAFC';
ctx.textAlign = 'center';
ctx.fillText('', 200, 120);
// Title
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#F7FAFC';
const pluginName = path.basename(projectPath);
ctx.fillText(pluginName, 200, 180);
// Subtitle
ctx.font = '16px Arial';
ctx.fillStyle = '#E2E8F0';
ctx.fillText(`${type.toUpperCase()} Plugin`, 200, 210);
// Type badge
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;
}
}
// สร้าง Canvas (ใช้ node-canvas หรือ fallback)
createCanvas(width, height) {
try {
// ลองใช้ node-canvas ก่อน
const { createCanvas } = require('canvas');
return createCanvas(width, height);
} catch (error) {
// Fallback: สร้าง mock canvas สำหรับ testing
console.warn(' node-canvas not available, using fallback');
return this.createMockCanvas(width, height);
}
}
// Mock Canvas สำหรับ fallback
createMockCanvas(width, height) {
return {
width,
height,
getContext: () => ({
fillStyle: '',
font: '',
textAlign: '',
fillRect: () => {},
fillText: () => {},
createLinearGradient: () => ({
addColorStop: () => {}
})
}),
toBuffer: () => Buffer.from('')
};
}
// บันทึก Canvas เป็นไฟล์
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}`);
// สร้างไฟล์ placeholder
return this.createPlaceholderImage(outputPath);
}
}
// สร้างไฟล์ placeholder
createPlaceholderImage(outputPath) {
try {
// สร้างไฟล์ SVG placeholder
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>
`;
// เปลี่ยนนามสกุลเป็น .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+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5FeGVjdX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:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM3MTgwOTYiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0Y3RkFGQyI+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');
// วิเคราะห์ package.json สำหรับ Node.js
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);
}
}
// วิเคราะห์ requirements.txt สำหรับ Python
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 : [];
}
// สร้าง UI Interface สำหรับการแสดงผล
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) {
// Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe
pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins');
} else {
// Development: มองหาใน UserData (หรือตามที่คุณตั้งค่าไว้)
// เราจะใช้ basePath สำหรับโฟลเดอร์อื่น แต่จะระบุ pluginsPath แยกต่างหาก
const basePath = app.getAppPath();
pluginsPath = path.join(basePath, 'plugins'); // หรือ path.join(app.getPath('userData'), 'plugins') หากต้องการ
}
const scanLocations = [
pluginsPath // สแกนที่ตำแหน่งของ plugins ที่ถูกต้องเพียงที่เดียว
];
for (const location of scanLocations) {
console.log(`[SystemDetector] Scanning location: ${location}`);
if (fs.existsSync(location)) {
await this.scanDirectoryRecursive(location, 0, 3); // สแกนลึกสูงสุด 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
};
}
/**
* สแกนโฟลเดอร์ย่อยๆ ข้างใน (Recursive)
*/
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) { // ถ้ามั่นใจเกิน 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);
}
}
// รีเฟรชการสแกนและสร้างปุ่ม (เก็บไว้เพื่อ backward compatibility)
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) {
// Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe
pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins');
} else {
// Development: มองหาใน Root ของโปรเจกต์
const basePath = app.getAppPath();
pluginsPath = path.join(basePath, 'plugins');
}
// สแกนโปรเจคใหม่ใน directories ต่างๆ
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);
}
}
/**
* รายงานสถานะ detector
*/
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;