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