18#include <wx/filename.h>
20#include <rapidjson/document.h>
21#include <rapidjson/writer.h>
45 return "audio/x-wavpack";
46 else if (ext ==
"flac")
47 return "audio/x-flac";
48 else if (ext ==
"mp3")
55 const wxString& filePath,
const wxString& projectName,
bool isPublic)
57 rapidjson::Document document;
60 const wxFileName fileName(filePath);
66 mimeType.data(), mimeType.length(), document.GetAllocator()),
67 document.GetAllocator());
71 if (!downloadMime.empty())
76 downloadMime.data(), downloadMime.length(),
77 document.GetAllocator()),
78 document.GetAllocator());
85 rapidjson::Value(
name.data(),
name.length(), document.GetAllocator()),
86 document.GetAllocator());
90 rapidjson::Value(
static_cast<int64_t
>(fileName.GetSize().GetValue())),
91 document.GetAllocator());
94 "public", rapidjson::Value(isPublic), document.GetAllocator());
96 rapidjson::StringBuffer buffer;
97 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
98 document.Accept(writer);
100 return std::string(buffer.GetString());
105 rapidjson::Document document;
106 document.SetObject();
109 "progress", rapidjson::Value(current /
static_cast<double>(total) * 100.0),
110 document.GetAllocator());
112 rapidjson::StringBuffer buffer;
113 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
114 document.Accept(writer);
116 return std::string(buffer.GetString());
121 rapidjson::StringStream stream(payloadText.c_str());
122 rapidjson::Document document;
124 document.ParseStream(stream);
126 if (!document.IsObject())
129 assert(document.IsObject());
135 auto readInt = [&document](
const char*
name) {
136 return document.HasMember(
name) && document[
name].IsInt() ?
137 document[
name].GetInt() :
141 auto readString = [&document](
const char*
name) ->
const char*
143 return document.HasMember(
name) && document[
name].IsString() ?
144 document[
name].GetString() :
148 payload.
code = readInt(
"code");
149 payload.
status = readInt(
"status");
151 payload.
name = readString(
"name");
152 payload.
message = readString(
"message");
154 if (document.HasMember(
"errors") && document[
"errors"].IsObject())
156 for (
auto& err : document[
"errors"].GetObject ())
158 if (!err.value.IsString())
162 err.name.GetString(), err.value.GetString());
175 std::enable_shared_from_this<UploadOperation>
179 wxString projectName,
bool isPublic,
182 : mServiceConfig(serviceConfig)
183 , mFileName(
std::move(fileName))
184 , mProjectName(
std::move(projectName))
185 , mIsPublic(isPublic)
186 , mCompletedCallback(
std::move(completedCallback))
187 , mProgressCallback(
std::move(progressCallback))
213 using Clock = std::chrono::steady_clock;
226 if (!mAuthToken.empty())
232 if (!language.empty())
241 std::lock_guard<std::mutex> lock(mStatusMutex);
245 std::lock_guard<std::mutex> callbacksLock(mCallbacksMutex);
247 if (mCompletedCallback)
253 mProgressCallback = {};
254 mCompletedCallback = {};
260 std::lock_guard<std::mutex> lock(mStatusMutex);
264 std::lock_guard<std::mutex> callbacksLock(mCallbacksMutex);
266 if (mCompletedCallback)
268 const auto uploadURL =
278 mProgressCallback = {};
279 mCompletedCallback = {};
294 mAuthToken = std::string(authToken);
295 SetRequiredHeaders(request);
299 std::lock_guard<std::mutex> lock(mStatusMutex);
306 request, payload.data(), payload.size());
308 mActiveResponse = response;
310 response->setRequestFinishedCallback(
311 [response, sharedThis = shared_from_this(),
this](
auto) {
312 auto responseCode = response->getHTTPCode();
314 if (responseCode == 201)
316 HandleUploadPolicy(response->readAll<std::string>());
318 else if (responseCode == 401)
322 response->readAll<std::string>());
324 else if (responseCode == 422)
328 response->readAll<std::string>());
334 response->readAll<std::string>());
343 rapidjson::Document document;
344 document.Parse(uploadPolicyJSON.data(), uploadPolicyJSON.length());
347 !document.HasMember(
"url") || !document.HasMember(
"success") ||
348 !document.HasMember(
"fail") || !document.HasMember(
"progress"))
357 auto form = std::make_unique<MultipartData>();
359 if (document.HasMember(
"fields"))
361 const auto& fields = document[
"fields"];
363 for (
auto it = fields.MemberBegin(); it != fields.MemberEnd(); ++it)
364 form->Add(it->name.GetString(), it->value.GetString());
367 const auto fileField =
368 document.HasMember(
"field") ? document[
"field"].GetString() :
"file";
370 const wxFileName
name { mFileName };
388 const auto url = document[
"url"].GetString();
390 mSuccessUrl = document[
"success"].GetString();
391 mFailureUrl = document[
"fail"].GetString();
392 mProgressUrl = document[
"progress"].GetString();
394 if (document.HasMember(
"extra"))
396 const auto& extra = document[
"extra"];
398 mAudioID = extra[
"audio"][
"id"].GetString();
399 mAudioSlug = extra[
"audio"][
"slug"].GetString();
401 if (extra.HasMember(
"token"))
402 mUploadToken = extra[
"token"].GetString();
404 mUserName = extra[
"audio"][
"username"].GetString();
407 const auto encType = document.HasMember(
"enctype") ?
408 document[
"enctype"].GetString() :
409 "multipart/form-data";
418 std::lock_guard<std::mutex> lock(mStatusMutex);
426 mActiveResponse = response;
428 response->setRequestFinishedCallback(
429 [response, sharedThis = shared_from_this(),
this](
auto)
431 HandleS3UploadCompleted(response);
434 response->setUploadProgressCallback(
435 [response, sharedThis = shared_from_this(),
436 this](
auto current,
auto total)
437 { HandleUploadProgress(current, total); });
443 std::lock_guard<std::mutex> callbacksLock(mCallbacksMutex);
445 if (mProgressCallback)
446 mProgressCallback(current, total);
449 const auto now = Clock::now();
453 mLastProgressReportTime = now;
465 std::lock_guard<std::mutex> lock(mStatusMutex);
471 request, payload.data(), payload.size());
473 response->setRequestFinishedCallback([response](
auto) {});
481 const auto responseCode = response->getHTTPCode();
484 responseCode == 200 || responseCode == 201 || responseCode == 204;
486 Request request(success ? mSuccessUrl : mFailureUrl);
487 SetRequiredHeaders(request);
489 std::lock_guard<std::mutex> lock(mStatusMutex);
497 mActiveResponse = finalResponse;
499 finalResponse->setRequestFinishedCallback(
500 [finalResponse, sharedThis = shared_from_this(),
this, success](
auto)
502 const auto httpCode = finalResponse->getHTTPCode();
503 if (success && httpCode >= 200 && httpCode < 300)
511 finalResponse->readAll<std::string>());
517 std::lock_guard<std::mutex> lock(mStatusMutex);
524 std::lock_guard<std::mutex> lock(mStatusMutex);
532 if (
auto activeResponse = mActiveResponse.lock())
533 activeResponse->abort();
536 std::lock_guard<std::mutex> callbacksLock(mCallbacksMutex);
538 if (mCompletedCallback)
541 mCompletedCallback = {};
542 mProgressCallback = {};
552 auto url = mServiceConfig.
GetAPIUrl(
"/audio");
553 url +=
"/" + mAudioID +
"?token=" + mUploadToken;
558 response->setRequestFinishedCallback(
568 : mServiceConfig(config), mOAuthService(service)
573 const wxString& fileName,
const wxString& projectName,
bool isPublic,
576 if (!wxFileExists(fileName))
578 if (completedCallback)
585 auto operation = std::make_shared<AudiocomUploadOperation>(
587 std::move(completedCallback), std::move(progressCallback));
590 { operation->InitiateUpload(authToken); });
598 std::shared_ptr<UploadOperation> operation)
599 : mOperation(
std::move(operation))
610UploadOperationHandle::operator bool() const noexcept
612 return mOperation !=
nullptr;
624 if (!wxDirExists(tempPath))
633 tempPath,
XO(
"Cannot proceed to upload.")))
636 return tempPath +
"/cloud/";
644 if (!wxDirExists(tempPath))
649 wxDir::GetAllFiles(tempPath, &files, {}, wxDIR_FILES);
651 for (
const auto& file : files)
Declare abstract class AudacityException, some often-used subclasses, and GuardedCall.
Declare functions to perform UTF-8 to std::wstring conversions.
const TranslatableString name
Declare an interface for HTTP response.
Declare a class for performing HTTP requests.
Declare a class for constructing HTTP requests.
Subscription Subscribe(Callback callback)
Connect a callback to the Publisher; later-connected are called earlier.
Request & setHeader(const std::string &name, std::string value)
Service responsible for OAuth authentication against the audio.com service.
void ValidateAuth(std::function< void(std::string_view)> completedHandler)
Attempt to authorize the user.
Configuration for the audio.com.
std::string GetDownloadMime() const
std::string GetAcceptLanguageValue() const
Returns the preferred language.
std::string GetAPIUrl(std::string_view apiURI) const
Helper to construct the full URLs for the API.
std::chrono::milliseconds GetProgressCallbackTimeout() const
Timeout between progress callbacks.
std::string GetAudioURL(std::string_view userSlug, std::string_view audioSlug) const
Helper to construct the page URL for the authorised upload.
std::string GetFinishUploadPage(std::string_view audioID, std::string_view token) const
Helper to construct the page URL for the anonymous upload last stage.
A unique_ptr like class that holds a pointer to UploadOperation.
UploadOperationHandle()=default
UploadOperation * operator->() const noexcept
std::shared_ptr< UploadOperation > mOperation
Class used to track the upload operation.
virtual ~UploadOperation()
std::function< void(uint64_t current, uint64_t total)> ProgressCallback
OAuthService & mOAuthService
UploadOperationHandle Upload(const wxString &fileName, const wxString &projectName, bool isPublic, CompletedCallback completedCallback, ProgressCallback progressCallback)
Uploads the file to audio.com.
const ServiceConfig & mServiceConfig
UploadService(const ServiceConfig &config, OAuthService &service)
std::function< void(const UploadOperationCompleted &)> CompletedCallback
FILES_API bool WritableLocationCheck(const FilePath &path, const TranslatableString &message)
Check location on writable access and return true if checked successfully.
FILES_API const FilePath & DefaultTempDir()
FILES_API Observer::Publisher< FilePath > & GetTempPathObserver()
FrameStatistics & GetInstance() noexcept
const std::string ApplicationJson
std::string ToUTF8(const std::wstring &wstr)
std::string GetProgressPayload(uint64_t current, uint64_t total)
UploadFailedPayload ParseUploadFailedMessage(const std::string &payloadText)
std::string_view DeduceMimeType(const wxString &ext)
const auto tempChangedSubscription
std::string GetUploadRequestPayload(const wxString &filePath, const wxString &projectName, bool isPublic)
wxString GetUploadTempPath()
const ServiceConfig & GetServiceConfig()
Returns the instance of the ServiceConfig.
This structure represents an upload error as returned by the server.
std::vector< AdditionalError > additionalErrors
Result
Result of the upload.
@ FileNotFound
Specified file is not found.
@ InvalidData
audio.com has failed to understand what Audacity wants
@ Success
Upload was successful.
@ Aborted
Upload was aborted by the user.
@ UnexpectedResponse
Audacity has failed to understand audio.com response.
@ UploadFailed
Upload failed for some other reason.
@ Unauthorized
Authorization is required.
This structure represents the payload associated with successful upload.
void HandleS3UploadCompleted(std::shared_ptr< audacity::network_manager::IResponse > response)
AudiocomUploadOperation(const ServiceConfig &serviceConfig, wxString fileName, wxString projectName, bool isPublic, UploadService::CompletedCallback completedCallback, UploadService::ProgressCallback progressCallback)
const ServiceConfig & mServiceConfig
void Abort() override
Abort the upload, if running.
UploadService::ProgressCallback mProgressCallback
void SetRequiredHeaders(audacity::network_manager::Request &request) const
UploadService::CompletedCallback mCompletedCallback
std::mutex mCallbacksMutex
void HandleUploadProgress(uint64_t current, uint64_t total)
const wxString mProjectName
void FailPromise(UploadOperationCompleted::Result result, std::string errorMessage)
void DiscardResult() override
Clock::time_point mLastProgressReportTime
bool IsCompleted() override
Returns true if the upload is finished.
std::chrono::steady_clock Clock
std::weak_ptr< audacity::network_manager::IResponse > mActiveResponse
void HandleUploadPolicy(std::string uploadPolicyJSON)
void InitiateUpload(std::string_view authToken)