| 988 | // --------------------------------------------------------------------------- |
| 989 | |
| 990 | std::shared_ptr<std::vector<unsigned char>> |
| 991 | NetworkChunkCache::get(PJ_CONTEXT *ctx, const std::string &url, |
| 992 | unsigned long long chunkIdx) { |
| 993 | std::shared_ptr<std::vector<unsigned char>> ret; |
| 994 | if (cache_.tryGet(Key(url, chunkIdx), ret)) { |
| 995 | return ret; |
| 996 | } |
| 997 | |
| 998 | auto diskCache = DiskChunkCache::open(ctx); |
| 999 | if (!diskCache) |
| 1000 | return ret; |
| 1001 | auto hDB = diskCache->handle(); |
| 1002 | |
| 1003 | auto stmt = diskCache->prepare( |
| 1004 | "SELECT chunks.id, chunks.data_size, chunk_data.data FROM chunks " |
| 1005 | "JOIN chunk_data ON chunks.id = chunk_data.id " |
| 1006 | "WHERE chunks.url = ? AND chunks.offset = ?"); |
| 1007 | if (!stmt) |
| 1008 | return ret; |
| 1009 | |
| 1010 | stmt->bindText(url.c_str()); |
| 1011 | stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); |
| 1012 | |
| 1013 | const auto mainRet = stmt->execute(); |
| 1014 | if (mainRet == SQLITE_ROW) { |
| 1015 | const auto chunk_id = stmt->getInt64(); |
| 1016 | const auto data_size = stmt->getInt64(); |
| 1017 | int blob_size = 0; |
| 1018 | const void *blob = stmt->getBlob(blob_size); |
| 1019 | if (blob_size < data_size) { |
| 1020 | pj_log(ctx, PJ_LOG_ERROR, |
| 1021 | "blob_size=%d < data_size for chunk_id=%d", blob_size, |
| 1022 | static_cast<int>(chunk_id)); |
| 1023 | return ret; |
| 1024 | } |
| 1025 | if (data_size > static_cast<sqlite3_int64>(DOWNLOAD_CHUNK_SIZE)) { |
| 1026 | pj_log(ctx, PJ_LOG_ERROR, "data_size > DOWNLOAD_CHUNK_SIZE"); |
| 1027 | return ret; |
| 1028 | } |
| 1029 | ret.reset(new std::vector<unsigned char>()); |
| 1030 | ret->assign(reinterpret_cast<const unsigned char *>(blob), |
| 1031 | reinterpret_cast<const unsigned char *>(blob) + |
| 1032 | static_cast<size_t>(data_size)); |
| 1033 | cache_.insert(Key(url, chunkIdx), ret); |
| 1034 | |
| 1035 | if (!diskCache->move_to_head(chunk_id)) |
| 1036 | return ret; |
| 1037 | } else if (mainRet != SQLITE_DONE) { |
| 1038 | pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); |
| 1039 | } |
| 1040 | |
| 1041 | return ret; |
| 1042 | } |
| 1043 | |
| 1044 | // --------------------------------------------------------------------------- |
| 1045 | |