File size: 50,361 Bytes
857cdcf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 | /**
* 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,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbn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c3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM5MENERjQiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0VCRjhGRiI+8J+MkDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5XZWIgQXBwPC90ZXh0Pgo8L3N2Zz4=',
'default': 'data: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; |