mirror of
https://github.com/jung-geun/NFD2NFC.git
synced 2025-12-19 20:14:39 +09:00
디렉토리 목록 업데이트 기능 추가: UI 개선 및 로그 메시지 현지화
This commit is contained in:
149
index.html
149
index.html
@@ -14,22 +14,25 @@
|
|||||||
|
|
||||||
#selected-directories {
|
#selected-directories {
|
||||||
margin-top: 20px;
|
margin-top: 20px;
|
||||||
text-align: left;
|
max-width: 700px;
|
||||||
max-width: 500px;
|
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
margin-right: auto;
|
margin-right: auto;
|
||||||
|
text-align: left;
|
||||||
}
|
}
|
||||||
|
|
||||||
.directory-item {
|
table {
|
||||||
display: flex;
|
width: 100%;
|
||||||
justify-content: space-between;
|
border-collapse: collapse;
|
||||||
align-items: center;
|
|
||||||
padding: 8px;
|
|
||||||
border-bottom: 1px solid #ccc;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.directory-path {
|
th,
|
||||||
word-break: break-all;
|
td {
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
background-color: #f2f2f2;
|
||||||
}
|
}
|
||||||
|
|
||||||
.remove-button {
|
.remove-button {
|
||||||
@@ -48,9 +51,9 @@
|
|||||||
background-color: #f0f0f0;
|
background-color: #f0f0f0;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
height: 200px;
|
height: 150px;
|
||||||
overflow-y: scroll;
|
overflow-y: scroll;
|
||||||
max-width: 500px;
|
max-width: 700px;
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
margin-right: auto;
|
margin-right: auto;
|
||||||
}
|
}
|
||||||
@@ -65,16 +68,27 @@
|
|||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<h1>Directory Watcher Application</h1>
|
<h1>디렉토리 감시 애플리케이션</h1>
|
||||||
<button id="select-directory">Select Directories</button>
|
<button id="select-directory">디렉토리 선택</button>
|
||||||
|
|
||||||
<div id="selected-directories">
|
<div id="selected-directories">
|
||||||
<h2>Watched Directories</h2>
|
<h2>감시 중인 디렉토리</h2>
|
||||||
<div id="directories-list">
|
<table>
|
||||||
<!-- Selected directories will appear here -->
|
<thead>
|
||||||
</div>
|
<tr>
|
||||||
|
<th>디렉토리 경로</th>
|
||||||
|
<th>마지막 갱신 시간</th>
|
||||||
|
<th>제거</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="directories-list">
|
||||||
|
<!-- 선택된 디렉토리 목록이 여기에 표시됩니다 -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="log">
|
<div id="log">
|
||||||
Logs will appear here.
|
로그가 여기에 표시됩니다.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
@@ -82,56 +96,69 @@
|
|||||||
const directoriesList = document.getElementById('directories-list');
|
const directoriesList = document.getElementById('directories-list');
|
||||||
const logDiv = document.getElementById('log');
|
const logDiv = document.getElementById('log');
|
||||||
|
|
||||||
// Function to add a directory to the list in the UI
|
// 디렉토리 선택 버튼 클릭 시
|
||||||
function addDirectoryToList(dirPath) {
|
|
||||||
// Avoid adding duplicates
|
|
||||||
if (document.querySelector(`[data-path="${ dirPath }"]`)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const directoryItem = document.createElement('div');
|
|
||||||
directoryItem.className = 'directory-item';
|
|
||||||
directoryItem.setAttribute('data-path', dirPath);
|
|
||||||
|
|
||||||
const pathSpan = document.createElement('span');
|
|
||||||
pathSpan.className = 'directory-path';
|
|
||||||
pathSpan.textContent = dirPath;
|
|
||||||
|
|
||||||
const removeBtn = document.createElement('button');
|
|
||||||
removeBtn.className = 'remove-button';
|
|
||||||
removeBtn.textContent = 'Remove';
|
|
||||||
removeBtn.addEventListener('click', async () => {
|
|
||||||
const response = await window.electronAPI.removeDirectory(dirPath);
|
|
||||||
if (response.success) {
|
|
||||||
directoriesList.removeChild(directoryItem);
|
|
||||||
appendLog(`Stopped watching directory: "${ dirPath }"`);
|
|
||||||
} else {
|
|
||||||
appendLog(`Failed to remove directory: "${ response.message }"`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
directoryItem.appendChild(pathSpan);
|
|
||||||
directoryItem.appendChild(removeBtn);
|
|
||||||
directoriesList.appendChild(directoryItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to append log messages to the log div
|
|
||||||
function appendLog(message) {
|
|
||||||
logDiv.textContent += `${ message }\n`;
|
|
||||||
logDiv.scrollTop = logDiv.scrollHeight; // Auto-scroll to the bottom
|
|
||||||
}
|
|
||||||
|
|
||||||
// Event listener for the "Select Directories" button
|
|
||||||
selectDirButton.addEventListener('click', async () => {
|
selectDirButton.addEventListener('click', async () => {
|
||||||
const result = await window.electronAPI.selectDirectories();
|
const result = await window.electronAPI.selectDirectories();
|
||||||
if (!result.canceled) {
|
if (!result.canceled) {
|
||||||
for (const path of result.paths) {
|
for (const path of result.paths) {
|
||||||
addDirectoryToList(path);
|
addDirectoryToList(path, new Date().toISOString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for log messages from the main process
|
// 디렉토리를 목록에 추가하는 함수
|
||||||
|
function addDirectoryToList(dirPath, lastUpdateTime) {
|
||||||
|
// 이미 목록에 있는 경우 중복 추가 방지
|
||||||
|
if (document.querySelector(`[data-path="${ dirPath }"]`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const directoryRow = document.createElement('tr');
|
||||||
|
directoryRow.setAttribute('data-path', dirPath);
|
||||||
|
|
||||||
|
const pathCell = document.createElement('td');
|
||||||
|
pathCell.textContent = dirPath;
|
||||||
|
|
||||||
|
const timeCell = document.createElement('td');
|
||||||
|
timeCell.textContent = new Date(lastUpdateTime).toLocaleString();
|
||||||
|
|
||||||
|
const removeCell = document.createElement('td');
|
||||||
|
const removeBtn = document.createElement('button');
|
||||||
|
removeBtn.className = 'remove-button';
|
||||||
|
removeBtn.textContent = '제거';
|
||||||
|
removeBtn.addEventListener('click', async () => {
|
||||||
|
const response = await window.electronAPI.removeDirectory(dirPath);
|
||||||
|
if (response.success) {
|
||||||
|
directoriesList.removeChild(directoryRow);
|
||||||
|
appendLog(`디렉토리 감시 중지: "${ dirPath }"`);
|
||||||
|
} else {
|
||||||
|
appendLog(`디렉토리 제거 실패: "${ response.message }"`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
removeCell.appendChild(removeBtn);
|
||||||
|
|
||||||
|
directoryRow.appendChild(pathCell);
|
||||||
|
directoryRow.appendChild(timeCell);
|
||||||
|
directoryRow.appendChild(removeCell);
|
||||||
|
directoriesList.appendChild(directoryRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그 메시지를 로그 섹션에 추가하는 함수
|
||||||
|
function appendLog(message) {
|
||||||
|
logDiv.textContent += `${ message }\n`;
|
||||||
|
logDiv.scrollTop = logDiv.scrollHeight; // 자동 스크롤
|
||||||
|
}
|
||||||
|
|
||||||
|
// 디렉토리 목록 업데이트 이벤트 수신
|
||||||
|
window.electronAPI.onUpdateDirectories((directories) => {
|
||||||
|
// 기존 목록 초기화
|
||||||
|
directoriesList.innerHTML = '';
|
||||||
|
for (const [dirPath, lastUpdateTime] of Object.entries(directories)) {
|
||||||
|
addDirectoryToList(dirPath, lastUpdateTime);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 로그 메시지 수신 시
|
||||||
window.electronAPI.onLog((message) => {
|
window.electronAPI.onLog((message) => {
|
||||||
appendLog(message);
|
appendLog(message);
|
||||||
});
|
});
|
||||||
|
|||||||
338
main.js
338
main.js
@@ -11,114 +11,77 @@ const {
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
const chokidar = require("chokidar");
|
const chokidar = require("chokidar");
|
||||||
const fs = require("fs").promises;
|
const fs = require("fs").promises;
|
||||||
const sqlite3 = require("sqlite3").verbose(); // Ensure sqlite3 is required
|
const fsSync = require("fs"); // For synchronous path checks
|
||||||
|
|
||||||
let tray = null;
|
let tray = null;
|
||||||
let mainWindow = null;
|
let mainWindow = null;
|
||||||
|
let watchers = {}; // To keep track of file watchers
|
||||||
|
|
||||||
// Log file path
|
// 로그 파일 경로 지정
|
||||||
const logFilePath = path.join(app.getPath("userData"), "watcher.log");
|
const logFilePath = path.join(app.getPath("userData"), "watcher.log");
|
||||||
|
|
||||||
// SQLite database path
|
// JSON 파일 경로 지정
|
||||||
const dbPath = path.join(app.getPath("userData"), "directories.db");
|
const watchedDirectoriesPath = path.join(
|
||||||
|
app.getPath("userData"),
|
||||||
|
"watchedDirectories.json"
|
||||||
|
);
|
||||||
|
|
||||||
// Initialize and connect to the SQLite database
|
// 현재 감시 중인 디렉토리 목록 및 마지막 갱신 시간
|
||||||
const db = new sqlite3.Database(dbPath, (err) => {
|
let watchedDirectories = {}; // { "path/to/dir": "2024-12-16T23:30:25.615Z", ... }
|
||||||
if (err) {
|
|
||||||
console.error("Failed to connect to the SQLite database:", err);
|
|
||||||
} else {
|
|
||||||
console.log("Connected to the SQLite database.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create the directories table if it doesn't exist
|
// Load the directories from JSON
|
||||||
db.serialize(() => {
|
async function loadWatchedDirectories() {
|
||||||
db.run(
|
try {
|
||||||
`
|
const data = await fs.readFile(watchedDirectoriesPath, "utf-8");
|
||||||
CREATE TABLE IF NOT EXISTS directories (
|
watchedDirectories = JSON.parse(data);
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
for (const dirPath of Object.keys(watchedDirectories)) {
|
||||||
path TEXT NOT NULL UNIQUE
|
watchDirectory(dirPath);
|
||||||
)
|
|
||||||
`,
|
|
||||||
(err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Failed to create directories table:", err);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
);
|
} catch (error) {
|
||||||
});
|
if (error.code !== "ENOENT") {
|
||||||
|
console.error(`Error loading directories: ${error}`);
|
||||||
|
new Notification({
|
||||||
|
title: "Error",
|
||||||
|
body: `Error loading directories: ${error.message}`,
|
||||||
|
}).show();
|
||||||
|
} else {
|
||||||
|
console.log("No watched directories found. Starting fresh.");
|
||||||
|
watchedDirectories = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Function to log messages to the log file
|
// Save directories to JSON
|
||||||
|
async function saveWatchedDirectories() {
|
||||||
|
try {
|
||||||
|
await fs.writeFile(
|
||||||
|
watchedDirectoriesPath,
|
||||||
|
JSON.stringify(watchedDirectories, null, 2),
|
||||||
|
"utf-8"
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error saving directories: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그 기록 함수
|
||||||
async function log(message) {
|
async function log(message) {
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
const logMessage = `[${timestamp}] ${message}\n`;
|
const logMessage = `[${timestamp}] ${message}\n`;
|
||||||
try {
|
try {
|
||||||
await fs.appendFile(logFilePath, logMessage);
|
await fs.appendFile(logFilePath, logMessage);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to write to log file:", error);
|
console.error("로그 파일 작성 실패:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to determine if a file/directory should be ignored
|
// 무시할 파일/디렉토리를 결정하는 함수
|
||||||
function shouldIgnore(itemName) {
|
function shouldIgnore(itemName) {
|
||||||
const ignoredItems = [".git", "node_modules", ".env"];
|
const ignoredItems = [".git", "node_modules", ".env"];
|
||||||
return ignoredItems.includes(itemName);
|
return ignoredItems.includes(itemName);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Maintain a list of watched directories and their watchers
|
// 파일 이름을 정규화하는 함수
|
||||||
let watchedDirectories = [];
|
|
||||||
let watchers = {};
|
|
||||||
|
|
||||||
// Function to load watched directories from the database
|
|
||||||
function loadWatchedDirectoriesFromDB() {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
db.all(`SELECT path FROM directories`, [], (err, rows) => {
|
|
||||||
if (err) {
|
|
||||||
log(`Failed to load directories from DB: ${err}`).catch(console.error);
|
|
||||||
return reject(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
watchedDirectories = rows.map((row) => row.path);
|
|
||||||
watchedDirectories.forEach((dirPath) => watchDirectory(dirPath));
|
|
||||||
log("Loaded watched directories from the database.").catch(console.error);
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to add a directory to the database
|
|
||||||
function addDirectoryToDB(dirPath) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
db.run(
|
|
||||||
`INSERT INTO directories (path) VALUES (?)`,
|
|
||||||
[dirPath],
|
|
||||||
function (err) {
|
|
||||||
if (err) {
|
|
||||||
log(`Failed to add directory to DB: ${err}`).catch(console.error);
|
|
||||||
return reject(err);
|
|
||||||
}
|
|
||||||
log(`Added directory to DB: "${dirPath}"`).catch(console.error);
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to remove a directory from the database
|
|
||||||
function removeDirectoryFromDB(dirPath) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
db.run(`DELETE FROM directories WHERE path = ?`, [dirPath], function (err) {
|
|
||||||
if (err) {
|
|
||||||
log(`Failed to remove directory from DB: ${err}`).catch(console.error);
|
|
||||||
return reject(err);
|
|
||||||
}
|
|
||||||
log(`Removed directory from DB: "${dirPath}"`).catch(console.error);
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to normalize file names
|
|
||||||
async function normalizeFileName(filePath) {
|
async function normalizeFileName(filePath) {
|
||||||
const dir = path.dirname(filePath);
|
const dir = path.dirname(filePath);
|
||||||
const oldName = path.basename(filePath);
|
const oldName = path.basename(filePath);
|
||||||
@@ -128,46 +91,52 @@ async function normalizeFileName(filePath) {
|
|||||||
const newPath = path.join(dir, newName);
|
const newPath = path.join(dir, newName);
|
||||||
try {
|
try {
|
||||||
await fs.rename(filePath, newPath);
|
await fs.rename(filePath, newPath);
|
||||||
await log(`Renamed: "${oldName}" -> "${newName}"`);
|
// watchedDirectories[newPath] = new Date().toISOString();
|
||||||
|
// delete watchedDirectories[filePath];
|
||||||
|
await saveWatchedDirectories();
|
||||||
|
await log(`이름 변경: "${oldName}" -> "${newName}"`);
|
||||||
|
|
||||||
// Show notification
|
// 알림 생성
|
||||||
new Notification({
|
new Notification({
|
||||||
title: "Rename Successful",
|
title: "이름 변경 완료",
|
||||||
body: `"${oldName}" has been renamed to "${newName}".`,
|
body: `"${oldName}"이 "${newName}"으로 변경되었습니다.`,
|
||||||
}).show();
|
}).show();
|
||||||
|
|
||||||
// Send log message to renderer
|
// 렌더러 프로세스로 알림 전송
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Renamed: "${oldName}" -> "${newName}"`
|
`이름 변경: "${oldName}" -> "${newName}"`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return newPath;
|
return newPath;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await log(`Failed to rename "${oldName}": ${error}`);
|
await log(`이름 변경 실패 ("${oldName}"): ${error}`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Failed to rename "${oldName}": ${error}`
|
`이름 변경 실패 ("${oldName}"): ${error}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 변경 시 마지막 갱신 시간 업데이트
|
||||||
|
// watchedDirectories[filePath] = new Date().toISOString();
|
||||||
|
// await saveWatchedDirectories();
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to process a directory recursively
|
// 디렉토리를 재귀적으로 처리하는 함수
|
||||||
async function processDirectory(dirPath) {
|
async function processDirectory(dirPath) {
|
||||||
try {
|
try {
|
||||||
await log(`Processing directory: "${dirPath}"`);
|
await log(`디렉토리 처리 시작: "${dirPath}"`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Processing directory: "${dirPath}"`
|
`디렉토리 처리 시작: "${dirPath}"`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,25 +155,28 @@ async function processDirectory(dirPath) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await normalizeFileName(dirPath);
|
await normalizeFileName(dirPath);
|
||||||
await log(`Finished processing directory: "${dirPath}"`);
|
// console.log(`디렉토리 처리 완료: "${dirPath}"`);
|
||||||
|
// watchedDirectories[dirPath] = new Date().toISOString();
|
||||||
|
// await saveWatchedDirectories();
|
||||||
|
await log(`디렉토리 처리 완료: "${dirPath}"`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Finished processing directory: "${dirPath}"`
|
`디렉토리 처리 완료: "${dirPath}"`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await log(`Error processing directory "${dirPath}": ${error}`);
|
await log(`디렉토리 처리 중 오류 발생 ("${dirPath}"): ${error}`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Error processing directory "${dirPath}": ${error}`
|
`디렉토리 처리 중 오류 발생 ("${dirPath}"): ${error}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to watch a directory
|
// 디렉토리를 감시하는 함수
|
||||||
function watchDirectory(directory) {
|
function watchDirectory(directory) {
|
||||||
const watcher = chokidar.watch(directory, {
|
const watcher = chokidar.watch(directory, {
|
||||||
ignored: (pathStr) => {
|
ignored: (pathStr) => {
|
||||||
@@ -224,76 +196,83 @@ function watchDirectory(directory) {
|
|||||||
|
|
||||||
watcher
|
watcher
|
||||||
.on("add", async (filePath) => {
|
.on("add", async (filePath) => {
|
||||||
await log(`File added: "${filePath}"`);
|
// await log(`파일 추가됨: "${filePath}"`);
|
||||||
if (mainWindow) {
|
// if (mainWindow) {
|
||||||
mainWindow.webContents.send("log-message", `File added: "${filePath}"`);
|
// mainWindow.webContents.send(
|
||||||
}
|
// "log-message",
|
||||||
|
// `파일 추가됨: "${filePath}"`
|
||||||
|
// );
|
||||||
|
// }
|
||||||
await normalizeFileName(filePath);
|
await normalizeFileName(filePath);
|
||||||
})
|
})
|
||||||
.on("change", async (filePath) => {
|
.on("change", async (filePath) => {
|
||||||
await log(`File changed: "${filePath}"`);
|
// await log(`파일 변경됨: "${filePath}"`);
|
||||||
if (mainWindow) {
|
// if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
// mainWindow.webContents.send(
|
||||||
"log-message",
|
// "log-message",
|
||||||
`File changed: "${filePath}"`
|
// `파일 변경됨: "${filePath}"`
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
await normalizeFileName(filePath);
|
await normalizeFileName(filePath);
|
||||||
})
|
})
|
||||||
.on("unlink", async (filePath) => {
|
.on("unlink", async (filePath) => {
|
||||||
await log(`File removed: "${filePath}"`);
|
// await log(`파일 삭제됨: "${filePath}"`);
|
||||||
if (mainWindow) {
|
// if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
// mainWindow.webContents.send(
|
||||||
"log-message",
|
// "log-message",
|
||||||
`File removed: "${filePath}"`
|
// `파일 삭제됨: "${filePath}"`
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
})
|
})
|
||||||
.on("addDir", async (dirPath) => {
|
.on("addDir", async (dirPath) => {
|
||||||
await log(`Directory added: "${dirPath}"`);
|
// await log(`디렉토리 추가됨: "${dirPath}"`);
|
||||||
if (mainWindow) {
|
// if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
// mainWindow.webContents.send(
|
||||||
"log-message",
|
// "log-message",
|
||||||
`Directory added: "${dirPath}"`
|
// `디렉토리 추가됨: "${dirPath}"`
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
await processDirectory(dirPath);
|
await processDirectory(dirPath);
|
||||||
})
|
})
|
||||||
.on("unlinkDir", async (dirPath) => {
|
.on("unlinkDir", async (dirPath) => {
|
||||||
await log(`Directory removed: "${dirPath}"`);
|
// await log(`디렉토리 삭제됨: "${dirPath}"`);
|
||||||
if (mainWindow) {
|
// if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
// mainWindow.webContents.send(
|
||||||
"log-message",
|
// "log-message",
|
||||||
`Directory removed: "${dirPath}"`
|
// `디렉토리 삭제됨: "${dirPath}"`
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
})
|
})
|
||||||
.on("error", async (error) => {
|
.on("error", async (error) => {
|
||||||
await log(`Watcher error: ${error}`);
|
await log(`Watcher error: ${error}`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send("log-message", `Watcher error: ${error}`);
|
mainWindow.webContents.send("log-message", `Watcher error: ${error}`);
|
||||||
}
|
}
|
||||||
|
new Notification({
|
||||||
|
title: "Watcher Error",
|
||||||
|
body: `Error watching directory: ${error.message}`,
|
||||||
|
}).show();
|
||||||
})
|
})
|
||||||
.on("ready", () => {
|
.on("ready", () => {
|
||||||
log(
|
log(
|
||||||
`Initial scan complete. Watching for changes in "${directory}".`
|
`초기 스캔 완료. "${directory}"에서 변경 사항을 감시 중입니다.`
|
||||||
).catch(console.error);
|
).catch(console.error);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Initial scan complete. Watching for changes in "${directory}".`
|
`초기 스캔 완료. "${directory}"에서 변경 사항을 감시 중입니다.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to create the application window
|
// 창을 생성하는 함수
|
||||||
function createWindow() {
|
function createWindow() {
|
||||||
mainWindow = new BrowserWindow({
|
mainWindow = new BrowserWindow({
|
||||||
width: 600,
|
width: 550, // 너비 조정
|
||||||
height: 500,
|
height: 600, // 높이 조정
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
preload: path.join(__dirname, "preload.js"), // Recommended for security
|
preload: path.join(__dirname, "preload.js"), // 보안상 추천
|
||||||
nodeIntegration: false,
|
nodeIntegration: false,
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
},
|
},
|
||||||
@@ -301,21 +280,31 @@ function createWindow() {
|
|||||||
|
|
||||||
mainWindow.loadFile("index.html");
|
mainWindow.loadFile("index.html");
|
||||||
|
|
||||||
// Open DevTools for debugging (remove in production)
|
// 개발자 도구 열기 (배포 시 제거 권장)
|
||||||
// mainWindow.webContents.openDevTools();
|
mainWindow.webContents.openDevTools();
|
||||||
|
|
||||||
mainWindow.on("closed", function () {
|
mainWindow.on("closed", function () {
|
||||||
mainWindow = null;
|
mainWindow = null;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to set up the system tray
|
|
||||||
function setTray() {
|
function setTray() {
|
||||||
tray = new Tray(path.join(__dirname, "icon.png")); // Ensure 'icon.png' exists in your project directory
|
const iconPath = path.join(__dirname, "build/Macicon.iconset/icon_32x32.png"); // Define iconPath here
|
||||||
|
|
||||||
|
if (!fsSync.existsSync(iconPath)) {
|
||||||
|
console.error("Tray icon not found at:", iconPath);
|
||||||
|
new Notification({
|
||||||
|
title: "Error",
|
||||||
|
body: `Tray icon not found at ${iconPath}`,
|
||||||
|
}).show();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
tray = new Tray(iconPath);
|
||||||
|
|
||||||
const contextMenu = Menu.buildFromTemplate([
|
const contextMenu = Menu.buildFromTemplate([
|
||||||
{
|
{
|
||||||
label: "Open",
|
label: "열기",
|
||||||
click: () => {
|
click: () => {
|
||||||
if (mainWindow === null) {
|
if (mainWindow === null) {
|
||||||
createWindow();
|
createWindow();
|
||||||
@@ -325,7 +314,7 @@ function setTray() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Quit",
|
label: "종료",
|
||||||
click: () => {
|
click: () => {
|
||||||
app.quit();
|
app.quit();
|
||||||
},
|
},
|
||||||
@@ -335,7 +324,7 @@ function setTray() {
|
|||||||
tray.setToolTip("Directory Watcher App");
|
tray.setToolTip("Directory Watcher App");
|
||||||
tray.setContextMenu(contextMenu);
|
tray.setContextMenu(contextMenu);
|
||||||
|
|
||||||
// Double-click to open the window
|
// 더블 클릭 시 창 열기
|
||||||
tray.on("double-click", () => {
|
tray.on("double-click", () => {
|
||||||
if (mainWindow === null) {
|
if (mainWindow === null) {
|
||||||
createWindow();
|
createWindow();
|
||||||
@@ -345,23 +334,23 @@ function setTray() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to initialize the application
|
// 애플리케이션 준비 시 창 및 트레이 설정 후 디렉토리 목록 로드
|
||||||
app.whenReady().then(async () => {
|
app.whenReady().then(async () => {
|
||||||
createWindow();
|
createWindow();
|
||||||
setTray();
|
setTray();
|
||||||
await loadWatchedDirectoriesFromDB();
|
await loadWatchedDirectories();
|
||||||
|
|
||||||
app.on("activate", function () {
|
app.on("activate", function () {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Quit the app when all windows are closed (except on macOS)
|
// 모든 창이 닫히면 애플리케이션 종료 (macOS 특성)
|
||||||
app.on("window-all-closed", function () {
|
app.on("window-all-closed", function () {
|
||||||
if (process.platform !== "darwin") app.quit();
|
if (process.platform !== "darwin") app.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle selecting directories
|
// 디렉토리 감시 로직 처리
|
||||||
ipcMain.handle("select-directories", async () => {
|
ipcMain.handle("select-directories", async () => {
|
||||||
const result = await dialog.showOpenDialog({
|
const result = await dialog.showOpenDialog({
|
||||||
properties: ["openDirectory", "multiSelections"],
|
properties: ["openDirectory", "multiSelections"],
|
||||||
@@ -371,58 +360,65 @@ ipcMain.handle("select-directories", async () => {
|
|||||||
return { canceled: true };
|
return { canceled: true };
|
||||||
} else {
|
} else {
|
||||||
const selectedPaths = result.filePaths;
|
const selectedPaths = result.filePaths;
|
||||||
console.log(`Selected directories: ${selectedPaths.join(", ")}`);
|
await log(`선택된 디렉토리: "${selectedPaths.join('", "')}"`);
|
||||||
await log(`Selected directories: "${selectedPaths.join('", "')}"`);
|
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Selected directories: "${selectedPaths.join('", "')}"`
|
`선택된 디렉토리: "${selectedPaths.join('", "')}"`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const selectedPath of selectedPaths) {
|
for (const selectedPath of selectedPaths) {
|
||||||
if (!watchedDirectories.includes(selectedPath)) {
|
if (!watchedDirectories.hasOwnProperty(selectedPath)) {
|
||||||
watchedDirectories.push(selectedPath);
|
watchedDirectories[selectedPath] = new Date().toISOString();
|
||||||
watchDirectory(selectedPath);
|
watchDirectory(selectedPath);
|
||||||
await addDirectoryToDB(selectedPath);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await saveWatchedDirectories();
|
||||||
|
|
||||||
|
// 렌더러 프로세스로 선택된 디렉토리 목록 업데이트 요청
|
||||||
|
if (mainWindow) {
|
||||||
|
mainWindow.webContents.send("update-directories", watchedDirectories);
|
||||||
|
}
|
||||||
|
|
||||||
return { canceled: false, paths: selectedPaths };
|
return { canceled: false, paths: selectedPaths };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle removing a directory
|
// 디렉토리 제거 핸들러
|
||||||
ipcMain.handle("remove-directory", async (event, dirPath) => {
|
ipcMain.handle("remove-directory", async (event, dirPath) => {
|
||||||
if (watchedDirectories.includes(dirPath)) {
|
if (watchedDirectories.hasOwnProperty(dirPath)) {
|
||||||
watchedDirectories = watchedDirectories.filter((path) => path !== dirPath);
|
watchedDirectories = Object.keys(watchedDirectories)
|
||||||
|
.filter((key) => key !== dirPath)
|
||||||
|
.reduce((obj, key) => {
|
||||||
|
obj[key] = watchedDirectories[key];
|
||||||
|
return obj;
|
||||||
|
}, {});
|
||||||
if (watchers[dirPath]) {
|
if (watchers[dirPath]) {
|
||||||
await watchers[dirPath].close();
|
await watchers[dirPath].close();
|
||||||
delete watchers[dirPath];
|
delete watchers[dirPath];
|
||||||
await log(`Stopped watching directory: "${dirPath}"`);
|
await log(`디렉토리 감시 중지: "${dirPath}"`);
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
mainWindow.webContents.send(
|
mainWindow.webContents.send(
|
||||||
"log-message",
|
"log-message",
|
||||||
`Stopped watching directory: "${dirPath}"`
|
`디렉토리 감시 중지: "${dirPath}"`
|
||||||
);
|
);
|
||||||
|
mainWindow.webContents.send("update-directories", watchedDirectories);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await removeDirectoryFromDB(dirPath);
|
await saveWatchedDirectories();
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} else {
|
} else {
|
||||||
return { success: false, message: "Directory is not in the watch list." };
|
return { success: false, message: "디렉토리가 감시 목록에 없습니다." };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Close the database connection when quitting the app
|
process.on("unhandledRejection", (reason, promise) => {
|
||||||
app.on("before-quit", () => {
|
new Notification({
|
||||||
db.close((err) => {
|
title: "Unhandled Promise Rejection",
|
||||||
if (err) {
|
body: reason.message || "Unknown error",
|
||||||
console.error("Failed to close the database:", err);
|
}).show();
|
||||||
} else {
|
|
||||||
console.log("Database connection closed.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,4 +6,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
|
|||||||
removeDirectory: (dirPath) => ipcRenderer.invoke("remove-directory", dirPath),
|
removeDirectory: (dirPath) => ipcRenderer.invoke("remove-directory", dirPath),
|
||||||
onLog: (callback) =>
|
onLog: (callback) =>
|
||||||
ipcRenderer.on("log-message", (event, message) => callback(message)),
|
ipcRenderer.on("log-message", (event, message) => callback(message)),
|
||||||
|
onUpdateDirectories: (callback) =>
|
||||||
|
ipcRenderer.on("update-directories", (event, directories) =>
|
||||||
|
callback(directories)
|
||||||
|
),
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user