ResourceLoader.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <LibCore/CFile.h>
  2. #include <LibCore/CHttpJob.h>
  3. #include <LibCore/CHttpRequest.h>
  4. #include <LibCore/CNetworkResponse.h>
  5. #include <LibHTML/ResourceLoader.h>
  6. ResourceLoader& ResourceLoader::the()
  7. {
  8. static ResourceLoader* s_the;
  9. if (!s_the)
  10. s_the = new ResourceLoader;
  11. return *s_the;
  12. }
  13. void ResourceLoader::load(const URL& url, Function<void(const ByteBuffer&)> callback)
  14. {
  15. if (url.protocol() == "file") {
  16. auto f = CFile::construct();
  17. f->set_filename(url.path());
  18. if (!f->open(CIODevice::OpenMode::ReadOnly)) {
  19. dbg() << "HtmlView::load: Error: " << f->error_string();
  20. callback({});
  21. return;
  22. }
  23. auto data = f->read_all();
  24. callback(data);
  25. return;
  26. }
  27. if (url.protocol() == "http") {
  28. CHttpRequest request;
  29. request.set_url(url);
  30. request.set_method(CHttpRequest::Method::GET);
  31. auto job = request.schedule();
  32. job->on_finish = [job, callback = move(callback)](bool success) {
  33. if (!success) {
  34. dbg() << "HTTP job failed!";
  35. ASSERT_NOT_REACHED();
  36. }
  37. auto* response = job->response();
  38. ASSERT(response);
  39. callback(response->payload());
  40. };
  41. return;
  42. }
  43. dbg() << "Unimplemented protocol: " << url.protocol();
  44. ASSERT_NOT_REACHED();
  45. }