Files
imexrps/electron/file-watcher/file-watcher.js
2020-10-14 17:08:47 -07:00

97 lines
2.7 KiB
JavaScript

const chokidar = require("chokidar");
const settings = require("electron-settings");
const ipcTypes = require("../../src/ipc.types");
const path = require("path");
const { DecodeEstimate } = require("../decoder/decoder");
const { BrowserWindow, Notification } = require("electron");
const _ = require("lodash");
var watcher;
function StartWatcher() {
const filePaths =
settings
.getSync("filePaths")
.map((fp) => path.join(fp, "**.[eE][nN][vV]")) || [];
console.log("StartWatcher -> filePaths", filePaths);
Notification({
title: "Watcher started!",
body: "Watcher has been started..",
}).show();
watcher = chokidar.watch(filePaths, {
//ignored: /[\/\\]\./,
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
pollInterval: 100,
stabilityThreshold: 2000,
},
});
watcher
.on("add", async function (path) {
console.log("File", path, "has been added");
HandleNewFile(path);
})
.on("addDir", function (path) {
console.log("Directory", path, "has been added");
})
.on("change", async function (path) {
console.log("File", path, "has been changed");
HandleNewFile(path);
})
.on("unlink", function (path) {
console.log("File", path, "has been removed");
})
.on("unlinkDir", function (path) {
console.log("Directory", path, "has been removed");
})
.on("error", function (error) {
console.log("Error happened", error);
const b = BrowserWindow.getFocusedWindow();
b.webContents.send(ipcTypes.fileWatcher.toRenderer.error, error);
})
.on("ready", onWatcherReady)
.on("raw", function (event, path, details) {
// This event should be triggered everytime something happens.
// console.log("Raw event info:", event, path, details);
});
return filePaths;
}
function onWatcherReady() {
console.log("Ready!");
const b = BrowserWindow.getFocusedWindow();
b.webContents.send(ipcTypes.default.fileWatcher.toRenderer.startSuccess);
}
async function StopWatcher() {
await watcher.close();
console.log("Watcher Stopped!");
}
exports.StartWatcher = StartWatcher;
exports.StopWatcher = StopWatcher;
exports.watcher = watcher;
async function HandleNewFile(path) {
const b = BrowserWindow.getAllWindows()[0];
b.webContents.send(ipcTypes.default.estimate.toRenderer.estimateDecodeStart);
const newJob = await DecodeEstimate(path);
const newJobLow = _.transform(newJob, function (result, val, key) {
result[key.toLowerCase()] = val;
});
console.log("HandleNewFile -> newJobLow", newJobLow);
b.webContents.send(
ipcTypes.default.estimate.toRenderer.estimateDecodeSuccess,
newJobLow
);
Notification({
title: "Job Uploaded",
body: "A new job has been uploaded.",
}).show();
}