widget-helpers.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { promises as fs } from "fs";
  2. import path from "path";
  3. import yaml from "js-yaml";
  4. import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
  5. export async function widgetsFromConfig() {
  6. checkAndCopyConfig("widgets.yaml");
  7. const widgetsYaml = path.join(CONF_DIR, "widgets.yaml");
  8. const rawFileContents = await fs.readFile(widgetsYaml, "utf8");
  9. const fileContents = substituteEnvironmentVars(rawFileContents);
  10. const widgets = yaml.load(fileContents);
  11. if (!widgets) return [];
  12. // map easy to write YAML objects into easy to consume JS arrays
  13. const widgetsArray = widgets.map((group, index) => ({
  14. type: Object.keys(group)[0],
  15. options: {
  16. index,
  17. ...group[Object.keys(group)[0]]
  18. },
  19. }));
  20. return widgetsArray;
  21. }
  22. export async function cleanWidgetGroups(widgets) {
  23. return widgets.map((widget, index) => {
  24. const sanitizedOptions = widget.options;
  25. const optionKeys = Object.keys(sanitizedOptions);
  26. // delete private options from the sanitized options
  27. ["username", "password", "key"].forEach((pO) => {
  28. if (optionKeys.includes(pO)) {
  29. delete sanitizedOptions[pO];
  30. }
  31. });
  32. // delete url from the sanitized options if the widget is not a search or glances widgeth
  33. if (widget.type !== "search" && widget.type !== "glances" && optionKeys.includes("url")) {
  34. delete sanitizedOptions.url;
  35. }
  36. return {
  37. type: widget.type,
  38. options: {
  39. index,
  40. ...sanitizedOptions
  41. },
  42. }
  43. });
  44. }
  45. export async function getPrivateWidgetOptions(type, widgetIndex) {
  46. const widgets = await widgetsFromConfig();
  47. const privateOptions = widgets.map((widget) => {
  48. const {
  49. index,
  50. url,
  51. username,
  52. password,
  53. key
  54. } = widget.options;
  55. return {
  56. type: widget.type,
  57. options: {
  58. index,
  59. url,
  60. username,
  61. password,
  62. key
  63. },
  64. }
  65. });
  66. return (type !== undefined && widgetIndex !== undefined) ? privateOptions.find(o => o.type === type && o.options.index === parseInt(widgetIndex, 10))?.options : privateOptions;
  67. }