| 208 | }; |
| 209 | |
| 210 | static bool common_pull_file(httplib::Client & cli, |
| 211 | const std::string & resolve_path, |
| 212 | const std::string & path_tmp, |
| 213 | bool supports_ranges, |
| 214 | common_download_progress & p, |
| 215 | common_download_callback * callback) { |
| 216 | std::ofstream ofs(path_tmp, std::ios::binary | std::ios::app); |
| 217 | if (!ofs.is_open()) { |
| 218 | LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_tmp.c_str()); |
| 219 | return false; |
| 220 | } |
| 221 | |
| 222 | httplib::Headers headers; |
| 223 | if (supports_ranges && p.downloaded > 0) { |
| 224 | headers.emplace("Range", "bytes=" + std::to_string(p.downloaded) + "-"); |
| 225 | } |
| 226 | |
| 227 | const char * func = __func__; // avoid __func__ inside a lambda |
| 228 | size_t progress_step = 0; |
| 229 | |
| 230 | auto res = cli.Get(resolve_path, headers, |
| 231 | [&](const httplib::Response &response) { |
| 232 | if (p.downloaded > 0 && response.status != 206) { |
| 233 | LOG_WRN("%s: server did not respond with 206 Partial Content for a resume request. Status: %d\n", func, response.status); |
| 234 | return false; |
| 235 | } |
| 236 | if (p.downloaded == 0 && response.status != 200) { |
| 237 | LOG_WRN("%s: download received non-successful status code: %d\n", func, response.status); |
| 238 | return false; |
| 239 | } |
| 240 | if (p.total == 0 && response.has_header("Content-Length")) { |
| 241 | try { |
| 242 | size_t content_length = std::stoull(response.get_header_value("Content-Length")); |
| 243 | p.total = p.downloaded + content_length; |
| 244 | } catch (const std::exception &e) { |
| 245 | LOG_WRN("%s: invalid Content-Length header: %s\n", func, e.what()); |
| 246 | } |
| 247 | } |
| 248 | return true; |
| 249 | }, |
| 250 | [&](const char *data, size_t len) { |
| 251 | ofs.write(data, len); |
| 252 | if (!ofs) { |
| 253 | LOG_ERR("%s: error writing to file: %s\n", func, path_tmp.c_str()); |
| 254 | return false; |
| 255 | } |
| 256 | p.downloaded += len; |
| 257 | progress_step += len; |
| 258 | |
| 259 | if (progress_step >= p.total / 1000 || p.downloaded == p.total) { |
| 260 | if (callback) { |
| 261 | callback->on_update(p); |
| 262 | if (callback->is_cancelled()) { |
| 263 | return false; |
| 264 | } |
| 265 | } |
| 266 | progress_step = 0; |
| 267 | } |
no test coverage detected