You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

11 months ago
  1. const path = require("path");
  2. const fs = require("fs");
  3. const { getType } = require("mime");
  4. const { User } = require("../../models/user");
  5. const { normalizePath, isWithin } = require(".");
  6. const { Workspace } = require("../../models/workspace");
  7. function fetchPfp(pfpPath) {
  8. if (!fs.existsSync(pfpPath)) {
  9. return {
  10. found: false,
  11. buffer: null,
  12. size: 0,
  13. mime: "none/none",
  14. };
  15. }
  16. const mime = getType(pfpPath);
  17. const buffer = fs.readFileSync(pfpPath);
  18. return {
  19. found: true,
  20. buffer,
  21. size: buffer.length,
  22. mime,
  23. };
  24. }
  25. async function determinePfpFilepath(id) {
  26. const numberId = Number(id);
  27. const user = await User.get({ id: numberId });
  28. const pfpFilename = user?.pfpFilename || null;
  29. if (!pfpFilename) return null;
  30. const basePath = process.env.STORAGE_DIR
  31. ? path.join(process.env.STORAGE_DIR, "assets/pfp")
  32. : path.join(__dirname, "../../storage/assets/pfp");
  33. const pfpFilepath = path.join(basePath, normalizePath(pfpFilename));
  34. if (!isWithin(path.resolve(basePath), path.resolve(pfpFilepath))) return null;
  35. if (!fs.existsSync(pfpFilepath)) return null;
  36. return pfpFilepath;
  37. }
  38. async function determineWorkspacePfpFilepath(slug) {
  39. const workspace = await Workspace.get({ slug });
  40. const pfpFilename = workspace?.pfpFilename || null;
  41. if (!pfpFilename) return null;
  42. const basePath = process.env.STORAGE_DIR
  43. ? path.join(process.env.STORAGE_DIR, "assets/pfp")
  44. : path.join(__dirname, "../../storage/assets/pfp");
  45. const pfpFilepath = path.join(basePath, normalizePath(pfpFilename));
  46. if (!isWithin(path.resolve(basePath), path.resolve(pfpFilepath))) return null;
  47. if (!fs.existsSync(pfpFilepath)) return null;
  48. return pfpFilepath;
  49. }
  50. module.exports = {
  51. fetchPfp,
  52. determinePfpFilepath,
  53. determineWorkspacePfpFilepath,
  54. };