1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*!********************************************************************
Audacity: A Digital Audio Editor
CloudSyncService.cpp
Dmitry Vedenko
**********************************************************************/
#include "CloudSyncService.h"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <mutex>
#include <string>
#include "CloudLibrarySettings.h"
#include "sync/CloudProjectsDatabase.h"
#include "sync/CloudSyncDTO.h"
#include "sync/RemoteProjectSnapshot.h"
#include "CodeConversions.h"
#include "OAuthService.h"
#include "ServiceConfig.h"
#include "MemoryX.h"
#include "Project.h"
#include "ProjectFileIO.h"
#include "BasicUI.h"
#include "FileNames.h"
#include "IResponse.h"
#include "NetworkManager.h"
#include "Request.h"
namespace audacity::cloud::audiocom
{
namespace
{
std::mutex& GetResponsesMutex()
{
static std::mutex mutex;
return mutex;
}
std::vector<std::shared_ptr<audacity::network_manager::IResponse>>&
GetPendingRequests()
{
static std::vector<std::shared_ptr<audacity::network_manager::IResponse>>
requests;
return requests;
}
void RemovePendingRequest(audacity::network_manager::IResponse* request)
{
std::lock_guard lock { GetResponsesMutex() };
auto& requests = GetPendingRequests();
requests.erase(
std::remove_if(
requests.begin(), requests.end(),
[request](const auto& r) { return r.get() == request; }),
requests.end());
}
void PerformProjectGetRequest(
OAuthService& oAuthService, std::string url,
std::function<void(ResponseResult)> dataCallback)
{
assert(oAuthService.HasAccessToken());
if (!oAuthService.HasAccessToken())
{
dataCallback({ SyncResultCode::Unauthorized });
return;
}
using namespace audacity::network_manager;
auto request = Request(std::move(url));
request.setHeader(
common_headers::ContentType, common_content_types::ApplicationJson);
request.setHeader(
common_headers::Accept, common_content_types::ApplicationJson);
SetCommonHeaders(request);
SetOptionalHeaders(request);
auto response = NetworkManager::GetInstance().doGet(request);
response->setRequestFinishedCallback(
[dataCallback = std::move(dataCallback)](auto response)
{
BasicUI::CallAfter(
[dataCallback = std::move(dataCallback), response]
{
auto removeRequest =
finally([response] { RemovePendingRequest(response); });
dataCallback(GetResponseResult(*response, true));
});
});
std::lock_guard lock { GetResponsesMutex() };
GetPendingRequests().emplace_back(std::move(response));
}
void GetProjectInfo(
OAuthService& oAuthService, const ServiceConfig& serviceConfig,
std::string projectId,
std::function<void(sync::ProjectInfo, ResponseResult)> callback)
{
assert(callback);
PerformProjectGetRequest(
oAuthService, serviceConfig.GetProjectInfoUrl(projectId),
[callback = std::move(callback)](ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
{
callback(sync::ProjectInfo {}, std::move(result));
return;
}
auto projectInfo = sync::DeserializeProjectInfo(result.Content);
if (!projectInfo)
{
callback(
{}, { SyncResultCode::UnexpectedResponse,
std::move(result.Content) });
return;
}
callback(std::move(*projectInfo), std::move(result));
});
}
void GetSnapshotInfo(
OAuthService& oAuthService, const ServiceConfig& serviceConfig,
std::string projectId, std::string snapshotId,
std::function<void(sync::SnapshotInfo, ResponseResult result)> callback)
{
assert(callback);
PerformProjectGetRequest(
oAuthService, serviceConfig.GetSnapshotInfoUrl(projectId, snapshotId),
[callback = std::move(callback)](ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
{
callback({}, std::move(result));
return;
}
auto snapshotInfo = sync::DeserializeSnapshotInfo(result.Content);
if (!snapshotInfo)
{
callback(
{}, { SyncResultCode::UnexpectedResponse,
std::move(result.Content) });
return;
}
callback(std::move(*snapshotInfo), std::move(result));
});
}
void GetSnapshotInfo(
OAuthService& oAuthService, const ServiceConfig& serviceConfig,
std::string projectId, std::string snapshotId,
std::function<
void(sync::ProjectInfo, sync::SnapshotInfo, ResponseResult result)>
callback)
{
assert(callback);
GetProjectInfo(
oAuthService, serviceConfig, projectId,
[callback = std::move(callback), projectId,
snapshotId = std::move(snapshotId), &oAuthService,
&serviceConfig](sync::ProjectInfo projectInfo, ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
{
callback({}, {}, std::move(result));
return;
}
const auto id = !snapshotId.empty() ?
snapshotId :
(projectInfo.HeadSnapshot.Synced > 0 ?
projectInfo.HeadSnapshot.Id :
projectInfo.LastSyncedSnapshotId);
if (id.empty())
{
callback(
std::move(projectInfo), sync::SnapshotInfo {},
{ SyncResultCode::Success });
return;
}
GetSnapshotInfo(
oAuthService, serviceConfig, projectId, id,
[callback = std::move(callback),
projectInfo = std::move(projectInfo)](
sync::SnapshotInfo snapshotInfo, ResponseResult result)
{
callback(
std::move(projectInfo), std::move(snapshotInfo),
std::move(result));
});
});
}
bool HasAutosave(const std::string& path)
{
auto connection = sqlite::Connection::Open(path, sqlite::OpenMode::ReadOnly);
if (!connection)
return false;
if (!connection->CheckTableExists("autosave"))
return false;
auto statement =
connection->CreateStatement("SELECT COUNT(1) FROM autosave");
if (!statement)
return false;
auto result = statement->Prepare().Run();
if (!result.IsOk())
return false;
for (const auto& row : result)
{
if (row.GetOr(0, 0) > 0)
return true;
}
return false;
}
bool DropAutosave(const std::string& path)
{
auto connection =
sqlite::Connection::Open(path, sqlite::OpenMode::ReadWrite);
if (!connection)
return false;
if (!connection->CheckTableExists("autosave"))
return false;
auto statement = connection->CreateStatement("DELETE FROM autosave");
if (!statement)
return false;
auto result = statement->Prepare().Run();
return result.IsOk();
}
} // namespace
CloudSyncService& CloudSyncService::Get()
{
static CloudSyncService service;
return service;
}
CloudSyncService::GetProjectsFuture CloudSyncService::GetProjects(
concurrency::CancellationContextPtr context, int page, int pageSize,
std::string_view searchString)
{
using namespace audacity::network_manager;
auto promise = std::make_shared<GetProjectsPromise>();
auto& serviceConfig = GetServiceConfig();
auto& oAuthService = GetOAuthService();
auto request =
Request(serviceConfig.GetProjectsUrl(page, pageSize, searchString));
request.setHeader(
common_headers::ContentType, common_content_types::ApplicationJson);
request.setHeader(
common_headers::Accept, common_content_types::ApplicationJson);
SetCommonHeaders(request);
SetOptionalHeaders(request);
auto response = NetworkManager::GetInstance().doGet(request);
context->OnCancelled(response);
response->setRequestFinishedCallback(
[promise, response](auto)
{
auto responseResult = GetResponseResult(*response, true);
if (responseResult.Code != SyncResultCode::Success)
{
promise->set_value(responseResult);
return;
}
auto projects =
sync::DeserializePaginatedProjectsResponse(responseResult.Content);
if (!projects)
{
promise->set_value(
ResponseResult { SyncResultCode::UnexpectedResponse,
std::move(responseResult.Content) });
return;
}
promise->set_value(std::move(*projects));
});
return promise->get_future();
}
CloudSyncService::SyncFuture CloudSyncService::OpenFromCloud(
std::string projectId, std::string snapshotId, SyncMode mode,
sync::ProgressCallback callback)
{
ASSERT_MAIN_THREAD();
// Reset promise
mSyncPromise = {};
if (mSyncInProcess.exchange(true))
{
CompleteSync({ sync::ProjectSyncResult::StatusCode::Blocked, {}, {} });
return mSyncPromise.get_future();
}
if (projectId.empty())
{
FailSync({ SyncResultCode::InternalClientError, "Empty projectId" });
return mSyncPromise.get_future();
}
if (!callback)
mProgressCallback = [](auto...) { return true; };
else
mProgressCallback = std::move(callback);
GetSnapshotInfo(
GetOAuthService(), GetServiceConfig(), projectId, snapshotId,
[this, mode](
sync::ProjectInfo projectInfo, sync::SnapshotInfo snapshotInfo,
ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
FailSync(std::move(result));
else
SyncCloudSnapshot(projectInfo, snapshotInfo, mode);
});
return mSyncPromise.get_future();
}
CloudSyncService::SyncFuture CloudSyncService::SyncProject(
AudacityProject& project, const std::string& path, bool forceSync,
sync::ProgressCallback callback)
{
ASSERT_MAIN_THREAD();
// Reset promise
mSyncPromise = {};
if (mSyncInProcess.exchange(true))
{
CompleteSync({ sync::ProjectSyncResult::StatusCode::Blocked });
return mSyncPromise.get_future();
}
if (!callback)
mProgressCallback = [](auto...) { return true; };
else
mProgressCallback = std::move(callback);
auto& cloudDatabase = sync::CloudProjectsDatabase::Get();
auto projectInfo = cloudDatabase.GetProjectDataForPath(path);
if (!projectInfo)
{
// We assume, that the project is local
CompleteSync(path);
return mSyncPromise.get_future();
}
GetProjectInfo(
GetOAuthService(), GetServiceConfig(), projectInfo->ProjectId,
[projectInfo = *projectInfo, &project, path,
mode = forceSync ? SyncMode::ForceOverwrite : SyncMode::Normal,
this](sync::ProjectInfo remoteInfo, ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
{
FailSync(std::move(result));
return;
}
// Do not perform the snapshot request if the project is up to date
if (remoteInfo.HeadSnapshot.Id == projectInfo.SnapshotId)
{
CompleteSync({ sync::ProjectSyncResult::StatusCode::Succeeded });
return;
}
const auto snapshotId = remoteInfo.HeadSnapshot.Synced > 0 ?
remoteInfo.HeadSnapshot.Id :
remoteInfo.LastSyncedSnapshotId;
GetSnapshotInfo(
GetOAuthService(), GetServiceConfig(), remoteInfo.Id, snapshotId,
[this, &project, mode,
remoteInfo](sync::SnapshotInfo snapshotInfo, ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
FailSync(std::move(result));
else
SyncCloudSnapshot(remoteInfo, snapshotInfo, mode);
});
});
return mSyncPromise.get_future();
}
bool CloudSyncService::IsCloudProject(const std::string& path)
{
auto& cloudDatabase = sync::CloudProjectsDatabase::Get();
auto projectInfo = cloudDatabase.GetProjectDataForPath(path);
return projectInfo.has_value();
}
CloudSyncService::ProjectState
CloudSyncService::GetProjectState(const std::string& projectId)
{
auto& cloudDatabase = sync::CloudProjectsDatabase::Get();
auto projectInfo = cloudDatabase.GetProjectData(projectId);
if (!projectInfo)
return ProjectState::NotAvaliable;
if (!wxFileExists(ToWXString(projectInfo->LocalPath)))
return ProjectState::NotAvaliable;
if (projectInfo->SyncStatus == sync::DBProjectData::SyncStatusSynced)
return ProjectState::FullySynced;
return ProjectState::PendingSync;
}
CloudSyncService::GetHeadSnapshotIDFuture
CloudSyncService::GetHeadSnapshotID(std::string_view projectId)
{
ASSERT_MAIN_THREAD();
auto promise = std::make_shared<GetHeadSnapshotIDPromise>();
GetProjectInfo(
GetOAuthService(), GetServiceConfig(), std::string(projectId),
[promise](sync::ProjectInfo projectInfo, ResponseResult result)
{
if (result.Code != SyncResultCode::Success)
{
promise->set_value(
sync::GetHeadSnapshotIDResult { std::move(result) });
}
else
promise->set_value({ projectInfo.HeadSnapshot.Id });
});
return promise->get_future();
}
void CloudSyncService::FailSync(ResponseResult responseResult)
{
CompleteSync(
sync::ProjectSyncResult { sync::ProjectSyncResult::StatusCode::Failed,
std::move(responseResult),
{} });
}
void CloudSyncService::CompleteSync(std::string path)
{
CompleteSync(sync::ProjectSyncResult {
sync::ProjectSyncResult::StatusCode::Succeeded, {}, std::move(path) });
}
void CloudSyncService::CompleteSync(sync::ProjectSyncResult result)
{
if (mRemoteSnapshot)
{
result.Stats = mRemoteSnapshot->GetTransferStats();
ReportUploadStats(mRemoteSnapshot->GetProjectId(), result.Stats);
}
mSyncPromise.set_value(std::move(result));
mRemoteSnapshot.reset();
mSyncInProcess.store(false);
}
void CloudSyncService::SyncCloudSnapshot(
const sync::ProjectInfo& projectInfo, const sync::SnapshotInfo& snapshotInfo,
SyncMode mode)
{
// Get the project location
auto localProjectInfo =
sync::CloudProjectsDatabase::Get().GetProjectData(projectInfo.Id);
const auto createNew = !localProjectInfo || mode == SyncMode::ForceNew;
const auto wxPath = createNew ?
sync::MakeSafeProjectPath(
CloudProjectsSavePath.Read(),
audacity::ToWXString(projectInfo.Name)) :
audacity::ToWXString(localProjectInfo->LocalPath);
const auto utf8Path = audacity::ToUTF8(wxPath);
const auto fileExists = wxFileExists(wxPath);
if (!fileExists)
{
if (snapshotInfo.Id.empty())
{
FailSync({ SyncResultCode::SyncImpossible });
return;
}
const auto dir = CloudProjectsSavePath.Read();
FileNames::MkDir(dir);
InvisibleTemporaryProject project;
ProjectFileIO::Get(project.Project()).LoadProject(wxPath, true);
}
else
{
assert(localProjectInfo.has_value());
assert(mode != SyncMode::ForceNew);
// The project exists on the disk. Depending on how we got here, we might
// different scenarios:
// 1. Local snapshot ID matches the remote snapshot ID. Just complete the
// sync right away. If the project was modified locally, but not saved,
// the user will be prompted about the autosave.
if (
localProjectInfo->SnapshotId == snapshotInfo.Id &&
localProjectInfo->SyncStatus != sync::DBProjectData::SyncStatusDownloading)
{
CompleteSync(
{ sync::ProjectSyncResult::StatusCode::Succeeded, {}, utf8Path });
return;
}
// 2. Project sync was interrupted.
if (
mode == SyncMode::Normal &&
localProjectInfo->SyncStatus == sync::DBProjectData::SyncStatusUploading)
{
// There is not enough information to decide if the project has
// diverged. Just open it, so the sync can resume. If the project has
// diverged, the user will be prompted to resolve the conflict on the
// next save.
CompleteSync(
{ sync::ProjectSyncResult::StatusCode::Succeeded, {}, utf8Path });
return;
}
// 3. Project was modified locally, but not saved.
if (HasAutosave(utf8Path))
{
if (mode == SyncMode::Normal)
{
FailSync({ SyncResultCode::Conflict });
return;
}
else
DropAutosave(utf8Path);
}
}
if (snapshotInfo.Id.empty())
{
FailSync({ SyncResultCode::SyncImpossible });
return;
}
mRemoteSnapshot = sync::RemoteProjectSnapshot::Sync(
projectInfo, snapshotInfo, utf8Path,
[this, createNew, path = utf8Path, projectId = projectInfo.Id,
snapshotId = snapshotInfo.Id](sync::RemoteProjectSnapshotState state)
{
UpdateDowloadProgress(
(state.ProjectDownloaded + state.BlocksDownloaded) /
(state.BlocksTotal + 1.0));
if (state.IsComplete())
{
const bool success = state.Result.Code == SyncResultCode::Success;
CompleteSync({ success ?
sync::ProjectSyncResult::StatusCode::Succeeded :
sync::ProjectSyncResult::StatusCode::Failed,
std::move(state.Result), std::move(path) });
}
},
mode == SyncMode::ForceNew);
}
void CloudSyncService::UpdateDowloadProgress(double downloadProgress)
{
mDownloadProgress.store(downloadProgress);
if (mProgressUpdateQueued.exchange(true))
return;
BasicUI::CallAfter(
[this]
{
auto remoteSnapshot = mRemoteSnapshot;
if (remoteSnapshot && !mProgressCallback(mDownloadProgress.load()))
remoteSnapshot->Cancel();
mProgressUpdateQueued.store(false);
});
}
void CloudSyncService::ReportUploadStats(
std::string_view projectId, const TransferStats& stats)
{
sync::NetworkStats networkStats;
networkStats.Bytes = stats.BytesTransferred;
networkStats.Blocks = stats.BlocksTransferred;
networkStats.Files = stats.ProjectFilesTransferred;
networkStats.Mixes = 0;
networkStats.IsDownload = true;
using namespace audacity::network_manager;
auto request = Request(GetServiceConfig().GetNetworkStatsUrl(projectId));
request.setHeader(
common_headers::ContentType, common_content_types::ApplicationJson);
SetCommonHeaders(request);
SetOptionalHeaders(request);
auto body = Serialize(networkStats);
auto response =
NetworkManager::GetInstance().doPost(request, body.data(), body.size());
// Keep response alive
response->setRequestFinishedCallback([response](auto) {});
}
} // namespace audacity::cloud::audiocom
|