Skip to content

Instantly share code, notes, and snippets.

@Ppang0405
Last active December 24, 2020 13:31
Show Gist options
  • Save Ppang0405/3d25974f7dd5a60258d3e8d9057835c5 to your computer and use it in GitHub Desktop.
Save Ppang0405/3d25974f7dd5a60258d3e8d9057835c5 to your computer and use it in GitHub Desktop.
a bitbar plugin.
#!/usr/bin/env /usr/local/bin/node
// jshint esversion: 8
// <bitbar.title>Weather Bitbar Plugin</bitbar.title>
// <bitbar.version>v0.1</bitbar.version>
// <bitbar.author>Truong Nguyen</bitbar.author>
// <bitbar.author.github>Ppang0405</bitbar.author.github>
// <bitbar.desc>getWeather</bitbar.desc>
"use strict";
const https = require("https");
const separator = Symbol("separator");
const encodeHref = (url) => {
url = encodeURI(url);
url = url.replace(/'/g, "%27");
url = url.replace(/&/g, "%26");
return url;
};
const create = (input, options = {}, menuLevel = 0) => {
if (typeof options.text !== "undefined") {
throw new TypeError(
"The `text` option is not supported as a top-level option. Use it on an item instead.",
);
}
return input.map((line) => {
if (typeof line === "string") {
line = { text: line };
}
if (line === separator) {
return "--".repeat(menuLevel) + "---";
}
line = {
...options,
...line,
};
const { text } = line;
if (typeof text !== "string") {
throw new TypeError(
"The `text` property is required and should be a string",
);
}
delete line.text;
let submenuText = "";
if (typeof line.submenu === "object" && line.submenu.length > 0) {
submenuText = `\n${create(line.submenu, options, menuLevel + 1)}`;
delete line.submenu;
}
const prefix = "--".repeat(menuLevel);
return text.split("\n").map((textLine) => {
const options = Object.keys(line).map((key) => {
const value = key === "href" ? encodeHref(line[key]) : line[key];
return `${key}="${value}"`;
}).join(" ");
return `${prefix}${textLine}|${options}`;
}).join("\n").concat(submenuText);
}).join("\n");
};
const make = (input, options) => {
console.log(create(input, options));
};
const darkMode = process.env.BitBarDarkMode === "1";
const apiKey = "c833730aa8d4c58f4e8637c62cd21ee0";
const city = "hanoi";
const url =
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
const K2C = (temperature) => temperature - 273.15;
https.get(url, (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", () => {
const temperature = K2C(JSON.parse(data)?.main?.temp);
make([
{
text: `Hanoi ${temperature}°C`,
color: darkMode ? "white" : "red",
},
]);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment