| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #include "FileLoadOperation.h" |
| 10 | #include <algorithm> |
| 11 | #include "ApiScheme.h" |
| 12 | #include "ByteArray.h" |
| 13 | #include "MTProtoScheme.h" |
| 14 | #include "FileLog.h" |
| 15 | #include "ConnectionsManager.h" |
| 16 | #include "NativeByteBuffer.h" |
| 17 | #include "Datacenter.h" |
| 18 |
| 19 | FileLoadOperation::FileLoadOperation(int32_t dc_id, int64_t id, int64_t volume_id, int64_t access_hash, int32_t local_id, uint8_t *encKey, uint8_t *encIv, std::string extension, int32_t version, int32_t size, std::string dest, std::string temp) { |
| 20 | if (!dest.empty() && dest.find_last_of('/') != dest.size() - 1) { |
| 21 | dest += "/"; |
| 22 | } |
| 23 | if (!temp.empty() && temp.find_last_of('/') != temp.size() - 1) { |
| 24 | temp += "/"; |
| 25 | } |
| 26 | if (encKey != nullptr) { |
| 27 | location = std::unique_ptr<InputFileLocation>(new TL_inputEncryptedFileLocation()); |
| 28 | location->id = id; |
| 29 | location->access_hash = access_hash; |
| 30 | location->volume_id = volume_id; |
| 31 | location->local_id = local_id; |
| 32 | key = std::unique_ptr<ByteArray>(new ByteArray(encKey, 32)); |
| 33 | iv = std::unique_ptr<ByteArray>(new ByteArray(encIv, 32)); |
| 34 | } else { |
| 35 | if (volume_id != 0) { |
| 36 | location = std::unique_ptr<InputFileLocation>(new TL_inputFileLocation()); |
| 37 | location->volume_id = volume_id; |
| 38 | location->local_id = local_id; |
| 39 | location->secret = access_hash; |
| 40 | } else { |
| 41 | location = std::unique_ptr<InputFileLocation>(new TL_inputDocumentFileLocation()); |
| 42 | location->id = id; |
| 43 | location->access_hash = access_hash; |
| 44 | location->version = version; |
| 45 | } |
| 46 | } |
| 47 | destPath = dest; |
| 48 | tempPath = temp; |
| 49 | datacenter_id = dc_id; |
| 50 | totalBytesCount = size; |
| 51 | ext = extension; |
| 52 | if (key != nullptr) { |
| 53 | if (totalBytesCount % 16 != 0) { |
| 54 | bytesCountPadding = 16 - totalBytesCount % 16; |
| 55 | totalBytesCount += bytesCountPadding; |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 |
| 60 | FileLoadOperation::~FileLoadOperation() { |
| 61 | #ifdef ANDROID |
| 62 | if (ptr1 != nullptr) { |
| 63 | jniEnv[0]->DeleteGlobalRef(ptr1); |
| 64 | ptr1 = nullptr; |
| 65 | } |
| 66 | #endif |
| 67 | } |
| 68 |
| 69 | void FileLoadOperation::start() { |
| 70 | ConnectionsManager::getInstance(0).scheduleTask([&] { |
| 71 | if (state != FileLoadStateIdle) { |
| 72 | return; |
| 73 | } |
| 74 | currentDownloadChunkSize = totalBytesCount >= DOWNLOAD_BIG_FILE_MIN_SIZE ? DOWNLOAD_CHUNK_BIG_SIZE : DOWNLOAD_CHUNK_SIZE; |
| 75 | currentMaxDownloadRequests = totalBytesCount >= DOWNLOAD_BIG_FILE_MIN_SIZE ? DOWNLOAD_MAX_BIG_REQUESTS : DOWNLOAD_MAX_REQUESTS; |
| 76 | state = FileLoadStateDownloading; |
| 77 | if (location == nullptr) { |
| 78 | onFailedLoadingFile(FileLoadFailReasonError); |
| 79 | return; |
| 80 | } |
| 81 | std::string prefix; |
| 82 | if (location->volume_id != 0 && location->local_id != 0) { |
| 83 | if (datacenter_id == INT_MIN || location->volume_id == INT_MIN || datacenter_id == 0) { |
| 84 | onFailedLoadingFile(FileLoadFailReasonError); |
| 85 | return; |
| 86 | } |
| 87 | prefix = to_string_uint64(location->volume_id) + "_" + to_string_int32(location->local_id); |
| 88 | } else { |
| 89 | if (datacenter_id == 0 || location->id == 0) { |
| 90 | onFailedLoadingFile(FileLoadFailReasonError); |
| 91 | return; |
| 92 | } |
| 93 | prefix = to_string_int32(datacenter_id) + "_" + to_string_uint64(location->id); |
| 94 | } |
| 95 | filePath = destPath + prefix + "." + ext; |
| 96 | tempFilePath = tempPath + prefix + ".temp"; |
| 97 | if (key != nullptr) { |
| 98 | tempFileIvPath = tempPath + prefix + ".iv"; |
| 99 | } |
| 100 |
| 101 | FILE *destFile = fopen(filePath.c_str(), "rb"); |
| 102 | if (destFile != nullptr) { |
| 103 | long len = ftell(destFile); |
| 104 | if (totalBytesCount != 0 && totalBytesCount != len) { |
| 105 | fclose(destFile); |
| 106 | destFile = nullptr; |
| 107 | remove(filePath.c_str()); |
| 108 | } |
| 109 | } |
| 110 |
| 111 | if (destFile == nullptr) { |
| 112 | tempFile = fopen(tempFilePath.c_str(), "r+b"); |
| 113 | if (tempFile != nullptr) { |
| 114 | if (!fseek(tempFile, 0, SEEK_END) && (downloadedBytes = ftell(tempFile)) != -1L) { |
| 115 | nextDownloadOffset = downloadedBytes = downloadedBytes / currentDownloadChunkSize * currentDownloadChunkSize; |
| 116 | } else { |
| 117 | fclose(tempFile); |
| 118 | tempFile = nullptr; |
| 119 | } |
| 120 | } |
| 121 |
| 122 | if (key != nullptr) { |
| 123 | if (tempFile != nullptr) { |
| 124 | tempIvFile = fopen(tempFileIvPath.c_str(), "r+b"); |
| 125 | if (tempIvFile != nullptr) { |
| 126 | if (fread(iv->bytes, sizeof(uint8_t), 32, tempIvFile) != 32) { |
| 127 | fclose(tempIvFile); |
| 128 | tempIvFile = nullptr; |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | if (tempIvFile == nullptr) { |
| 133 | tempIvFile = fopen(tempFileIvPath.c_str(), "w+b"); |
| 134 | nextDownloadOffset = downloadedBytes = 0; |
| 135 | if (tempIvFile == nullptr) { |
| 136 | onFailedLoadingFile(FileLoadFailReasonError); |
| 137 | return; |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 |
| 142 | if (tempFile != nullptr) { |
| 143 | if (downloadedBytes != 0) { |
| 144 | if (!fseek(tempFile, downloadedBytes, SEEK_SET)) { |
| 145 | if (LOGS_ENABLED) DEBUG_D("resume loading file to temp = %s final = %s from %d", tempFilePath.c_str(), filePath.c_str(), nextDownloadOffset); |
| 146 | } else { |
| 147 | fclose(tempFile); |
| 148 | tempFile = nullptr; |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | if (tempFile == nullptr) { |
| 153 | nextDownloadOffset = downloadedBytes = 0; |
| 154 | tempFile = fopen(tempFilePath.c_str(), "w+b"); |
| 155 | if (tempFile == nullptr) { |
| 156 | onFailedLoadingFile(FileLoadFailReasonError); |
| 157 | return; |
| 158 | } |
| 159 | if (LOGS_ENABLED) DEBUG_D("start loading file to temp = %s final = %s", tempFilePath.c_str(), filePath.c_str()); |
| 160 | } |
| 161 | if (totalBytesCount != 0 && downloadedBytes == totalBytesCount) { |
| 162 | onFinishLoadingFile(); |
| 163 | } else { |
| 164 | startDownloadRequest(); |
| 165 | } |
| 166 | } else { |
| 167 | fclose(destFile); |
| 168 | onFinishLoadingFile(); |
| 169 | } |
| 170 | }); |
| 171 | } |
| 172 |
| 173 | /*void setForceRequest(boolean forceRequest) { TODO |
| 174 | isForceRequest = forceRequest; |
| 175 | } |
| 176 |
| 177 | boolean isForceRequest() { |
| 178 | return isForceRequest; |
| 179 | } |
| 180 | */ |
| 181 |
| 182 | void FileLoadOperation::cancel() { |
| 183 | ConnectionsManager::getInstance(0).scheduleTask([&] { |
| 184 | if (state == FileLoadStateFinished || state == FileLoadStateFailed) { |
| 185 | return; |
| 186 | } |
| 187 | onFailedLoadingFile(FileLoadFailReasonCanceled); |
| 188 | }); |
| 189 | } |
| 190 |
| 191 | void FileLoadOperation::setDelegate(onFinishedFunc onFinished, onFailedFunc onFailed, onProgressChangedFunc onProgressChanged) { |
| 192 | onFinishedCallback = onFinished; |
| 193 | onFailedCallback = onFailed; |
| 194 | onProgressChangedCallback = onProgressChanged; |
| 195 | } |
| 196 |
| 197 | void FileLoadOperation::cleanup() { |
| 198 | ConnectionsManager::getInstance(0).scheduleTask([&] { |
| 199 | if (tempFile != nullptr) { |
| 200 | fclose(tempFile); |
| 201 | tempFile = nullptr; |
| 202 | } |
| 203 | if (tempIvFile != nullptr) { |
| 204 | fclose(tempIvFile); |
| 205 | tempIvFile = nullptr; |
| 206 | } |
| 207 | for (size_t a = 0; a < requestInfos.size(); a++) { |
| 208 | if (requestInfos[a] != nullptr && requestInfos[a]->requestToken != 0) { |
| 209 | ConnectionsManager::getInstance(0).cancelRequestInternal(requestInfos[a]->requestToken, 0, true, false); |
| 210 | } |
| 211 | } |
| 212 | requestInfos.clear(); |
| 213 | delayedRequestInfos.clear(); |
| 214 | delete this; |
| 215 | }); |
| 216 | } |
| 217 |
| 218 | void FileLoadOperation::onFinishLoadingFile() { |
| 219 | if (state != FileLoadStateDownloading) { |
| 220 | return; |
| 221 | } |
| 222 | state = FileLoadStateFinished; |
| 223 | if (tempIvFile != nullptr) { |
| 224 | fclose(tempIvFile); |
| 225 | tempIvFile = nullptr; |
| 226 | remove(tempFileIvPath.c_str()); |
| 227 | } |
| 228 | if (tempFile != nullptr) { |
| 229 | fclose(tempFile); |
| 230 | tempFile = nullptr; |
| 231 | if (rename(tempFilePath.c_str(), filePath.c_str())) { |
| 232 | if (LOGS_ENABLED) DEBUG_E("unable to rename temp = %s to final = %s", tempFilePath.c_str(), filePath.c_str()); |
| 233 | filePath = tempFilePath; |
| 234 | } |
| 235 | } |
| 236 | if (LOGS_ENABLED) DEBUG_D("finished downloading file %s", filePath.c_str()); |
| 237 | if (onFinishedCallback != nullptr) { |
| 238 | onFinishedCallback(filePath); |
| 239 | } |
| 240 | cleanup(); |
| 241 | } |
| 242 |
| 243 | void FileLoadOperation::onFailedLoadingFile(int reason) { |
| 244 | if (state == FileLoadStateFailed) { |
| 245 | return; |
| 246 | } |
| 247 | state = FileLoadStateFailed; |
| 248 | if (onFailedCallback != nullptr) { |
| 249 | onFailedCallback(FileLoadFailReasonCanceled); |
| 250 | } |
| 251 | cleanup(); |
| 252 | } |
| 253 |
| 254 | void FileLoadOperation::processRequestResult(RequestInfo *requestInfo, TL_error *error, bool next) { |
| 255 | std::unique_ptr<RequestInfo> info; |
| 256 | if (!next) { |
| 257 | std::vector<std::unique_ptr<RequestInfo>>::iterator iter = std::find_if(requestInfos.begin(), requestInfos.end(), [&](std::unique_ptr<RequestInfo> &p) { |
| 258 | return p.get() == requestInfo; |
| 259 | }); |
| 260 | if (iter != requestInfos.end()) { |
| 261 | info = std::move(*iter); |
| 262 | requestInfos.erase(iter); |
| 263 | } |
| 264 | } |
| 265 | if (error == nullptr) { |
| 266 | if (!next && downloadedBytes != requestInfo->offset) { |
| 267 | if (state == FileLoadStateDownloading) { |
| 268 | delayedRequestInfos.push_back(std::move(info)); |
| 269 | startDownloadRequest(); |
| 270 | } |
| 271 | return; |
| 272 | } |
| 273 |
| 274 | if (requestInfo->bytes == nullptr || requestInfo->bytes->limit() == 0) { |
| 275 | onFinishLoadingFile(); |
| 276 | return; |
| 277 | } |
| 278 | int32_t currentBytesSize = requestInfo->bytes->limit(); |
| 279 | downloadedBytes += currentBytesSize; |
| 280 | bool finishedDownloading = currentBytesSize != currentDownloadChunkSize || ((totalBytesCount == downloadedBytes || downloadedBytes % currentDownloadChunkSize != 0) && (totalBytesCount <= 0 || totalBytesCount <= downloadedBytes)); |
| 281 |
| 282 | if (key != nullptr) { |
| 283 | Datacenter::aesIgeEncryption(requestInfo->bytes->bytes(), key->bytes, iv->bytes, false, true, currentBytesSize); |
| 284 | if (finishedDownloading && bytesCountPadding != 0) { |
| 285 | requestInfo->bytes->limit(currentBytesSize = (currentBytesSize - bytesCountPadding)); |
| 286 | } |
| 287 | } |
| 288 | if (tempFile != nullptr) { |
| 289 | if (fwrite(requestInfo->bytes->bytes(), sizeof(uint8_t), currentBytesSize, tempFile) != (uint32_t) currentBytesSize) { |
| 290 | onFailedLoadingFile(FileLoadFailReasonError); |
| 291 | return; |
| 292 | } |
| 293 | } |
| 294 | if (tempIvFile != nullptr) { |
| 295 | if (fseek(tempIvFile, 0, SEEK_SET) || fwrite(iv->bytes, sizeof(uint8_t), 32, tempIvFile) != 32) { |
| 296 | onFailedLoadingFile(FileLoadFailReasonError); |
| 297 | return; |
| 298 | } |
| 299 | } |
| 300 | if (totalBytesCount > 0 && state == FileLoadStateDownloading) { |
| 301 | float progress = (float) downloadedBytes / (float) totalBytesCount; |
| 302 | if (progress > 1.0f) { |
| 303 | progress = 1.0f; |
| 304 | } |
| 305 | if (onProgressChangedCallback != nullptr) { |
| 306 | onProgressChangedCallback(progress); |
| 307 | } |
| 308 | } |
| 309 |
| 310 | for (std::vector<std::unique_ptr<RequestInfo>>::iterator iter = delayedRequestInfos.begin(); iter != delayedRequestInfos.end(); iter++) { |
| 311 | if (downloadedBytes == (*iter)->offset) { |
| 312 | info = std::move(*iter); |
| 313 | delayedRequestInfos.erase(iter); |
| 314 | processRequestResult(info.get(), nullptr, true); |
| 315 | break; |
| 316 | } |
| 317 | } |
| 318 |
| 319 | if (finishedDownloading) { |
| 320 | onFinishLoadingFile(); |
| 321 | } else { |
| 322 | startDownloadRequest(); |
| 323 | } |
| 324 | } else { |
| 325 | static std::string fileMigrate = "FILE_MIGRATE_"; |
| 326 | static std::string offsetInvalid = "OFFSET_INVALID"; |
| 327 | static std::string retryLimit = "RETRY_LIMIT"; |
| 328 | if (error->text.find(fileMigrate) != std::string::npos) { |
| 329 | /*std::string num = error->text.substr(fileMigrate.size(), error->text.size() - fileMigrate.size()); |
| 330 | int32_t dcId = atoi(num.c_str()); |
| 331 | if (dcId <= 0) { |
| 332 | onFailedLoadingFile(FileLoadFailReasonError); |
| 333 | } else { |
| 334 | datacenter_id = dcId; |
| 335 | nextDownloadOffset = downloadedBytes = 0; |
| 336 | startDownloadRequest(); |
| 337 | }*/ |
| 338 | onFailedLoadingFile(FileLoadFailReasonError); |
| 339 | } else if (error->text.find(offsetInvalid) != std::string::npos) { |
| 340 | if (downloadedBytes % currentDownloadChunkSize == 0) { |
| 341 | onFinishLoadingFile(); |
| 342 | } else { |
| 343 | onFailedLoadingFile(FileLoadFailReasonError); |
| 344 | } |
| 345 | } else if (error->text.find(retryLimit) != std::string::npos) { |
| 346 | onFailedLoadingFile(FileLoadFailReasonRetryLimit); |
| 347 | } else { |
| 348 | onFailedLoadingFile(FileLoadFailReasonError); |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 |
| 353 | void FileLoadOperation::startDownloadRequest() { |
| 354 | if (state != FileLoadStateDownloading || (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) || ((requestInfos.size() + delayedRequestInfos.size()) >= currentMaxDownloadRequests)) { |
| 355 | return; |
| 356 | } |
| 357 | int32_t count = 1; |
| 358 | if (totalBytesCount > 0) { |
| 359 | count = currentMaxDownloadRequests - requestInfos.size(); |
| 360 | } |
| 361 |
| 362 | for (int32_t a = 0; a < count; a++) { |
| 363 | if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) { |
| 364 | break; |
| 365 | } |
| 366 | bool isLast = totalBytesCount <= 0 || a == count - 1 || (totalBytesCount > 0 && (nextDownloadOffset + currentDownloadChunkSize) >= totalBytesCount); |
| 367 |
| 368 | RequestInfo *requestInfo = new RequestInfo(); |
| 369 | requestInfos.push_back(std::unique_ptr<RequestInfo>(requestInfo)); |
| 370 |
| 371 | TL_upload_getFile *request = new TL_upload_getFile(); |
| 372 | request->location = location.get(); |
| 373 | requestInfo->offset = request->offset = nextDownloadOffset; |
| 374 | request->limit = currentDownloadChunkSize; |
| 375 | nextDownloadOffset += currentDownloadChunkSize; |
| 376 |
| 377 | requestInfo->requestToken = ConnectionsManager::getInstance(0).sendRequest(request, [&, requestInfo](TLObject *response, TL_error *error, int32_t connectionType) { |
| 378 | requestInfo->requestToken = 0; |
| 379 | if (response != nullptr) { |
| 380 | TL_upload_file *res = (TL_upload_file *) response; |
| 381 | requestInfo->bytes = res->bytes; |
| 382 | res->bytes = nullptr; |
| 383 | } |
| 384 | processRequestResult(requestInfo, error, false); |
| 385 | }, nullptr, (isForceRequest ? RequestFlagForceDownload : 0) | RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionTypeDownload : (ConnectionType) (ConnectionTypeDownload | (1 << 16)), isLast); |
| 386 | requestsCount++; |
| 387 | } |
| 388 | } |
| 389 |
| 390 | FileLoadOperation::RequestInfo::~RequestInfo() { |
| 391 | if (bytes != nullptr) { |
| 392 | bytes->reuse(); |
| 393 | bytes = nullptr; |
| 394 | } |
| 395 | } |
| 396 |