FileDirectoryLoader.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2023, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/NumberFormat.h>
  7. #include <AK/QuickSort.h>
  8. #include <AK/SourceGenerator.h>
  9. #include <LibCore/DateTime.h>
  10. #include <LibCore/Directory.h>
  11. #include <LibCore/System.h>
  12. #include <LibWeb/Loader/FileDirectoryLoader.h>
  13. #include <LibWeb/Loader/FrameLoader.h>
  14. namespace Web {
  15. ErrorOr<DeprecatedString> load_file_directory_page(LoadRequest const& request)
  16. {
  17. // Generate HTML contents entries table
  18. auto lexical_path = LexicalPath(request.url().serialize_path());
  19. Core::DirIterator dt(lexical_path.string(), Core::DirIterator::Flags::SkipParentAndBaseDir);
  20. Vector<DeprecatedString> names;
  21. while (dt.has_next())
  22. names.append(dt.next_path());
  23. quick_sort(names);
  24. StringBuilder contents;
  25. contents.append("<table>"sv);
  26. for (auto& name : names) {
  27. auto path = lexical_path.append(name);
  28. auto maybe_st = Core::System::stat(path.string());
  29. if (!maybe_st.is_error()) {
  30. auto st = maybe_st.release_value();
  31. auto is_directory = S_ISDIR(st.st_mode);
  32. contents.append("<tr>"sv);
  33. contents.appendff("<td><span class=\"{}\"></span></td>", is_directory ? "folder" : "file");
  34. contents.appendff("<td><a href=\"file://{}\">{}</a></td><td>&nbsp;</td>"sv, path, name);
  35. contents.appendff("<td>{:10}</td><td>&nbsp;</td>", is_directory ? "-" : human_readable_size(st.st_size));
  36. contents.appendff("<td>{}</td>"sv, Core::DateTime::from_timestamp(st.st_mtime).to_deprecated_string());
  37. contents.append("</tr>\n"sv);
  38. }
  39. }
  40. contents.append("</table>"sv);
  41. // Generate HTML directory page from directory template file
  42. // FIXME: Use an actual templating engine (our own one when it's built, preferably with a way to check these usages at compile time)
  43. auto template_path = AK::URL::create_with_url_or_path(FrameLoader::directory_page_url()).serialize_path();
  44. auto template_file = TRY(Core::File::open(template_path, Core::File::OpenMode::Read));
  45. auto template_contents = TRY(template_file->read_until_eof());
  46. StringBuilder builder;
  47. SourceGenerator generator { builder };
  48. generator.set("resource_directory_url", FrameLoader::resource_directory_url());
  49. generator.set("path", escape_html_entities(lexical_path.string()));
  50. generator.set("parent_path", escape_html_entities(lexical_path.parent().string()));
  51. generator.set("contents", contents.to_deprecated_string());
  52. generator.append(template_contents);
  53. return generator.as_string_view().to_deprecated_string();
  54. }
  55. }