Arch-Node-JS-LemonBar/main.js
2021-09-23 21:28:11 -04:00

157 lines
6.0 KiB
JavaScript

// Required Modules
var lb = require("lemonbar");
var wifi = require('node-wifi');
const monitor = require('node-active-window');
var address = require('network-address')
const jsonfile = require('jsonfile')
const battery = require("battery");
const fs = require('fs');
const os = require('os');
const date = require('date-and-time');
var free = require('freem');
const checkDiskSpace = require('check-disk-space').default
let font = "Roboto Medium"
function cpuUsage(cb, core, sampleMs) {
var deltaUsed;
var deltaIdle;
var timesKeys = ["user", "nice", "sys", "irq"];
var allCores = null === core || !(core > -1);
var byCore = (cpu, i) => allCores || core === i;
var bySampleKey = (sample, key) => sample.filter(byCore).reduce((sum, cpu) => sum + cpu.times[key], 0);
var sample0 = os.cpus();
setTimeout(function () {
var sample1 = os.cpus();
deltaUsed = timesKeys.reduce(
(diff, key) => diff + bySampleKey(sample1, key) - bySampleKey(sample0, key), 0);
deltaIdle = bySampleKey(sample1, "idle") - bySampleKey(sample0, "idle");
if ("function" === typeof cb) {
cb(100 * (deltaUsed / (deltaUsed + deltaIdle)));
}
}, sampleMs || 1000);
}
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
const file = '/home/raven/Documents/cache.json'
// Launching Main PID for LemonBar
lb.launch({
lemonbar: "/usr/bin/lemonbar", // Lemonbar binary
shell: "/bin/sh", // Shell to use for actions
shelloutput: true, // Print shell STDOUT
background: "#000", // Background color (#rgb, #rrggbb, #aarrggbb)
foreground: "#000", // Foreground color
lineWidth: 1, lineColor: "#666",
fonts: ["Roboto Medium", "Roboto Medium"], // Underline/Overline config
geometry: { // Window geometry
x: 0, y: 0,
width: null, height: 25
},
bottom: false, // Dock bar at bottom instead of top
forceDocking: false, // Force docking without asking the window manager
name: null, // Set the WM_NAME atom value for the bar
areas: 10 // Number of clickable areas
})
// This must be async for battery level and charging detection
async function update() {
const now = new Date();
const pattern = date.compile('ddd, DD MMM YYYY');
// The cache file
const { level, charging } = await battery();
// Lets check our cache files mtime to see if we need to check the current SSID yet
fs.stat(file, function (err, stats) {
let seconds = (new Date().getTime() - stats.mtime) / 1000;
// If the mtime for the cache is over 1 hour, lets poll for a new SSID
if (seconds > 3600) {
// Init the card
wifi.init({
iface: null // network interface, choose a random wifi interface if set to null
});
// Grab the current Wifi SSID and details
wifi.getCurrentConnections((error, currentConnections) => {
if (error) {
console.log(error);
} else {
// If no error, write the result to the cache
const obj = { ssid: currentConnections[0].ssid }
jsonfile.writeFile(file, obj, function (err) {
if (err) console.error(err)
console.log("WifiCache Is Written")
})
}
})
}
checkDiskSpace('/').then((diskSpace) => {
free.m(function (err, freeRamMB) {
cpuUsage(perc => lb.append(lb.left + require("os").userInfo().username.lbFg("#fff") + " | CPU: ".lbFg("#fff") + (Math.round(perc * 100) / 100).toFixed(2).lbFg("#fff") + " | Mem: ".lbFg("#fff") + freeRamMB[0].free.lbFg("#fff") + " MB".lbFg("#fff") + " | ".lbFg("#fff") + formatBytes(diskSpace.free).toString().lbFg("#fff") + " of ".lbFg("#fff") + formatBytes(diskSpace.size).toString().lbFg("#fff")));
});
})
// Check the cache SSID
jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
// Set a new var containing the ID
let wifiSSID = obj.ssid
// If charging show its status, else, show nothing for charging
if (charging) {
lb.append(lb.right + (date.format(now, 'hh:mm:ss').toString.lbFg("#fff") + " | ".lbFg("#fff") + date.format(now, pattern).toString().lbFg("#fff") + " | BAT: ".lbFg("#fff") + level.toString().lbFg("#fff") + " (Charging)".lbFg("#fff") + " " + "| WIFI: ".lbFg("#fff") + wifiSSID.ssid.lbFg("#fff") + " | IP: ".lbFg("#fff") + address().lbFg("#fff")).lbSwap)
} else {
lb.append(lb.right + (date.format(now, 'hh:mm:ss').toString().lbFont(font).lbFg("#fff") + " | ".lbFg("#fff") + date.format(now, pattern).toString().lbFg("#fff") + " | BAT: ".lbFg("#fff") + level.toString().lbFg("#fff") + " " + "| WIFI: ".lbFg("#fff") + wifiSSID.toString().lbFg("#fff") + " | IP: ".lbFg("#fff") + address().lbFg("#fff")).lbSwap)
}
monitor.getActiveWindow((err, window) => {
if (!err) {
lb.append((lb.center + window.app.lbFg("#fff")))
} else
console.log(err)
}); // Grab the active window and and page name
// Write the data to lemonbar
lb.write()
})
})
}
update()
// Update current time every second
setTimeout(function () {
update()
setInterval(update, 1500)
}, 1500 - new Date().getMilliseconds())