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.

78 lines
2.0 KiB

11 months ago
  1. const path = require("path");
  2. const fs = require("fs");
  3. const {
  4. WATCH_DIRECTORY,
  5. SUPPORTED_FILETYPE_CONVERTERS,
  6. } = require("../utils/constants");
  7. const {
  8. trashFile,
  9. isTextType,
  10. normalizePath,
  11. isWithin,
  12. } = require("../utils/files");
  13. const RESERVED_FILES = ["__HOTDIR__.md"];
  14. async function processSingleFile(targetFilename, options = {}) {
  15. const fullFilePath = path.resolve(
  16. WATCH_DIRECTORY,
  17. normalizePath(targetFilename)
  18. );
  19. if (!isWithin(path.resolve(WATCH_DIRECTORY), fullFilePath))
  20. return {
  21. success: false,
  22. reason: "Filename is a not a valid path to process.",
  23. documents: [],
  24. };
  25. if (RESERVED_FILES.includes(targetFilename))
  26. return {
  27. success: false,
  28. reason: "Filename is a reserved filename and cannot be processed.",
  29. documents: [],
  30. };
  31. if (!fs.existsSync(fullFilePath))
  32. return {
  33. success: false,
  34. reason: "File does not exist in upload directory.",
  35. documents: [],
  36. };
  37. const fileExtension = path.extname(fullFilePath).toLowerCase();
  38. if (fullFilePath.includes(".") && !fileExtension) {
  39. return {
  40. success: false,
  41. reason: `No file extension found. This file cannot be processed.`,
  42. documents: [],
  43. };
  44. }
  45. let processFileAs = fileExtension;
  46. if (!SUPPORTED_FILETYPE_CONVERTERS.hasOwnProperty(fileExtension)) {
  47. if (isTextType(fullFilePath)) {
  48. console.log(
  49. `\x1b[33m[Collector]\x1b[0m The provided filetype of ${fileExtension} does not have a preset and will be processed as .txt.`
  50. );
  51. processFileAs = ".txt";
  52. } else {
  53. trashFile(fullFilePath);
  54. return {
  55. success: false,
  56. reason: `File extension ${fileExtension} not supported for parsing and cannot be assumed as text file type.`,
  57. documents: [],
  58. };
  59. }
  60. }
  61. const FileTypeProcessor = require(SUPPORTED_FILETYPE_CONVERTERS[
  62. processFileAs
  63. ]);
  64. return await FileTypeProcessor({
  65. fullFilePath,
  66. filename: targetFilename,
  67. options,
  68. });
  69. }
  70. module.exports = {
  71. processSingleFile,
  72. };