Home Reference Source

cables_dev/cables_electron/src/utils/helper_util.js

  1. import { SharedHelperUtil, utilProvider } from "cables-shared-api";
  2. import path from "path";
  3. import { fileURLToPath, pathToFileURL } from "url";
  4. import cables from "../cables.js";
  5. import settings from "../electron/electron_settings.js";
  6. class HelperUtil extends SharedHelperUtil
  7. {
  8. constructor(provider)
  9. {
  10. super(provider);
  11. }
  12. fileURLToPath(url, convertRelativeToProject = false)
  13. {
  14. if (!url || url === "0") return "";
  15. if (url.includes("://") && !url.startsWith("file://"))
  16. {
  17. return "";
  18. }
  19. let fileUrl = decodeURI(url);
  20. let filePath = fileUrl;
  21. const uiDistPath = cables.getUiDistPath();
  22. filePath = filePath.replace("file://" + uiDistPath, "");
  23. if (convertRelativeToProject && !filePath.startsWith("file:") && !path.isAbsolute(filePath))
  24. {
  25. filePath = path.join(cables.getAssetPath(), filePath);
  26. try
  27. {
  28. fileUrl = pathToFileURL(filePath);
  29. }
  30. catch (e)
  31. {
  32. this._log.error("failed to convert to project path", url, filePath, e);
  33. return "";
  34. }
  35. }
  36. try
  37. {
  38. return fileURLToPath(fileUrl);
  39. }
  40. catch (e)
  41. {
  42. this._log.info("failed to create path from url", convertRelativeToProject, fileUrl, url, e);
  43. return "";
  44. }
  45. }
  46. pathToFileURL(thePath, convertRelativeToProject = false)
  47. {
  48. if (thePath && thePath.startsWith("file:")) return thePath;
  49. if (convertRelativeToProject && !path.isAbsolute(thePath))
  50. {
  51. return pathToFileURL(path.join(cables.getAssetPath(), thePath)).href;
  52. }
  53. else
  54. {
  55. return thePath ? pathToFileURL(thePath).href : null;
  56. }
  57. }
  58. isLocalAssetPath(thePath)
  59. {
  60. const currentProjectDir = settings.getCurrentProjectDir();
  61. return (currentProjectDir && thePath.startsWith(currentProjectDir));
  62. }
  63. }
  64. export default new HelperUtil(utilProvider);