| 1010 | // --------------------------------------------------------------------------- |
| 1011 | |
| 1012 | std::shared_ptr<std::vector<unsigned char>> |
| 1013 | NetworkChunkCache::get(PJ_CONTEXT *ctx, const std::string &url, |
| 1014 | unsigned long long chunkIdx) { |
| 1015 | std::shared_ptr<std::vector<unsigned char>> ret; |
| 1016 | if (cache_.tryGet(Key(url, chunkIdx), ret)) { |
| 1017 | return ret; |
| 1018 | } |
| 1019 | |
| 1020 | auto diskCache = DiskChunkCache::open(ctx); |
| 1021 | if (!diskCache) |
| 1022 | return ret; |
| 1023 | auto hDB = diskCache->handle(); |
| 1024 | |
| 1025 | auto stmt = diskCache->prepare( |
| 1026 | "SELECT chunks.id, chunks.data_size, chunk_data.data FROM chunks " |
| 1027 | "JOIN chunk_data ON chunks.id = chunk_data.id " |
| 1028 | "WHERE chunks.url = ? AND chunks.offset = ?"); |
| 1029 | if (!stmt) |
| 1030 | return ret; |
| 1031 | |
| 1032 | stmt->bindText(url.c_str()); |
| 1033 | stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); |
| 1034 | |
| 1035 | const auto mainRet = stmt->execute(); |
| 1036 | if (mainRet == SQLITE_ROW) { |
| 1037 | const auto chunk_id = stmt->getInt64(); |
| 1038 | const auto data_size = stmt->getInt64(); |
| 1039 | int blob_size = 0; |
| 1040 | const void *blob = stmt->getBlob(blob_size); |
| 1041 | if (blob_size < data_size) { |
| 1042 | pj_log(ctx, PJ_LOG_ERROR, |
| 1043 | "blob_size=%d < data_size for chunk_id=%d", blob_size, |
| 1044 | static_cast<int>(chunk_id)); |
| 1045 | return ret; |
| 1046 | } |
| 1047 | if (data_size > static_cast<sqlite3_int64>(DOWNLOAD_CHUNK_SIZE)) { |
| 1048 | pj_log(ctx, PJ_LOG_ERROR, "data_size > DOWNLOAD_CHUNK_SIZE"); |
| 1049 | return ret; |
| 1050 | } |
| 1051 | ret.reset(new std::vector<unsigned char>()); |
| 1052 | ret->assign(reinterpret_cast<const unsigned char *>(blob), |
| 1053 | reinterpret_cast<const unsigned char *>(blob) + |
| 1054 | static_cast<size_t>(data_size)); |
| 1055 | cache_.insert(Key(url, chunkIdx), ret); |
| 1056 | |
| 1057 | if (!diskCache->move_to_head(chunk_id)) |
| 1058 | return ret; |
| 1059 | } else if (mainRet != SQLITE_DONE) { |
| 1060 | pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); |
| 1061 | } |
| 1062 | |
| 1063 | return ret; |
| 1064 | } |
| 1065 | |
| 1066 | // --------------------------------------------------------------------------- |
| 1067 | |