| 1 | // Aseprite |
| 2 | // Copyright (C) 2020-2022 Igara Studio S.A. |
| 3 | // Copyright (C) 2001-2016 David Capello |
| 4 | // |
| 5 | // This program is distributed under the terms of |
| 6 | // the End-User License Agreement for Aseprite. |
| 7 | |
| 8 | #ifdef HAVE_CONFIG_H |
| 9 | #include "config.h" |
| 10 | #endif |
| 11 | |
| 12 | #include "app/res/http_loader.h" |
| 13 | |
| 14 | #include "base/fs.h" |
| 15 | #include "base/fstream_path.h" |
| 16 | #include "base/replace_string.h" |
| 17 | #include "base/scoped_value.h" |
| 18 | #include "base/string.h" |
| 19 | #include "net/http_request.h" |
| 20 | #include "net/http_response.h" |
| 21 | #include "ver/info.h" |
| 22 | |
| 23 | #include <fstream> |
| 24 | |
| 25 | namespace app { |
| 26 | |
| 27 | HttpLoader::HttpLoader(const std::string& url) |
| 28 | : m_url(url) |
| 29 | , m_done(false) |
| 30 | , m_request(nullptr) |
| 31 | , m_thread([this]{ threadHttpRequest(); }) |
| 32 | { |
| 33 | } |
| 34 | |
| 35 | HttpLoader::~HttpLoader() |
| 36 | { |
| 37 | m_thread.join(); |
| 38 | } |
| 39 | |
| 40 | void HttpLoader::abort() |
| 41 | { |
| 42 | if (m_request) |
| 43 | m_request->abort(); |
| 44 | } |
| 45 | |
| 46 | void HttpLoader::threadHttpRequest() |
| 47 | { |
| 48 | try { |
| 49 | base::ScopedValue<std::atomic<bool>, bool> scoped(m_done, false, true); |
| 50 | |
| 51 | LOG("HTTP: Sending http request to %s\n" , m_url.c_str()); |
| 52 | |
| 53 | std::string dir = base::join_path(base::get_temp_path(), get_app_name()); |
| 54 | base::make_all_directories(dir); |
| 55 | |
| 56 | std::string fn = m_url; |
| 57 | base::replace_string(fn, ":" , "-" ); |
| 58 | base::replace_string(fn, "/" , "-" ); |
| 59 | base::replace_string(fn, "?" , "-" ); |
| 60 | base::replace_string(fn, "&" , "-" ); |
| 61 | fn = base::join_path(dir, fn); |
| 62 | |
| 63 | std::ofstream output(FSTREAM_PATH(fn), std::ofstream::binary); |
| 64 | m_request = new net::HttpRequest(m_url); |
| 65 | net::HttpResponse response(&output); |
| 66 | if (m_request->send(response) && |
| 67 | response.status() == 200) { |
| 68 | m_filename = fn; |
| 69 | } |
| 70 | |
| 71 | LOG("HTTP: Response: %d\n" , response.status()); |
| 72 | } |
| 73 | catch (const std::exception& e) { |
| 74 | LOG(ERROR, "HTTP: Unexpected exception sending http request: %s\n" , e.what()); |
| 75 | } |
| 76 | catch (...) { |
| 77 | LOG(ERROR, "HTTP: Unexpected unknown exception sending http request\n" ); |
| 78 | } |
| 79 | |
| 80 | delete m_request; |
| 81 | m_request = nullptr; |
| 82 | } |
| 83 | |
| 84 | } // namespace app |
| 85 | |