CLOUD: JANITORIAL: Fix code formatting

This commit is contained in:
Eugene Sandulenko 2016-07-22 15:38:24 +03:00 committed by Alexander Tkachev
parent cccfe7c247
commit d57fca4665
46 changed files with 874 additions and 442 deletions

View file

@ -57,16 +57,17 @@ BoxStorage::BoxStorage(Common::String accessToken, Common::String refreshToken):
BoxStorage::BoxStorage(Common::String code) {
getAccessToken(
new Common::Callback<BoxStorage, BoolResponse>(this, &BoxStorage::codeFlowComplete),
new Common::Callback<BoxStorage, Networking::ErrorResponse>(this, &BoxStorage::codeFlowFailed),
code
new Common::Callback<BoxStorage, BoolResponse>(this, &BoxStorage::codeFlowComplete),
new Common::Callback<BoxStorage, Networking::ErrorResponse>(this, &BoxStorage::codeFlowFailed),
code
);
}
BoxStorage::~BoxStorage() {}
void BoxStorage::getAccessToken(BoolCallback callback, Networking::ErrorCallback errorCallback, Common::String code) {
if (!KEY || !SECRET) loadKeyAndSecret();
if (!KEY || !SECRET)
loadKeyAndSecret();
bool codeFlow = (code != "");
if (!codeFlow && _refreshToken == "") {
@ -76,7 +77,9 @@ void BoxStorage::getAccessToken(BoolCallback callback, Networking::ErrorCallback
}
Networking::JsonCallback innerCallback = new Common::CallbackBridge<BoxStorage, BoolResponse, Networking::JsonResponse>(this, &BoxStorage::tokenRefreshed, callback);
if (errorCallback == nullptr) errorCallback = getErrorPrintingCallback();
if (errorCallback == nullptr)
errorCallback = getErrorPrintingCallback();
Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(innerCallback, errorCallback, "https://api.box.com/oauth2/token");
if (codeFlow) {
request->addPostField("grant_type=authorization_code");
@ -109,12 +112,14 @@ void BoxStorage::tokenRefreshed(BoolCallback callback, Networking::JsonResponse
if (!result.contains("access_token") || !result.contains("refresh_token")) {
warning("Bad response, no token passed");
debug("%s", json->stringify().c_str());
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
} else {
_token = result.getVal("access_token")->asString();
_refreshToken = result.getVal("refresh_token")->asString();
CloudMan.save(); //ask CloudManager to save our new refreshToken
if (callback) (*callback)(BoolResponse(nullptr, true));
if (callback)
(*callback)(BoolResponse(nullptr, true));
}
delete json;
}
@ -190,8 +195,10 @@ void BoxStorage::infoInnerCallback(StorageInfoCallback outerCallback, Networking
}
Networking::Request *BoxStorage::listDirectoryById(Common::String id, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!callback) callback = getPrintFilesCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = getPrintFilesCallback();
return addRequest(new BoxListDirectoryByIdRequest(this, id, callback, errorCallback));
}
@ -213,7 +220,8 @@ void BoxStorage::createDirectoryInnerCallback(BoolCallback outerCallback, Networ
}
Networking::Request *BoxStorage::createDirectoryWithParentId(Common::String parentId, Common::String name, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
Common::String url = "https://api.box.com/2.0/folders";
Networking::JsonCallback innerCallback = new Common::CallbackBridge<BoxStorage, BoolResponse, Networking::JsonResponse>(this, &BoxStorage::createDirectoryInnerCallback, callback);
@ -235,13 +243,15 @@ Networking::Request *BoxStorage::createDirectoryWithParentId(Common::String pare
}
Networking::Request *BoxStorage::upload(Common::String remotePath, Common::String localPath, UploadCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new BoxUploadRequest(this, remotePath, localPath, callback, errorCallback));
}
Networking::Request *BoxStorage::upload(Common::String path, Common::SeekableReadStream *contents, UploadCallback callback, Networking::ErrorCallback errorCallback) {
warning("BoxStorage::upload(ReadStream) not implemented");
if (errorCallback) (*errorCallback)(Networking::ErrorResponse(nullptr, false, true, "BoxStorage::upload(ReadStream) not implemented", -1));
if (errorCallback)
(*errorCallback)(Networking::ErrorResponse(nullptr, false, true, "BoxStorage::upload(ReadStream) not implemented", -1));
delete callback;
delete errorCallback;
return nullptr;

View file

@ -41,13 +41,15 @@ BoxUploadRequest::BoxUploadRequest(BoxStorage *storage, Common::String path, Com
BoxUploadRequest::~BoxUploadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _uploadCallback;
}
void BoxUploadRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_resolvedId = ""; //used to update file contents
_parentId = ""; //used to create file within parent directory
_ignoreCallback = false;
@ -101,7 +103,8 @@ void BoxUploadRequest::upload() {
}
Common::String url = "https://upload.box.com/api/2.0/files";
if (_resolvedId != "") url += "/" + _resolvedId;
if (_resolvedId != "")
url += "/" + _resolvedId;
url += "/content";
Networking::JsonCallback callback = new Common::Callback<BoxUploadRequest, Networking::JsonResponse>(this, &BoxUploadRequest::uploadedCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<BoxUploadRequest, Networking::ErrorResponse>(this, &BoxUploadRequest::notUploadedCallback);
@ -174,11 +177,11 @@ void BoxUploadRequest::uploadedCallback(Networking::JsonResponse response) {
//TODO: check errors
/*
if (object.contains("error")) {
warning("Box returned error: %s", json->stringify(true).c_str());
delete json;
error.response = json->stringify(true);
finishError(error);
return;
warning("Box returned error: %s", json->stringify(true).c_str());
delete json;
error.response = json->stringify(true);
finishError(error);
return;
}
*/
}
@ -205,7 +208,8 @@ void BoxUploadRequest::restart() { start(); }
void BoxUploadRequest::finishUpload(StorageFile file) {
Request::finishSuccess();
if (_uploadCallback) (*_uploadCallback)(Storage::UploadResponse(this, file));
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace Box

View file

@ -112,7 +112,8 @@ void CloudManager::init() {
void CloudManager::save() {
for (uint32 i = 0; i < _storages.size(); ++i) {
if (i == kStorageNoneId) continue;
if (i == kStorageNoneId)
continue;
Common::String name = getStorageConfigName(i);
ConfMan.set(kStoragePrefix + name + "_username", _storages[i].username, ConfMan.kCloudDomain);
ConfMan.set(kStoragePrefix + name + "_lastSync", _storages[i].lastSyncDate, ConfMan.kCloudDomain);
@ -127,12 +128,16 @@ void CloudManager::save() {
void CloudManager::replaceStorage(Storage *storage, uint32 index) {
freeStorages();
if (!storage) error("CloudManager::replaceStorage: NULL storage passed");
if (index >= kStorageTotal) error("CloudManager::replaceStorage: invalid index passed");
if (!storage)
error("CloudManager::replaceStorage: NULL storage passed");
if (index >= kStorageTotal)
error("CloudManager::replaceStorage: invalid index passed");
if (_activeStorage != nullptr && _activeStorage->isWorking()) {
warning("CloudManager::replaceStorage: replacing Storage while the other is working");
if (_activeStorage->isDownloading()) _activeStorage->cancelDownload();
if (_activeStorage->isSyncing()) _activeStorage->cancelSync();
if (_activeStorage->isDownloading())
_activeStorage->cancelDownload();
if (_activeStorage->isSyncing())
_activeStorage->cancelSync();
removeStorage(_activeStorage);
} else {
delete _activeStorage;
@ -161,7 +166,8 @@ void CloudManager::freeStorages() {
}
void CloudManager::passNoStorageConnected(Networking::ErrorCallback errorCallback) const {
if (errorCallback == nullptr) return;
if (errorCallback == nullptr)
return;
(*errorCallback)(Networking::ErrorResponse(nullptr, false, true, "No Storage connected!", -1));
}
@ -200,35 +206,42 @@ bool CloudManager::switchStorage(uint32 index) {
}
Common::String CloudManager::getStorageUsername(uint32 index) {
if (index >= _storages.size()) return "";
if (index >= _storages.size())
return "";
return _storages[index].username;
}
uint64 CloudManager::getStorageUsedSpace(uint32 index) {
if (index >= _storages.size()) return 0;
if (index >= _storages.size())
return 0;
return _storages[index].usedBytes;
}
Common::String CloudManager::getStorageLastSync(uint32 index) {
if (index >= _storages.size()) return "";
if (index == _currentStorageIndex && isSyncing()) return "";
if (index >= _storages.size())
return "";
if (index == _currentStorageIndex && isSyncing())
return "";
return _storages[index].lastSyncDate;
}
void CloudManager::setStorageUsername(uint32 index, Common::String name) {
if (index >= _storages.size()) return;
if (index >= _storages.size())
return;
_storages[index].username = name;
save();
}
void CloudManager::setStorageUsedSpace(uint32 index, uint64 used) {
if (index >= _storages.size()) return;
if (index >= _storages.size())
return;
_storages[index].usedBytes = used;
save();
}
void CloudManager::setStorageLastSync(uint32 index, Common::String date) {
if (index >= _storages.size()) return;
if (index >= _storages.size())
return;
_storages[index].lastSyncDate = date;
save();
}
@ -238,10 +251,18 @@ void CloudManager::connectStorage(uint32 index, Common::String code) {
Storage *storage = nullptr;
switch (index) {
case kStorageDropboxId: storage = new Dropbox::DropboxStorage(code); break;
case kStorageOneDriveId: storage = new OneDrive::OneDriveStorage(code); break;
case kStorageGoogleDriveId: storage = new GoogleDrive::GoogleDriveStorage(code); break;
case kStorageBoxId: storage = new Box::BoxStorage(code); break;
case kStorageDropboxId:
storage = new Dropbox::DropboxStorage(code);
break;
case kStorageOneDriveId:
storage = new OneDrive::OneDriveStorage(code);
break;
case kStorageGoogleDriveId:
storage = new GoogleDrive::GoogleDriveStorage(code);
break;
case kStorageBoxId:
storage = new Box::BoxStorage(code);
break;
}
// in these constructors Storages request token using the passed code
// when the token is received, they call replaceStorage()
@ -251,8 +272,9 @@ void CloudManager::connectStorage(uint32 index, Common::String code) {
Networking::Request *CloudManager::listDirectory(Common::String path, Storage::ListDirectoryCallback callback, Networking::ErrorCallback errorCallback, bool recursive) {
Storage *storage = getCurrentStorage();
if (storage) return storage->listDirectory(path, callback, errorCallback, recursive);
else {
if (storage) {
return storage->listDirectory(path, callback, errorCallback, recursive);
} else {
passNoStorageConnected(errorCallback);
delete callback;
delete errorCallback;
@ -262,8 +284,9 @@ Networking::Request *CloudManager::listDirectory(Common::String path, Storage::L
Networking::Request *CloudManager::downloadFolder(Common::String remotePath, Common::String localPath, Storage::FileArrayCallback callback, Networking::ErrorCallback errorCallback, bool recursive) {
Storage *storage = getCurrentStorage();
if (storage) return storage->downloadFolder(remotePath, localPath, callback, errorCallback, recursive);
else {
if (storage) {
return storage->downloadFolder(remotePath, localPath, callback, errorCallback, recursive);
} else {
passNoStorageConnected(errorCallback);
delete callback;
delete errorCallback;
@ -273,8 +296,9 @@ Networking::Request *CloudManager::downloadFolder(Common::String remotePath, Com
Networking::Request *CloudManager::info(Storage::StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
Storage *storage = getCurrentStorage();
if (storage) return storage->info(callback, errorCallback);
else {
if (storage) {
return storage->info(callback, errorCallback);
} else {
passNoStorageConnected(errorCallback);
delete callback;
delete errorCallback;
@ -284,7 +308,8 @@ Networking::Request *CloudManager::info(Storage::StorageInfoCallback callback, N
Common::String CloudManager::savesDirectoryPath() {
Storage *storage = getCurrentStorage();
if (storage) return storage->savesDirectoryPath();
if (storage)
return storage->savesDirectoryPath();
return "";
}
@ -303,7 +328,8 @@ SavesSyncRequest *CloudManager::syncSaves(Storage::BoolCallback callback, Networ
bool CloudManager::isWorking() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->isWorking();
if (storage)
return storage->isWorking();
return false;
}
@ -319,95 +345,111 @@ bool CloudManager::couldUseLocalServer() {
bool CloudManager::isSyncing() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->isSyncing();
if (storage)
return storage->isSyncing();
return false;
}
double CloudManager::getSyncDownloadingProgress() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getSyncDownloadingProgress();
if (storage)
return storage->getSyncDownloadingProgress();
return 1;
}
double CloudManager::getSyncProgress() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getSyncProgress();
if (storage)
return storage->getSyncProgress();
return 1;
}
Common::Array<Common::String> CloudManager::getSyncingFiles() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getSyncingFiles();
if (storage)
return storage->getSyncingFiles();
return Common::Array<Common::String>();
}
void CloudManager::cancelSync() const {
Storage *storage = getCurrentStorage();
if (storage) storage->cancelSync();
if (storage)
storage->cancelSync();
}
void CloudManager::setSyncTarget(GUI::CommandReceiver *target) const {
Storage *storage = getCurrentStorage();
if (storage) storage->setSyncTarget(target);
if (storage)
storage->setSyncTarget(target);
}
///// DownloadFolderRequest-related /////
bool CloudManager::startDownload(Common::String remotePath, Common::String localPath) const {
Storage *storage = getCurrentStorage();
if (storage) return storage->startDownload(remotePath, localPath);
if (storage)
return storage->startDownload(remotePath, localPath);
return false;
}
void CloudManager::cancelDownload() const {
Storage *storage = getCurrentStorage();
if (storage) storage->cancelDownload();
if (storage)
storage->cancelDownload();
}
void CloudManager::setDownloadTarget(GUI::CommandReceiver *target) const {
Storage *storage = getCurrentStorage();
if (storage) storage->setDownloadTarget(target);
if (storage)
storage->setDownloadTarget(target);
}
bool CloudManager::isDownloading() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->isDownloading();
if (storage)
return storage->isDownloading();
return false;
}
double CloudManager::getDownloadingProgress() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadingProgress();
if (storage)
return storage->getDownloadingProgress();
return 1;
}
uint64 CloudManager::getDownloadBytesNumber() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadBytesNumber();
if (storage)
return storage->getDownloadBytesNumber();
return 0;
}
uint64 CloudManager::getDownloadTotalBytesNumber() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadTotalBytesNumber();
if (storage)
return storage->getDownloadTotalBytesNumber();
return 0;
}
uint64 CloudManager::getDownloadSpeed() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadSpeed();
if (storage)
return storage->getDownloadSpeed();
return 0;
}
Common::String CloudManager::getDownloadRemoteDirectory() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadRemoteDirectory();
if (storage)
return storage->getDownloadRemoteDirectory();
return "";
}
Common::String CloudManager::getDownloadLocalDirectory() const {
Storage *storage = getCurrentStorage();
if (storage) return storage->getDownloadLocalDirectory();
if (storage)
return storage->getDownloadLocalDirectory();
return "";
}

View file

@ -34,7 +34,8 @@ DownloadRequest::DownloadRequest(Storage *storage, Storage::BoolCallback callbac
DownloadRequest::~DownloadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
delete _localFile;
delete[] _buffer;
@ -42,7 +43,8 @@ DownloadRequest::~DownloadRequest() {
void DownloadRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_remoteFileStream = nullptr;
//TODO: add some way to reopen DumpFile, so DownloadRequest could be restarted
_ignoreCallback = false;
@ -56,13 +58,15 @@ void DownloadRequest::start() {
void DownloadRequest::streamCallback(Networking::NetworkReadStreamResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
_remoteFileStream = (Networking::NetworkReadStream *)response.value;
}
void DownloadRequest::streamErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -113,11 +117,13 @@ void DownloadRequest::restart() {
void DownloadRequest::finishDownload(bool success) {
Request::finishSuccess();
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
void DownloadRequest::finishError(Networking::ErrorResponse error) {
if (_localFile) _localFile->close();
if (_localFile)
_localFile->close();
Request::finishError(error);
}

View file

@ -38,13 +38,15 @@ DropboxCreateDirectoryRequest::DropboxCreateDirectoryRequest(Common::String toke
DropboxCreateDirectoryRequest::~DropboxCreateDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void DropboxCreateDirectoryRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_ignoreCallback = false;
Networking::JsonCallback innerCallback = new Common::Callback<DropboxCreateDirectoryRequest, Networking::JsonResponse>(this, &DropboxCreateDirectoryRequest::responseCallback);
@ -82,8 +84,9 @@ void DropboxCreateDirectoryRequest::responseCallback(Networking::JsonResponse re
}
Common::JSONObject info = json->asObject();
if (info.contains("id")) finishCreation(true);
else {
if (info.contains("id")) {
finishCreation(true);
} else {
if (info.contains("error_summary") && info.getVal("error_summary")->isString()) {
Common::String summary = info.getVal("error_summary")->asString();
if (summary.contains("path") && summary.contains("conflict") && summary.contains("folder")) {
@ -101,8 +104,10 @@ void DropboxCreateDirectoryRequest::responseCallback(Networking::JsonResponse re
void DropboxCreateDirectoryRequest::errorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -114,7 +119,8 @@ Common::String DropboxCreateDirectoryRequest::date() const { return _date; }
void DropboxCreateDirectoryRequest::finishCreation(bool success) {
Request::finishSuccess();
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
} // End of namespace Dropbox

View file

@ -39,13 +39,15 @@ DropboxInfoRequest::DropboxInfoRequest(Common::String token, Storage::StorageInf
DropboxInfoRequest::~DropboxInfoRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _infoCallback;
}
void DropboxInfoRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_ignoreCallback = false;
Networking::JsonCallback innerCallback = new Common::Callback<DropboxInfoRequest, Networking::JsonResponse>(this, &DropboxInfoRequest::userResponseCallback);
@ -136,7 +138,8 @@ void DropboxInfoRequest::restart() { start(); }
void DropboxInfoRequest::finishInfo(StorageInfo info) {
Request::finishSuccess();
if (_infoCallback) (*_infoCallback)(Storage::StorageInfoResponse(this, info));
if (_infoCallback)
(*_infoCallback)(Storage::StorageInfoResponse(this, info));
}
} // End of namespace Dropbox

View file

@ -39,13 +39,15 @@ DropboxListDirectoryRequest::DropboxListDirectoryRequest(Common::String token, C
DropboxListDirectoryRequest::~DropboxListDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void DropboxListDirectoryRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_files.clear();
_ignoreCallback = false;
@ -69,9 +71,11 @@ void DropboxListDirectoryRequest::start() {
void DropboxListDirectoryRequest::responseCallback(Networking::JsonResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
if (response.request) _date = response.request->date();
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -138,8 +142,10 @@ void DropboxListDirectoryRequest::responseCallback(Networking::JsonResponse resp
void DropboxListDirectoryRequest::errorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -151,7 +157,8 @@ Common::String DropboxListDirectoryRequest::date() const { return _date; }
void DropboxListDirectoryRequest::finishListing(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback) (*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace Dropbox

View file

@ -61,7 +61,8 @@ DropboxStorage::DropboxStorage(Common::String code) {
DropboxStorage::~DropboxStorage() {}
void DropboxStorage::getAccessToken(Common::String code) {
if (!KEY || !SECRET) loadKeyAndSecret();
if (!KEY || !SECRET)
loadKeyAndSecret();
Networking::JsonCallback callback = new Common::Callback<DropboxStorage, Networking::JsonResponse>(this, &DropboxStorage::codeFlowComplete);
Networking::ErrorCallback errorCallback = new Common::Callback<DropboxStorage, Networking::ErrorResponse>(this, &DropboxStorage::codeFlowFailed);
Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(callback, errorCallback, "https://api.dropboxapi.com/oauth2/token");
@ -134,17 +135,20 @@ Networking::Request *DropboxStorage::streamFileById(Common::String path, Network
request->addHeader("Content-Type: "); //required to be empty (as we do POST, it's usually app/form-url-encoded)
Networking::NetworkReadStreamResponse response = request->execute();
if (callback) (*callback)(response);
if (callback)
(*callback)(response);
return response.request; // no leak here, response.request == request
}
Networking::Request *DropboxStorage::createDirectory(Common::String path, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new DropboxCreateDirectoryRequest(_token, path, callback, errorCallback));
}
Networking::Request *DropboxStorage::info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new DropboxInfoRequest(_token, callback, errorCallback));
}

View file

@ -40,14 +40,16 @@ DropboxUploadRequest::DropboxUploadRequest(Common::String token, Common::String
DropboxUploadRequest::~DropboxUploadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _contentsStream;
delete _uploadCallback;
}
void DropboxUploadRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
if (!_contentsStream) {
warning("DropboxUploadRequest: cannot start because stream is invalid");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
@ -120,7 +122,8 @@ void DropboxUploadRequest::uploadNextPart() {
void DropboxUploadRequest::partUploadedCallback(Networking::JsonResponse response) {
debug(9, "partUploadedCallback");
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "", -1);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -179,7 +182,8 @@ void DropboxUploadRequest::partUploadedCallback(Networking::JsonResponse respons
void DropboxUploadRequest::partUploadedErrorCallback(Networking::ErrorResponse error) {
debug("partUploadedErrorCallback");
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -189,7 +193,8 @@ void DropboxUploadRequest::restart() { start(); }
void DropboxUploadRequest::finishUpload(StorageFile file) {
Request::finishSuccess();
if (_uploadCallback) (*_uploadCallback)(Storage::UploadResponse(this, file));
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace Dropbox

View file

@ -39,14 +39,16 @@ FolderDownloadRequest::FolderDownloadRequest(Storage *storage, Storage::FileArra
FolderDownloadRequest::~FolderDownloadRequest() {
sendCommand(GUI::kDownloadEndedCmd, 0);
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _fileArrayCallback;
}
void FolderDownloadRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_currentFile = StorageFile();
_pendingFiles.clear();
_failedFiles.clear();
@ -65,7 +67,8 @@ void FolderDownloadRequest::start() {
void FolderDownloadRequest::directoryListedCallback(Storage::ListDirectoryResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
_pendingFiles = response.value;
// remove all directories
@ -84,13 +87,15 @@ void FolderDownloadRequest::directoryListedCallback(Storage::ListDirectoryRespon
void FolderDownloadRequest::directoryListedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
void FolderDownloadRequest::fileDownloadedCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
if (!response.value) _failedFiles.push_back(_currentFile);
_downloadedBytes += _currentFile.size();
downloadNextFile();
@ -98,7 +103,8 @@ void FolderDownloadRequest::fileDownloadedCallback(Storage::BoolResponse respons
void FolderDownloadRequest::fileDownloadedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
fileDownloadedCallback(Storage::BoolResponse(error.request, false));
}
@ -153,23 +159,28 @@ void FolderDownloadRequest::restart() { start(); }
void FolderDownloadRequest::finishDownload(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_fileArrayCallback) (*_fileArrayCallback)(Storage::FileArrayResponse(this, files));
if (_fileArrayCallback)
(*_fileArrayCallback)(Storage::FileArrayResponse(this, files));
}
double FolderDownloadRequest::getProgress() const {
if (_totalFiles == 0 || _totalBytes == 0) return 0;
if (_totalFiles == 0 || _totalBytes == 0)
return 0;
return (double)getDownloadedBytes() / (double)getTotalBytesToDownload();
}
uint64 FolderDownloadRequest::getDownloadedBytes() const {
if (_totalFiles == 0) return 0;
if (_totalFiles == 0)
return 0;
double currentFileProgress = 0;
DownloadRequest *downloadRequest = dynamic_cast<DownloadRequest *>(_workingRequest);
if (downloadRequest != nullptr) currentFileProgress = downloadRequest->getProgress();
else {
if (downloadRequest != nullptr) {
currentFileProgress = downloadRequest->getProgress();
} else {
Id::IdDownloadRequest *idDownloadRequest = dynamic_cast<Id::IdDownloadRequest *>(_workingRequest);
if (idDownloadRequest != nullptr) currentFileProgress = idDownloadRequest->getProgress();
if (idDownloadRequest != nullptr)
currentFileProgress = idDownloadRequest->getProgress();
}
return _downloadedBytes + (uint64)(currentFileProgress * _currentFile.size());

View file

@ -41,13 +41,15 @@ GoogleDriveListDirectoryByIdRequest::GoogleDriveListDirectoryByIdRequest(GoogleD
GoogleDriveListDirectoryByIdRequest::~GoogleDriveListDirectoryByIdRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void GoogleDriveListDirectoryByIdRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_files.clear();
_ignoreCallback = false;
@ -57,7 +59,8 @@ void GoogleDriveListDirectoryByIdRequest::start() {
void GoogleDriveListDirectoryByIdRequest::makeRequest(Common::String pageToken) {
Common::String url = "https://www.googleapis.com/drive/v3/files?spaces=drive&fields=files%28id,mimeType,modifiedTime,name,size%29,nextPageToken&orderBy=folder,name";
//files(id,mimeType,modifiedTime,name,size),nextPageToken
if (pageToken != "") url += "&pageToken=" + pageToken;
if (pageToken != "")
url += "&pageToken=" + pageToken;
url += "&q=%27" + _requestedId + "%27+in+parents";
Networking::JsonCallback callback = new Common::Callback<GoogleDriveListDirectoryByIdRequest, Networking::JsonResponse>(this, &GoogleDriveListDirectoryByIdRequest::responseCallback);
@ -69,8 +72,10 @@ void GoogleDriveListDirectoryByIdRequest::makeRequest(Common::String pageToken)
void GoogleDriveListDirectoryByIdRequest::responseCallback(Networking::JsonResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -131,8 +136,10 @@ void GoogleDriveListDirectoryByIdRequest::responseCallback(Networking::JsonRespo
void GoogleDriveListDirectoryByIdRequest::errorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -144,7 +151,8 @@ Common::String GoogleDriveListDirectoryByIdRequest::date() const { return _date;
void GoogleDriveListDirectoryByIdRequest::finishListing(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback) (*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace GoogleDrive

View file

@ -57,9 +57,9 @@ GoogleDriveStorage::GoogleDriveStorage(Common::String accessToken, Common::Strin
GoogleDriveStorage::GoogleDriveStorage(Common::String code) {
getAccessToken(
new Common::Callback<GoogleDriveStorage, BoolResponse>(this, &GoogleDriveStorage::codeFlowComplete),
new Common::Callback<GoogleDriveStorage, Networking::ErrorResponse>(this, &GoogleDriveStorage::codeFlowFailed),
code
new Common::Callback<GoogleDriveStorage, BoolResponse>(this, &GoogleDriveStorage::codeFlowComplete),
new Common::Callback<GoogleDriveStorage, Networking::ErrorResponse>(this, &GoogleDriveStorage::codeFlowFailed),
code
);
}
@ -71,12 +71,14 @@ void GoogleDriveStorage::getAccessToken(BoolCallback callback, Networking::Error
if (!codeFlow && _refreshToken == "") {
warning("GoogleDriveStorage: no refresh token available to get new access token.");
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
return;
}
Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, BoolResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::tokenRefreshed, callback);
if (errorCallback == nullptr) errorCallback = getErrorPrintingCallback();
if (errorCallback == nullptr)
errorCallback = getErrorPrintingCallback();
Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(innerCallback, errorCallback, "https://accounts.google.com/o/oauth2/token"); //TODO
if (codeFlow) {
request->addPostField("code=" + code);
@ -99,7 +101,8 @@ void GoogleDriveStorage::tokenRefreshed(BoolCallback callback, Networking::JsonR
Common::JSONValue *json = response.value;
if (!json) {
warning("GoogleDriveStorage: got NULL instead of JSON");
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
return;
}
@ -107,7 +110,8 @@ void GoogleDriveStorage::tokenRefreshed(BoolCallback callback, Networking::JsonR
if (!result.contains("access_token")) {
warning("Bad response, no token passed");
debug("%s", json->stringify().c_str());
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
} else {
_token = result.getVal("access_token")->asString();
if (!result.contains("refresh_token"))
@ -115,7 +119,8 @@ void GoogleDriveStorage::tokenRefreshed(BoolCallback callback, Networking::JsonR
else
_refreshToken = result.getVal("refresh_token")->asString();
CloudMan.save(); //ask CloudManager to save our new refreshToken
if (callback) (*callback)(BoolResponse(nullptr, true));
if (callback)
(*callback)(BoolResponse(nullptr, true));
}
delete json;
}
@ -206,8 +211,10 @@ void GoogleDriveStorage::createDirectoryInnerCallback(BoolCallback outerCallback
}
Networking::Request *GoogleDriveStorage::listDirectoryById(Common::String id, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!callback) callback = new Common::Callback<GoogleDriveStorage, FileArrayResponse>(this, &GoogleDriveStorage::printFiles);
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = new Common::Callback<GoogleDriveStorage, FileArrayResponse>(this, &GoogleDriveStorage::printFiles);
return addRequest(new GoogleDriveListDirectoryByIdRequest(this, id, callback, errorCallback));
}
@ -236,7 +243,8 @@ void GoogleDriveStorage::printInfo(StorageInfoResponse response) {
}
Networking::Request *GoogleDriveStorage::createDirectoryWithParentId(Common::String parentId, Common::String name, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
Common::String url = "https://www.googleapis.com/drive/v3/files";
Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, BoolResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::createDirectoryInnerCallback, callback);
@ -259,7 +267,8 @@ Networking::Request *GoogleDriveStorage::createDirectoryWithParentId(Common::Str
}
Networking::Request *GoogleDriveStorage::info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
if (!callback) callback = new Common::Callback<GoogleDriveStorage, StorageInfoResponse>(this, &GoogleDriveStorage::printInfo);
if (!callback)
callback = new Common::Callback<GoogleDriveStorage, StorageInfoResponse>(this, &GoogleDriveStorage::printInfo);
Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, StorageInfoResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::infoInnerCallback, callback);
Networking::CurlJsonRequest *request = new GoogleDriveTokenRefresher(this, innerCallback, errorCallback, "https://www.googleapis.com/drive/v3/about?fields=storageQuota,user");
request->addHeader("Authorization: Bearer " + _token);

View file

@ -41,14 +41,16 @@ GoogleDriveUploadRequest::GoogleDriveUploadRequest(GoogleDriveStorage *storage,
GoogleDriveUploadRequest::~GoogleDriveUploadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _contentsStream;
delete _uploadCallback;
}
void GoogleDriveUploadRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
if (_contentsStream == nullptr || !_contentsStream->seek(0)) {
warning("GoogleDriveUploadRequest: cannot restart because stream couldn't seek(0)");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
@ -71,14 +73,16 @@ void GoogleDriveUploadRequest::resolveId() {
void GoogleDriveUploadRequest::idResolvedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
_resolvedId = response.value.id();
startUpload();
}
void GoogleDriveUploadRequest::idResolveFailedCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//not resolved => error or no such file
if (error.response.contains("no such file found in its parent directory")) {
@ -108,18 +112,21 @@ void GoogleDriveUploadRequest::startUpload() {
}
Common::String url = "https://www.googleapis.com/upload/drive/v3/files";
if (_resolvedId != "") url += "/" + ConnMan.urlEncode(_resolvedId);
if (_resolvedId != "")
url += "/" + ConnMan.urlEncode(_resolvedId);
url += "?uploadType=resumable&fields=id,mimeType,modifiedTime,name,size";
Networking::JsonCallback callback = new Common::Callback<GoogleDriveUploadRequest, Networking::JsonResponse>(this, &GoogleDriveUploadRequest::startUploadCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<GoogleDriveUploadRequest, Networking::ErrorResponse>(this, &GoogleDriveUploadRequest::startUploadErrorCallback);
Networking::CurlJsonRequest *request = new GoogleDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
request->addHeader("Content-Type: application/json");
if (_resolvedId != "") request->usePatch();
if (_resolvedId != "")
request->usePatch();
Common::JSONObject jsonRequestParameters;
if (_resolvedId != "") jsonRequestParameters.setVal("id", new Common::JSONValue(_resolvedId));
else {
if (_resolvedId != "") {
jsonRequestParameters.setVal("id", new Common::JSONValue(_resolvedId));
} else {
Common::JSONArray parentsArray;
parentsArray.push_back(new Common::JSONValue(_parentId));
jsonRequestParameters.setVal("parents", new Common::JSONValue(parentsArray));
@ -134,7 +141,8 @@ void GoogleDriveUploadRequest::startUpload() {
void GoogleDriveUploadRequest::startUploadCallback(Networking::JsonResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "", -1);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -151,7 +159,8 @@ void GoogleDriveUploadRequest::startUploadCallback(Networking::JsonResponse resp
Common::String result = "";
char c;
for (const char *i = position + 10; c = *i, c != 0; ++i) {
if (c == '\n' || c == '\r') break;
if (c == '\n' || c == '\r')
break;
result += c;
}
_uploadUrl = result;
@ -172,7 +181,8 @@ void GoogleDriveUploadRequest::startUploadCallback(Networking::JsonResponse resp
void GoogleDriveUploadRequest::startUploadErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -198,7 +208,8 @@ void GoogleDriveUploadRequest::uploadNextPart() {
byte *buffer = new byte[UPLOAD_PER_ONE_REQUEST];
uint32 size = _contentsStream->read(buffer, UPLOAD_PER_ONE_REQUEST);
if (size != 0) request->setBuffer(buffer, size);
if (size != 0)
request->setBuffer(buffer, size);
if (_uploadUrl != "") {
if (_contentsStream->pos() == 0)
@ -212,8 +223,10 @@ void GoogleDriveUploadRequest::uploadNextPart() {
bool GoogleDriveUploadRequest::handleHttp308(const Networking::NetworkReadStream *stream) {
//308 Resume Incomplete, with Range: X-Y header
if (!stream) return false;
if (stream->httpResponseCode() != 308) return false; //seriously
if (!stream)
return false;
if (stream->httpResponseCode() != 308)
return false; //seriously
Common::String headers = stream->responseHeaders();
const char *cstr = headers.c_str();
@ -227,7 +240,8 @@ bool GoogleDriveUploadRequest::handleHttp308(const Networking::NetworkReadStream
Common::String result = "";
char c;
for (const char *i = position + needleLength; c = *i, c != 0; ++i) {
if (c == '\n' || c == '\r') break;
if (c == '\n' || c == '\r')
break;
result += c;
}
_serverReceivedBytes = result.asUint64() + 1;
@ -241,7 +255,8 @@ bool GoogleDriveUploadRequest::handleHttp308(const Networking::NetworkReadStream
void GoogleDriveUploadRequest::partUploadedCallback(Networking::JsonResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "", -1);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -303,7 +318,8 @@ void GoogleDriveUploadRequest::partUploadedCallback(Networking::JsonResponse res
void GoogleDriveUploadRequest::partUploadedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)error.request;
if (rq) {
@ -325,7 +341,8 @@ void GoogleDriveUploadRequest::restart() { start(); }
void GoogleDriveUploadRequest::finishUpload(StorageFile file) {
Request::finishSuccess();
if (_uploadCallback) (*_uploadCallback)(Storage::UploadResponse(this, file));
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace GoogleDrive

View file

@ -36,20 +36,23 @@ IdCreateDirectoryRequest::IdCreateDirectoryRequest(IdStorage *storage, Common::S
IdCreateDirectoryRequest::~IdCreateDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void IdCreateDirectoryRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_ignoreCallback = false;
//the only exception when we create parent folder - is when it's ScummVM/ base folder
Common::String prefix = _requestedParentPath;
if (prefix.size() > 7) prefix.erase(7);
if (prefix.size() > 7)
prefix.erase(7);
if (prefix.equalsIgnoreCase("ScummVM")) {
Storage::BoolCallback callback = new Common::Callback<IdCreateDirectoryRequest, Storage::BoolResponse>(this, &IdCreateDirectoryRequest::createdBaseDirectoryCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<IdCreateDirectoryRequest, Networking::ErrorResponse>(this, &IdCreateDirectoryRequest::createdBaseDirectoryErrorCallback);
@ -62,15 +65,19 @@ void IdCreateDirectoryRequest::start() {
void IdCreateDirectoryRequest::createdBaseDirectoryCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
resolveId();
}
void IdCreateDirectoryRequest::createdBaseDirectoryErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -79,15 +86,18 @@ void IdCreateDirectoryRequest::resolveId() {
Storage::UploadCallback innerCallback = new Common::Callback<IdCreateDirectoryRequest, Storage::UploadResponse>(this, &IdCreateDirectoryRequest::idResolvedCallback);
Networking::ErrorCallback innerErrorCallback = new Common::Callback<IdCreateDirectoryRequest, Networking::ErrorResponse>(this, &IdCreateDirectoryRequest::idResolveFailedCallback);
Common::String path = _requestedParentPath;
if (_requestedParentPath != "") path += "/";
if (_requestedParentPath != "")
path += "/";
path += _requestedDirectoryName;
_workingRequest = _storage->resolveFileId(path, innerCallback, innerErrorCallback);
}
void IdCreateDirectoryRequest::idResolvedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
//resolved => folder already exists
finishCreation(false);
@ -95,8 +105,10 @@ void IdCreateDirectoryRequest::idResolvedCallback(Storage::UploadResponse respon
void IdCreateDirectoryRequest::idResolveFailedCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
//not resolved => folder not exists
if (error.response.contains("no such file found in its parent directory")) {
@ -119,15 +131,19 @@ void IdCreateDirectoryRequest::idResolveFailedCallback(Networking::ErrorResponse
void IdCreateDirectoryRequest::createdDirectoryCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
finishCreation(response.value);
}
void IdCreateDirectoryRequest::createdDirectoryErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -139,7 +155,8 @@ Common::String IdCreateDirectoryRequest::date() const { return _date; }
void IdCreateDirectoryRequest::finishCreation(bool success) {
Request::finishSuccess();
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
} // End of namespace Id

View file

@ -35,14 +35,16 @@ IdDownloadRequest::IdDownloadRequest(IdStorage *storage, Common::String remotePa
IdDownloadRequest::~IdDownloadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void IdDownloadRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_ignoreCallback = false;
@ -54,7 +56,8 @@ void IdDownloadRequest::start() {
void IdDownloadRequest::idResolvedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Storage::BoolCallback innerCallback = new Common::Callback<IdDownloadRequest, Storage::BoolResponse>(this, &IdDownloadRequest::downloadCallback);
Networking::ErrorCallback innerErrorCallback = new Common::Callback<IdDownloadRequest, Networking::ErrorResponse>(this, &IdDownloadRequest::downloadErrorCallback);
@ -63,19 +66,22 @@ void IdDownloadRequest::idResolvedCallback(Storage::UploadResponse response) {
void IdDownloadRequest::idResolveFailedCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
void IdDownloadRequest::downloadCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishDownload(response.value);
}
void IdDownloadRequest::downloadErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -85,12 +91,14 @@ void IdDownloadRequest::restart() { start(); }
void IdDownloadRequest::finishDownload(bool success) {
Request::finishSuccess();
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
double IdDownloadRequest::getProgress() const {
DownloadRequest *downloadRequest = dynamic_cast<DownloadRequest *>(_workingRequest);
if (downloadRequest == nullptr) return 0; // resolving id still
if (downloadRequest == nullptr)
return 0; // resolving id still
// id resolve is 10 % and download is the other 90 %
return 0.1 + 0.9 * downloadRequest->getProgress(); // downloading

View file

@ -35,14 +35,16 @@ IdListDirectoryRequest::IdListDirectoryRequest(IdStorage *storage, Common::Strin
IdListDirectoryRequest::~IdListDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void IdListDirectoryRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_files.clear();
_directoriesQueue.clear();
@ -57,8 +59,10 @@ void IdListDirectoryRequest::start() {
void IdListDirectoryRequest::idResolvedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
StorageFile directory = response.value;
directory.setPath(_requestedPath);
@ -68,8 +72,10 @@ void IdListDirectoryRequest::idResolvedCallback(Storage::UploadResponse response
void IdListDirectoryRequest::idResolveErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -89,13 +95,16 @@ void IdListDirectoryRequest::listNextDirectory() {
void IdListDirectoryRequest::listedDirectoryCallback(Storage::FileArrayResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (response.request) _date = response.request->date();
if (_ignoreCallback)
return;
if (response.request)
_date = response.request->date();
for (uint32 i = 0; i < response.value.size(); ++i) {
StorageFile &file = response.value[i];
Common::String path = _currentDirectory.path();
if (path.size() && path.lastChar() != '/' && path.lastChar() != '\\') path += '/';
if (path.size() && path.lastChar() != '/' && path.lastChar() != '\\')
path += '/';
path += file.name();
file.setPath(path);
_files.push_back(file);
@ -109,8 +118,10 @@ void IdListDirectoryRequest::listedDirectoryCallback(Storage::FileArrayResponse
void IdListDirectoryRequest::listedDirectoryErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -122,7 +133,8 @@ Common::String IdListDirectoryRequest::date() const { return _date; }
void IdListDirectoryRequest::finishListing(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback) (*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace Id

View file

@ -35,14 +35,16 @@ IdResolveIdRequest::IdResolveIdRequest(IdStorage *storage, Common::String path,
IdResolveIdRequest::~IdResolveIdRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _uploadCallback;
}
void IdResolveIdRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_currentDirectory = "";
_currentDirectoryId = _storage->getRootDirectoryId();
@ -64,12 +66,15 @@ void IdResolveIdRequest::listNextDirectory(StorageFile fileToReturn) {
void IdResolveIdRequest::listedDirectoryCallback(Storage::FileArrayResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Common::String currentLevelName = _requestedPath;
///debug("'%s'", currentLevelName.c_str());
if (_currentDirectory.size()) currentLevelName.erase(0, _currentDirectory.size());
if (currentLevelName.size() && (currentLevelName[0] == '/' || currentLevelName[0] == '\\')) currentLevelName.erase(0, 1);
if (_currentDirectory.size())
currentLevelName.erase(0, _currentDirectory.size());
if (currentLevelName.size() && (currentLevelName[0] == '/' || currentLevelName[0] == '\\'))
currentLevelName.erase(0, 1);
///debug("'%s'", currentLevelName.c_str());
for (uint32 i = 0; i < currentLevelName.size(); ++i) {
if (currentLevelName[i] == '/' || currentLevelName[i] == '\\') {
@ -80,7 +85,8 @@ void IdResolveIdRequest::listedDirectoryCallback(Storage::FileArrayResponse resp
}
Common::String path = _currentDirectory;
if (path != "") path += "/";
if (path != "")
path += "/";
path += currentLevelName;
bool lastLevel = (path.equalsIgnoreCase(_requestedPath));
@ -90,7 +96,8 @@ void IdResolveIdRequest::listedDirectoryCallback(Storage::FileArrayResponse resp
bool found = false;
for (uint32 i = 0; i < files.size(); ++i) {
if ((files[i].isDirectory() || lastLevel) && files[i].name().equalsIgnoreCase(currentLevelName)) {
if (_currentDirectory != "") _currentDirectory += "/";
if (_currentDirectory != "")
_currentDirectory += "/";
_currentDirectory += files[i].name();
_currentDirectoryId = files[i].id();
///debug("found it! new directory and its id: '%s', '%s'", _currentDirectory.c_str(), _currentDirectoryId.c_str());
@ -101,14 +108,17 @@ void IdResolveIdRequest::listedDirectoryCallback(Storage::FileArrayResponse resp
}
if (!found) {
if (lastLevel) finishError(Networking::ErrorResponse(this, false, true, Common::String("no such file found in its parent directory\n") + _currentDirectoryId, 404));
else finishError(Networking::ErrorResponse(this, false, true, "subdirectory not found", 400));
if (lastLevel)
finishError(Networking::ErrorResponse(this, false, true, Common::String("no such file found in its parent directory\n") + _currentDirectoryId, 404));
else
finishError(Networking::ErrorResponse(this, false, true, "subdirectory not found", 400));
}
}
void IdResolveIdRequest::listedDirectoryErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -118,7 +128,8 @@ void IdResolveIdRequest::restart() { start(); }
void IdResolveIdRequest::finishFile(StorageFile file) {
Request::finishSuccess();
if (_uploadCallback) (*_uploadCallback)(Storage::UploadResponse(this, file));
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace Id

View file

@ -63,20 +63,26 @@ Storage::ListDirectoryCallback IdStorage::getPrintFilesCallback() {
}
Networking::Request *IdStorage::resolveFileId(Common::String path, UploadCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!callback) callback = new Common::Callback<IdStorage, UploadResponse>(this, &IdStorage::printFile);
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = new Common::Callback<IdStorage, UploadResponse>(this, &IdStorage::printFile);
return addRequest(new IdResolveIdRequest(this, path, callback, errorCallback));
}
Networking::Request *IdStorage::listDirectory(Common::String path, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback, bool recursive) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!callback) callback = new Common::Callback<IdStorage, FileArrayResponse>(this, &IdStorage::printFiles);
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = new Common::Callback<IdStorage, FileArrayResponse>(this, &IdStorage::printFiles);
return addRequest(new IdListDirectoryRequest(this, path, callback, errorCallback, recursive));
}
Networking::Request *IdStorage::createDirectory(Common::String path, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!callback) callback = new Common::Callback<IdStorage, BoolResponse>(this, &IdStorage::printBool);
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = new Common::Callback<IdStorage, BoolResponse>(this, &IdStorage::printBool);
//find out the parent path and directory name
Common::String parentPath = "", directoryName = path;

View file

@ -34,14 +34,16 @@ IdStreamFileRequest::IdStreamFileRequest(IdStorage *storage, Common::String path
IdStreamFileRequest::~IdStreamFileRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _streamCallback;
}
void IdStreamFileRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_ignoreCallback = false;
@ -53,7 +55,8 @@ void IdStreamFileRequest::start() {
void IdStreamFileRequest::idResolvedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::NetworkReadStreamCallback innerCallback = new Common::Callback<IdStreamFileRequest, Networking::NetworkReadStreamResponse>(this, &IdStreamFileRequest::streamFileCallback);
Networking::ErrorCallback innerErrorCallback = new Common::Callback<IdStreamFileRequest, Networking::ErrorResponse>(this, &IdStreamFileRequest::streamFileErrorCallback);
@ -62,19 +65,22 @@ void IdStreamFileRequest::idResolvedCallback(Storage::UploadResponse response) {
void IdStreamFileRequest::idResolveFailedCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
void IdStreamFileRequest::streamFileCallback(Networking::NetworkReadStreamResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishStream(response.value);
}
void IdStreamFileRequest::streamFileErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -84,7 +90,8 @@ void IdStreamFileRequest::restart() { start(); }
void IdStreamFileRequest::finishStream(Networking::NetworkReadStream *stream) {
Request::finishSuccess();
if (_streamCallback) (*_streamCallback)(Networking::NetworkReadStreamResponse(this, stream));
if (_streamCallback)
(*_streamCallback)(Networking::NetworkReadStreamResponse(this, stream));
}
} // End of namespace Id

View file

@ -35,7 +35,8 @@ Common::String getSubstring(const Common::String &s, uint32 beginning, uint32 en
int find(const char *cstr, uint32 startPosition, char needle) {
const char *res = strchr(cstr + startPosition, needle);
if (res == nullptr) return -1;
if (res == nullptr)
return -1;
return res - cstr;
}
@ -53,7 +54,8 @@ uint32 convertToTimestamp(const Common::String &iso8601Date) {
int firstColon = find(cstr, tSeparator + 1, ':');
int secondColon = find(cstr, firstColon + 1, ':');
int zSeparator = find(cstr, secondColon + 1, 'Z');
if (zSeparator == -1) zSeparator = find(cstr, secondColon + 1, '-'); // Box's RFC 3339
if (zSeparator == -1)
zSeparator = find(cstr, secondColon + 1, '-'); // Box's RFC 3339
//now note '+1' which means if there ever was '-1' result of find(), we still did a valid find() from 0th char
Common::String year = getSubstring(iso8601Date, 0, firstHyphen);

View file

@ -39,13 +39,15 @@ OneDriveCreateDirectoryRequest::OneDriveCreateDirectoryRequest(OneDriveStorage *
OneDriveCreateDirectoryRequest::~OneDriveCreateDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void OneDriveCreateDirectoryRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_ignoreCallback = false;
Common::String name = _path, parent = _path;
@ -57,13 +59,15 @@ void OneDriveCreateDirectoryRequest::start() {
name.erase(0, i + 1);
break;
}
if (i == 0) break;
if (i == 0)
break;
--i;
}
}
Common::String url = "https://api.onedrive.com/v1.0/drive/special/approot";
if (parent != "") url += ":/" + ConnMan.urlEncode(parent) + ":";
if (parent != "")
url += ":/" + ConnMan.urlEncode(parent) + ":";
url += "/children";
Networking::JsonCallback innerCallback = new Common::Callback<OneDriveCreateDirectoryRequest, Networking::JsonResponse>(this, &OneDriveCreateDirectoryRequest::responseCallback);
Networking::ErrorCallback errorCallback = new Common::Callback<OneDriveCreateDirectoryRequest, Networking::ErrorResponse>(this, &OneDriveCreateDirectoryRequest::errorCallback);
@ -87,7 +91,8 @@ void OneDriveCreateDirectoryRequest::responseCallback(Networking::JsonResponse r
delete json;
return;
}
if (response.request) _date = response.request->date();
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -101,8 +106,9 @@ void OneDriveCreateDirectoryRequest::responseCallback(Networking::JsonResponse r
}
Common::JSONObject info = json->asObject();
if (info.contains("id")) finishCreation(true);
else {
if (info.contains("id")) {
finishCreation(true);
} else {
error.response = json->stringify(true);
finishError(error);
}
@ -112,8 +118,10 @@ void OneDriveCreateDirectoryRequest::responseCallback(Networking::JsonResponse r
void OneDriveCreateDirectoryRequest::errorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -125,7 +133,8 @@ Common::String OneDriveCreateDirectoryRequest::date() const { return _date; }
void OneDriveCreateDirectoryRequest::finishCreation(bool success) {
Request::finishSuccess();
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
} // End of namespace OneDrive

View file

@ -40,14 +40,16 @@ OneDriveListDirectoryRequest::OneDriveListDirectoryRequest(OneDriveStorage *stor
OneDriveListDirectoryRequest::~OneDriveListDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void OneDriveListDirectoryRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_files.clear();
_directoriesQueue.clear();
@ -94,7 +96,8 @@ void OneDriveListDirectoryRequest::listedDirectoryCallback(Networking::JsonRespo
return;
}
if (response.request) _date = response.request->date();
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -139,8 +142,10 @@ void OneDriveListDirectoryRequest::listedDirectoryCallback(Networking::JsonRespo
void OneDriveListDirectoryRequest::listedDirectoryErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (error.request) _date = error.request->date();
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
@ -152,7 +157,8 @@ Common::String OneDriveListDirectoryRequest::date() const { return _date; }
void OneDriveListDirectoryRequest::finishListing(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback) (*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace OneDrive

View file

@ -58,26 +58,29 @@ OneDriveStorage::OneDriveStorage(Common::String accessToken, Common::String user
OneDriveStorage::OneDriveStorage(Common::String code) {
getAccessToken(
new Common::Callback<OneDriveStorage, BoolResponse>(this, &OneDriveStorage::codeFlowComplete),
new Common::Callback<OneDriveStorage, Networking::ErrorResponse>(this, &OneDriveStorage::codeFlowFailed),
code
new Common::Callback<OneDriveStorage, BoolResponse>(this, &OneDriveStorage::codeFlowComplete),
new Common::Callback<OneDriveStorage, Networking::ErrorResponse>(this, &OneDriveStorage::codeFlowFailed),
code
);
}
OneDriveStorage::~OneDriveStorage() {}
void OneDriveStorage::getAccessToken(BoolCallback callback, Networking::ErrorCallback errorCallback, Common::String code) {
if (!KEY || !SECRET) loadKeyAndSecret();
if (!KEY || !SECRET)
loadKeyAndSecret();
bool codeFlow = (code != "");
if (!codeFlow && _refreshToken == "") {
warning("OneDriveStorage: no refresh token available to get new access token.");
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
return;
}
Networking::JsonCallback innerCallback = new Common::CallbackBridge<OneDriveStorage, BoolResponse, Networking::JsonResponse>(this, &OneDriveStorage::tokenRefreshed, callback);
if (errorCallback == nullptr) errorCallback = getErrorPrintingCallback();
if (errorCallback == nullptr)
errorCallback = getErrorPrintingCallback();
Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(innerCallback, errorCallback, "https://login.live.com/oauth20_token.srf"); //TODO
if (codeFlow) {
request->addPostField("code=" + code);
@ -108,13 +111,15 @@ void OneDriveStorage::tokenRefreshed(BoolCallback callback, Networking::JsonResp
if (!result.contains("access_token") || !result.contains("user_id") || !result.contains("refresh_token")) {
warning("Bad response, no token or user_id passed");
debug("%s", json->stringify().c_str());
if (callback) (*callback)(BoolResponse(nullptr, false));
if (callback)
(*callback)(BoolResponse(nullptr, false));
} else {
_token = result.getVal("access_token")->asString();
_uid = result.getVal("user_id")->asString();
_refreshToken = result.getVal("refresh_token")->asString();
CloudMan.save(); //ask CloudManager to save our new refreshToken
if (callback) (*callback)(BoolResponse(nullptr, true));
if (callback)
(*callback)(BoolResponse(nullptr, true));
}
delete json;
}
@ -174,8 +179,10 @@ void OneDriveStorage::infoInnerCallback(StorageInfoCallback outerCallback, Netwo
}
Common::String username = email;
if (username == "") username = name;
if (username == "") username = uid;
if (username == "")
username = name;
if (username == "")
username = uid;
CloudMan.setStorageUsername(kStorageOneDriveId, username);
if (outerCallback) {
@ -189,7 +196,8 @@ void OneDriveStorage::infoInnerCallback(StorageInfoCallback outerCallback, Netwo
void OneDriveStorage::fileInfoCallback(Networking::NetworkReadStreamCallback outerCallback, Networking::JsonResponse response) {
if (!response.value) {
warning("fileInfoCallback: NULL");
if (outerCallback) (*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
return;
}
@ -204,7 +212,8 @@ void OneDriveStorage::fileInfoCallback(Networking::NetworkReadStreamCallback out
} else {
warning("downloadUrl not found in passed JSON");
debug("%s", response.value->stringify().c_str());
if (outerCallback) (*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
}
delete response.value;
}
@ -226,7 +235,8 @@ Networking::Request *OneDriveStorage::streamFileById(Common::String path, Networ
}
Networking::Request *OneDriveStorage::createDirectory(Common::String path, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new OneDriveCreateDirectoryRequest(this, path, callback, errorCallback));
}

View file

@ -92,7 +92,8 @@ void OneDriveTokenRefresher::finishJson(Common::JSONValue *json) {
irrecoverable = false;
}
if (code == "unauthenticated") irrecoverable = false;
if (code == "unauthenticated")
irrecoverable = false;
if (irrecoverable) {
finishError(Networking::ErrorResponse(this, false, true, json->stringify(true), httpResponseCode));

View file

@ -41,14 +41,16 @@ OneDriveUploadRequest::OneDriveUploadRequest(OneDriveStorage *storage, Common::S
OneDriveUploadRequest::~OneDriveUploadRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _contentsStream;
delete _uploadCallback;
}
void OneDriveUploadRequest::start() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
if (_contentsStream == nullptr) {
warning("OneDriveUploadRequest: cannot restart because no stream given");
finishError(Networking::ErrorResponse(this, false, true, "No stream given", -1));
@ -97,9 +99,9 @@ void OneDriveUploadRequest::uploadNextPart() {
uint32 size = _contentsStream->read(buffer, UPLOAD_PER_ONE_REQUEST);
request->setBuffer(buffer, size);
if (_uploadUrl != "")
if (_uploadUrl != "") {
request->addHeader(Common::String::format("Content-Range: bytes %u-%u/%u", oldPos, _contentsStream->pos() - 1, _contentsStream->size()));
else if (_contentsStream->size() == 0) {
} else if (_contentsStream->size() == 0) {
warning("\"Sorry, OneDrive can't upload empty files\"");
finishUpload(StorageFile(_savePath, 0, 0, false));
delete request;
@ -111,7 +113,8 @@ void OneDriveUploadRequest::uploadNextPart() {
void OneDriveUploadRequest::partUploadedCallback(Networking::JsonResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "", -1);
Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
@ -164,7 +167,8 @@ void OneDriveUploadRequest::partUploadedCallback(Networking::JsonResponse respon
void OneDriveUploadRequest::partUploadedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
finishError(error);
}
@ -174,7 +178,8 @@ void OneDriveUploadRequest::restart() { start(); }
void OneDriveUploadRequest::finishUpload(StorageFile file) {
Request::finishSuccess();
if (_uploadCallback) (*_uploadCallback)(Storage::UploadResponse(this, file));
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace OneDrive

View file

@ -41,14 +41,16 @@ SavesSyncRequest::SavesSyncRequest(Storage *storage, Storage::BoolCallback callb
SavesSyncRequest::~SavesSyncRequest() {
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void SavesSyncRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest) _workingRequest->finish();
if (_workingRequest)
_workingRequest->finish();
_currentDownloadingFile = StorageFile();
_currentUploadingFile = "";
_filesToDownload.clear();
@ -62,7 +64,8 @@ void SavesSyncRequest::start() {
//list saves directory
Common::String dir = _storage->savesDirectoryPath();
if (dir.lastChar() == '/') dir.deleteLastChar();
if (dir.lastChar() == '/')
dir.deleteLastChar();
_workingRequest = _storage->listDirectory(
dir,
new Common::Callback<SavesSyncRequest, Storage::ListDirectoryResponse>(this, &SavesSyncRequest::directoryListedCallback),
@ -73,7 +76,8 @@ void SavesSyncRequest::start() {
void SavesSyncRequest::directoryListedCallback(Storage::ListDirectoryResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
if (response.request) _date = response.request->date();
@ -87,14 +91,16 @@ void SavesSyncRequest::directoryListedCallback(Storage::ListDirectoryResponse re
uint64 totalSize = 0;
for (uint32 i = 0; i < remoteFiles.size(); ++i) {
StorageFile &file = remoteFiles[i];
if (file.isDirectory()) continue;
if (file.isDirectory())
continue;
totalSize += file.size();
if (file.name() == DefaultSaveFileManager::TIMESTAMPS_FILENAME) continue;
if (file.name() == DefaultSaveFileManager::TIMESTAMPS_FILENAME)
continue;
Common::String name = file.name();
if (!_localFilesTimestamps.contains(name))
if (!_localFilesTimestamps.contains(name)) {
_filesToDownload.push_back(file);
else {
} else {
localFileNotAvailableInCloud[name] = false;
if (_localFilesTimestamps[name] == file.timestamp())
@ -113,8 +119,10 @@ void SavesSyncRequest::directoryListedCallback(Storage::ListDirectoryResponse re
//upload files which are unavailable in cloud
for (Common::HashMap<Common::String, bool>::iterator i = localFileNotAvailableInCloud.begin(); i != localFileNotAvailableInCloud.end(); ++i) {
if (i->_key == DefaultSaveFileManager::TIMESTAMPS_FILENAME) continue;
if (i->_value) _filesToUpload.push_back(i->_key);
if (i->_key == DefaultSaveFileManager::TIMESTAMPS_FILENAME)
continue;
if (i->_value)
_filesToUpload.push_back(i->_key);
}
debug(9, "\ndownload files:");
@ -133,7 +141,8 @@ void SavesSyncRequest::directoryListedCallback(Storage::ListDirectoryResponse re
void SavesSyncRequest::directoryListedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
bool irrecoverable = error.interrupted || error.failed;
if (error.failed) {
@ -179,19 +188,22 @@ void SavesSyncRequest::directoryListedErrorCallback(Networking::ErrorResponse er
//we're lucky - user just lacks his "/cloud/" folder - let's create one
Common::String dir = _storage->savesDirectoryPath();
if (dir.lastChar() == '/') dir.deleteLastChar();
if (dir.lastChar() == '/')
dir.deleteLastChar();
debug(9, "creating %s", dir.c_str());
_workingRequest = _storage->createDirectory(
dir,
new Common::Callback<SavesSyncRequest, Storage::BoolResponse>(this, &SavesSyncRequest::directoryCreatedCallback),
new Common::Callback<SavesSyncRequest, Networking::ErrorResponse>(this, &SavesSyncRequest::directoryCreatedErrorCallback)
);
if (!_workingRequest) finishError(Networking::ErrorResponse(this));
if (!_workingRequest)
finishError(Networking::ErrorResponse(this));
}
void SavesSyncRequest::directoryCreatedCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//stop syncing if failed to create saves directory
if (!response.value) {
@ -206,7 +218,8 @@ void SavesSyncRequest::directoryCreatedCallback(Storage::BoolResponse response)
void SavesSyncRequest::directoryCreatedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//stop syncing if failed to create saves directory
finishError(error);
@ -232,12 +245,14 @@ void SavesSyncRequest::downloadNextFile() {
new Common::Callback<SavesSyncRequest, Storage::BoolResponse>(this, &SavesSyncRequest::fileDownloadedCallback),
new Common::Callback<SavesSyncRequest, Networking::ErrorResponse>(this, &SavesSyncRequest::fileDownloadedErrorCallback)
);
if (!_workingRequest) finishError(Networking::ErrorResponse(this));
if (!_workingRequest)
finishError(Networking::ErrorResponse(this));
}
void SavesSyncRequest::fileDownloadedCallback(Storage::BoolResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//stop syncing if download failed
if (!response.value) {
@ -258,7 +273,8 @@ void SavesSyncRequest::fileDownloadedCallback(Storage::BoolResponse response) {
void SavesSyncRequest::fileDownloadedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//stop syncing if download failed
finishError(error);
@ -294,7 +310,8 @@ void SavesSyncRequest::uploadNextFile() {
void SavesSyncRequest::fileUploadedCallback(Storage::UploadResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//update local timestamp for the uploaded file
_localFilesTimestamps = DefaultSaveFileManager::loadTimestamps();
@ -307,7 +324,8 @@ void SavesSyncRequest::fileUploadedCallback(Storage::UploadResponse response) {
void SavesSyncRequest::fileUploadedErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback) return;
if (_ignoreCallback)
return;
//stop syncing if upload failed
finishError(error);
@ -319,11 +337,13 @@ void SavesSyncRequest::restart() { start(); }
double SavesSyncRequest::getDownloadingProgress() const {
if (_totalFilesToHandle == 0) {
if (_state == Networking::FINISHED) return 1; //nothing to upload and download => Request ends soon
if (_state == Networking::FINISHED)
return 1; //nothing to upload and download => Request ends soon
return 0; //directory not listed yet
}
if (_totalFilesToHandle == _filesToUpload.size()) return 1; //nothing to download => download complete
if (_totalFilesToHandle == _filesToUpload.size())
return 1; //nothing to download => download complete
uint32 totalFilesToDownload = _totalFilesToHandle - _filesToUpload.size();
uint32 filesLeftToDownload = _filesToDownload.size() + (_currentDownloadingFile.name() != "" ? 1 : 0);
@ -332,7 +352,8 @@ double SavesSyncRequest::getDownloadingProgress() const {
double SavesSyncRequest::getProgress() const {
if (_totalFilesToHandle == 0) {
if (_state == Networking::FINISHED) return 1; //nothing to upload and download => Request ends soon
if (_state == Networking::FINISHED)
return 1; //nothing to upload and download => Request ends soon
return 0; //directory not listed yet
}
@ -363,7 +384,8 @@ void SavesSyncRequest::finishError(Networking::ErrorResponse error) {
_currentDownloadingFile = StorageFile();
_filesToDownload.clear();
//delete the incomplete file
if (name != "") g_system->getSavefileManager()->removeSavefile(name);
if (name != "")
g_system->getSavefileManager()->removeSavefile(name);
Request::finishError(error);
}
@ -373,7 +395,8 @@ void SavesSyncRequest::finishSync(bool success) {
//update last successful sync date
CloudMan.setStorageLastSync(CloudMan.getStorageIndex(), _date);
if (_boolCallback) (*_boolCallback)(Storage::BoolResponse(this, success));
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
} // End of namespace Cloud

View file

@ -49,7 +49,8 @@ void Storage::printErrorResponse(Networking::ErrorResponse error) {
Networking::Request *Storage::addRequest(Networking::Request *request) {
_runningRequestsMutex.lock();
++_runningRequestsCount;
if (_runningRequestsCount == 1) debug(9, "Storage is working now");
if (_runningRequestsCount == 1)
debug(9, "Storage is working now");
_runningRequestsMutex.unlock();
return ConnMan.addRequest(request, new Common::Callback<Storage, Networking::Request *>(this, &Storage::requestFinishedCallback));
}
@ -61,8 +62,10 @@ void Storage::requestFinishedCallback(Networking::Request *invalidRequestPointer
if (invalidRequestPointer == _savesSyncRequest)
_savesSyncRequest = nullptr;
--_runningRequestsCount;
if (_syncRestartRequestsed) restartSync = true;
if (_runningRequestsCount == 0 && !restartSync) debug(9, "Storage is not working now");
if (_syncRestartRequestsed)
restartSync = true;
if (_runningRequestsCount == 0 && !restartSync)
debug(9, "Storage is not working now");
_runningRequestsMutex.unlock();
if (restartSync)
@ -75,7 +78,8 @@ Networking::Request *Storage::upload(Common::String remotePath, Common::String l
Common::File *f = new Common::File();
if (!f->open(localPath)) {
warning("Storage: unable to open file to upload from");
if (errorCallback) (*errorCallback)(Networking::ErrorResponse(nullptr, false, true, "", -1));
if (errorCallback)
(*errorCallback)(Networking::ErrorResponse(nullptr, false, true, "", -1));
delete errorCallback;
delete callback;
delete f;
@ -116,7 +120,8 @@ Networking::Request *Storage::downloadById(Common::String remoteId, Common::Stri
}
Networking::Request *Storage::downloadFolder(Common::String remotePath, Common::String localPath, FileArrayCallback callback, Networking::ErrorCallback errorCallback, bool recursive) {
if (!errorCallback) errorCallback = getErrorPrintingCallback();
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new FolderDownloadRequest(this, callback, errorCallback, remotePath, localPath, recursive));
}
@ -128,8 +133,10 @@ SavesSyncRequest *Storage::syncSaves(BoolCallback callback, Networking::ErrorCal
_runningRequestsMutex.unlock();
return _savesSyncRequest;
}
if (!callback) callback = new Common::Callback<Storage, BoolResponse>(this, &Storage::savesSyncDefaultCallback);
if (!errorCallback) errorCallback = new Common::Callback<Storage, Networking::ErrorResponse>(this, &Storage::savesSyncDefaultErrorCallback);
if (!callback)
callback = new Common::Callback<Storage, BoolResponse>(this, &Storage::savesSyncDefaultCallback);
if (!errorCallback)
errorCallback = new Common::Callback<Storage, Networking::ErrorResponse>(this, &Storage::savesSyncDefaultErrorCallback);
_savesSyncRequest = new SavesSyncRequest(this, callback, errorCallback);
_syncRestartRequestsed = false;
_runningRequestsMutex.unlock();
@ -198,7 +205,8 @@ void Storage::savesSyncDefaultCallback(BoolResponse response) {
_savesSyncRequest = nullptr;
_runningRequestsMutex.unlock();
if (!response.value) warning("SavesSyncRequest called success callback with `false` argument");
if (!response.value)
warning("SavesSyncRequest called success callback with `false` argument");
g_system->displayMessageOnOSD(_("Saves sync complete."));
}
@ -332,4 +340,3 @@ void Storage::directoryDownloadedErrorCallback(Networking::ErrorResponse error)
}
} // End of namespace Cloud

View file

@ -45,7 +45,8 @@ StorageFile::StorageFile(Common::String pth, uint32 sz, uint32 ts, bool dir) {
_name.erase(0, i + 1);
break;
}
if (i == 0) break;
if (i == 0)
break;
--i;
}
}

View file

@ -83,14 +83,16 @@ bool CloudIcon::draw() {
if (g_system) {
Graphics::TransparentSurface *surface = &_icon;
makeAlphaIcon((_showingDisabled ? _disabledIcon : _icon), _currentAlpha);
if (_alphaIcon.getPixels()) surface = &_alphaIcon;
if (_alphaIcon.getPixels())
surface = &_alphaIcon;
if (surface && surface->getPixels()) {
int x = g_system->getOverlayWidth() - surface->w - 10, y = 10;
g_system->copyRectToOSD(surface->getPixels(), surface->pitch, x, y, surface->w, surface->h);
}
}
if (stop) _showingDisabled = false;
if (stop)
_showingDisabled = false;
return stop;
}
@ -103,7 +105,8 @@ void CloudIcon::showDisabled() {
#include "backends/networking/curl/cloudicon_disabled_data.h"
void CloudIcon::initIcons() {
if (_iconsInited) return;
if (_iconsInited)
return;
loadIcon(_icon, cloudicon_data, ARRAYSIZE(cloudicon_data));
loadIcon(_disabledIcon, cloudicon_disabled_data, ARRAYSIZE(cloudicon_disabled_data));
_iconsInited = true;
@ -120,14 +123,18 @@ void CloudIcon::loadIcon(Graphics::TransparentSurface &icon, byte *data, uint32
Graphics::PixelFormat f = g_system->getOSDFormat();
if (f != s->format) {
Graphics::TransparentSurface *s2 = s->convertTo(f);
if (s2) icon.copyFrom(*s2);
else warning("CloudIcon::loadIcon: failed converting TransparentSurface");
if (s2)
icon.copyFrom(*s2);
else
warning("CloudIcon::loadIcon: failed converting TransparentSurface");
delete s2;
} else {
icon.copyFrom(*s);
}
delete s;
} else warning("CloudIcon::loadIcon: failed reading TransparentSurface from PNGDecoder");
} else {
warning("CloudIcon::loadIcon: failed reading TransparentSurface from PNGDecoder");
}
}
void CloudIcon::makeAlphaIcon(Graphics::TransparentSurface &icon, float alpha) {

View file

@ -50,9 +50,11 @@ ConnectionManager::~ConnectionManager() {
for (Common::Array<RequestWithCallback>::iterator i = _requests.begin(); i != _requests.end(); ++i) {
Request *request = i->request;
RequestCallback callback = i->onDeleteCallback;
if (request) request->finish();
if (request)
request->finish();
delete request;
if (callback) (*callback)(request);
if (callback)
(*callback)(request);
}
_requests.clear();
@ -70,7 +72,8 @@ void ConnectionManager::registerEasyHandle(CURL *easy) const {
Request *ConnectionManager::addRequest(Request *request, RequestCallback callback) {
_addedRequestsMutex.lock();
_addedRequests.push_back(RequestWithCallback(request, callback));
if (!_timerStarted) startTimer();
if (!_timerStarted)
startTimer();
_addedRequestsMutex.unlock();
return request;
}
@ -81,7 +84,8 @@ void ConnectionManager::showCloudDisabledIcon() {
}
Common::String ConnectionManager::urlEncode(Common::String s) const {
if (!_multi) return "";
if (!_multi)
return "";
char *output = curl_easy_escape(_multi, s.c_str(), s.size());
if (output) {
Common::String result = output;
@ -128,8 +132,10 @@ void ConnectionManager::handle() {
//lock mutex here (in case another handle() would be called before this one ends)
_handleMutex.lock();
++_frame;
if (_frame % CLOUD_PERIOD == 0) interateRequests();
if (_frame % CURL_PERIOD == 0) processTransfers();
if (_frame % CLOUD_PERIOD == 0)
interateRequests();
if (_frame % CURL_PERIOD == 0)
processTransfers();
if (_icon.draw() && _requests.empty() && !hasAddedRequests())
stopTimer();
@ -150,13 +156,16 @@ void ConnectionManager::interateRequests() {
for (Common::Array<RequestWithCallback>::iterator i = _requests.begin(); i != _requests.end();) {
Request *request = i->request;
if (request) {
if (request->state() == PROCESSING) request->handle();
else if (request->state() == RETRY) request->handleRetry();
if (request->state() == PROCESSING)
request->handle();
else if (request->state() == RETRY)
request->handleRetry();
}
if (!request || request->state() == FINISHED) {
delete (i->request);
if (i->onDeleteCallback) (*i->onDeleteCallback)(i->request); //that's not a mistake (we're passing an address and that method knows there is no object anymore)
if (i->onDeleteCallback)
(*i->onDeleteCallback)(i->request); //that's not a mistake (we're passing an address and that method knows there is no object anymore)
_requests.erase(i);
continue;
}
@ -179,7 +188,8 @@ void ConnectionManager::processTransfers() {
NetworkReadStream *stream;
curl_easy_getinfo(easyHandle, CURLINFO_PRIVATE, &stream);
if (stream) stream->finished();
if (stream)
stream->finished();
if (curlMsg->msg == CURLMSG_DONE) {
debug(9, "ConnectionManager: SUCCESS (%d - %s)", curlMsg->data.result, curl_easy_strerror(curlMsg->data.result));

View file

@ -49,7 +49,8 @@ char *CurlJsonRequest::getPreparedContents() {
byte *result = _contentsStream.getData();
uint32 size = _contentsStream.size();
for (uint32 i = 0; i < size; ++i) {
if (result[i] == '\n') result[i] = ' '; //yeah, kinda stupid
if (result[i] == '\n')
result[i] = ' '; //yeah, kinda stupid
else if (result[i] < 0x20 || result[i] > 0x7f)
result[i] = '.';
}
@ -85,7 +86,8 @@ void CurlJsonRequest::handle() {
}
void CurlJsonRequest::restart() {
if (_stream) delete _stream;
if (_stream)
delete _stream;
_stream = nullptr;
_contentsStream = Common::MemoryWriteStreamDynamic(DisposeAfterUse::YES);
//with no stream available next handle() will create another one
@ -93,8 +95,10 @@ void CurlJsonRequest::restart() {
void CurlJsonRequest::finishJson(Common::JSONValue *json) {
Request::finishSuccess();
if (_jsonCallback) (*_jsonCallback)(JsonResponse(this, json)); //potential memory leak, free it in your callbacks!
else delete json;
if (_jsonCallback)
(*_jsonCallback)(JsonResponse(this, json)); //potential memory leak, free it in your callbacks!
else
delete json;
}
bool CurlJsonRequest::jsonIsObject(Common::JSONValue *item, const char *warningPrefix) {

View file

@ -63,7 +63,8 @@ void CurlRequest::handle() {
}
void CurlRequest::restart() {
if (_stream) delete _stream;
if (_stream)
delete _stream;
_stream = nullptr;
//with no stream available next handle() will create another one
}
@ -78,7 +79,8 @@ Common::String CurlRequest::date() const {
Common::String result = "";
char c;
for (const char *i = position + 6; c = *i, c != 0; ++i) {
if (c == '\n' || c == '\r') break;
if (c == '\n' || c == '\r')
break;
result += c;
}
return result;
@ -135,7 +137,8 @@ void CurlRequest::setBuffer(byte *buffer, uint32 size) {
if (_postFields != "")
warning("CurlRequest: added POST fields would be ignored, because buffer added");
if (_bytesBuffer) delete _bytesBuffer;
if (_bytesBuffer)
delete _bytesBuffer;
_bytesBuffer = buffer;
_bytesBufferSize = size;

View file

@ -31,25 +31,29 @@ namespace Networking {
static size_t curlDataCallback(char *d, size_t n, size_t l, void *p) {
NetworkReadStream *stream = (NetworkReadStream *)p;
if (stream) return stream->write(d, n * l);
if (stream)
return stream->write(d, n * l);
return 0;
}
static size_t curlReadDataCallback(char *d, size_t n, size_t l, void *p) {
NetworkReadStream *stream = (NetworkReadStream *)p;
if (stream) return stream->fillWithSendingContents(d, n * l);
if (stream)
return stream->fillWithSendingContents(d, n * l);
return 0;
}
static size_t curlHeadersCallback(char *d, size_t n, size_t l, void *p) {
NetworkReadStream *stream = (NetworkReadStream *)p;
if (stream) return stream->addResponseHeaders(d, n * l);
if (stream)
return stream->addResponseHeaders(d, n * l);
return 0;
}
static int curlProgressCallback(void *p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
NetworkReadStream *stream = (NetworkReadStream *)p;
if (stream) stream->setProgress(dlnow, dltotal);
if (stream)
stream->setProgress(dlnow, dltotal);
return 0;
}
@ -171,7 +175,8 @@ uint32 NetworkReadStream::read(void *dataPtr, uint32 dataSize) {
uint32 actuallyRead = MemoryReadWriteStream::read(dataPtr, dataSize);
if (actuallyRead == 0) {
if (_requestComplete) _eos = true;
if (_requestComplete)
_eos = true;
return 0;
}
@ -205,7 +210,8 @@ Common::String NetworkReadStream::responseHeaders() const {
uint32 NetworkReadStream::fillWithSendingContents(char *bufferToFill, uint32 maxSize) {
uint32 size = _sendingContentsSize - _sendingContentsPos;
if (size > maxSize) size = maxSize;
if (size > maxSize)
size = maxSize;
for (uint32 i = 0; i < size; ++i) {
bufferToFill[i] = _sendingContentsBuffer[_sendingContentsPos + i];
}
@ -219,7 +225,8 @@ uint32 NetworkReadStream::addResponseHeaders(char *buffer, uint32 size) {
}
double NetworkReadStream::getProgress() const {
if (_progressTotal < 1) return 0;
if (_progressTotal < 1)
return 0;
return (double)_progressDownloaded / (double)_progressTotal;
}

View file

@ -39,8 +39,9 @@ Request::~Request() {
}
void Request::handleRetry() {
if (_retryInSeconds > 0) --_retryInSeconds;
else {
if (_retryInSeconds > 0) {
--_retryInSeconds;
} else {
_state = PROCESSING;
restart();
}
@ -64,7 +65,8 @@ Common::String Request::date() const { return ""; }
void Request::finishError(ErrorResponse error) {
_state = FINISHED;
if (_errorCallback) (*_errorCallback)(error);
if (_errorCallback)
(*_errorCallback)(error);
}
void Request::finishSuccess() { _state = FINISHED; }

View file

@ -45,15 +45,18 @@ Client::~Client() {
}
void Client::open(SDLNet_SocketSet set, TCPsocket socket) {
if (_state != INVALID) close();
if (_state != INVALID)
close();
_state = READING_HEADERS;
_socket = socket;
_set = set;
Reader cleanReader;
_reader = cleanReader;
if (_handler) delete _handler;
if (_handler)
delete _handler;
_handler = nullptr;
if (_previousHandler) delete _previousHandler;
if (_previousHandler)
delete _previousHandler;
_previousHandler = nullptr;
_stream = new Common::MemoryReadWriteStream(DisposeAfterUse::YES);
if (set) {
@ -65,10 +68,14 @@ void Client::open(SDLNet_SocketSet set, TCPsocket socket) {
}
bool Client::readMoreIfNeeded() {
if (_stream == nullptr) return false; //nothing to read into
if (_stream->size() - _stream->pos() > 0) return true; //not needed, some data left in the stream
if (!_socket) return false;
if (!SDLNet_SocketReady(_socket)) return false;
if (_stream == nullptr)
return false; //nothing to read into
if (_stream->size() - _stream->pos() > 0)
return true; //not needed, some data left in the stream
if (!_socket)
return false;
if (!SDLNet_SocketReady(_socket))
return false;
int bytes = SDLNet_TCP_Recv(_socket, _buffer, CLIENT_BUFFER_SIZE);
if (bytes <= 0) {
@ -87,33 +94,38 @@ bool Client::readMoreIfNeeded() {
}
void Client::readHeaders() {
if (!readMoreIfNeeded()) return;
if (!readMoreIfNeeded())
return;
_reader.setContent(_stream);
if (_reader.readFirstHeaders())
_state = (_reader.badRequest() ? BAD_REQUEST : READ_HEADERS);
}
bool Client::readContent(Common::WriteStream *stream) {
if (!readMoreIfNeeded()) return false;
if (!readMoreIfNeeded())
return false;
_reader.setContent(_stream);
return _reader.readFirstContent(stream);
}
bool Client::readBlockHeaders(Common::WriteStream *stream) {
if (!readMoreIfNeeded()) return false;
if (!readMoreIfNeeded())
return false;
_reader.setContent(_stream);
return _reader.readBlockHeaders(stream);
}
bool Client::readBlockContent(Common::WriteStream *stream) {
if (!readMoreIfNeeded()) return false;
if (!readMoreIfNeeded())
return false;
_reader.setContent(_stream);
return _reader.readBlockContent(stream);
}
void Client::setHandler(ClientHandler *handler) {
if (_handler) {
if (_previousHandler) delete _previousHandler;
if (_previousHandler)
delete _previousHandler;
_previousHandler = _handler; //can't just delete it, as setHandler() could've been called by handler itself
}
_state = BEING_HANDLED;
@ -121,9 +133,12 @@ void Client::setHandler(ClientHandler *handler) {
}
void Client::handle() {
if (_state != BEING_HANDLED) warning("handle() called in a wrong Client's state");
if (!_handler) warning("Client doesn't have handler to be handled by");
if (_handler) _handler->handle(this);
if (_state != BEING_HANDLED)
warning("handle() called in a wrong Client's state");
if (!_handler)
warning("Client doesn't have handler to be handled by");
if (_handler)
_handler->handle(this);
}
void Client::close() {

View file

@ -121,15 +121,18 @@ void GetClientHandler::prepareHeaders() {
}
void GetClientHandler::handle(Client *client) {
if (!client) return;
if (!_headersPrepared) prepareHeaders();
if (!client)
return;
if (!_headersPrepared)
prepareHeaders();
uint32 readBytes;
// send headers first
if (_headers.size() > 0) {
readBytes = _headers.size();
if (readBytes > CLIENT_HANDLER_BUFFER_SIZE) readBytes = CLIENT_HANDLER_BUFFER_SIZE;
if (readBytes > CLIENT_HANDLER_BUFFER_SIZE)
readBytes = CLIENT_HANDLER_BUFFER_SIZE;
memcpy(_buffer, _headers.c_str(), readBytes);
_headers.erase(0, readBytes);
} else {
@ -149,7 +152,8 @@ void GetClientHandler::handle(Client *client) {
}
// we're done here!
if (_stream->eos()) client->close();
if (_stream->eos())
client->close();
}
void GetClientHandler::setHeader(Common::String name, Common::String value) { _specialHeaders[name] = value; }

View file

@ -61,7 +61,8 @@ void CreateDirectoryHandler::handle(Client &client) {
}
// check that <directory_name> doesn't exist or is directory
if (path.lastChar() != '/' && path.lastChar() != '\\') path += '/';
if (path.lastChar() != '/' && path.lastChar() != '\\')
path += '/';
node = g_system->getFilesystemFactory()->makeFileNodePath(path + name);
if (node->exists()) {
if (!node->isDirectory()) {
@ -97,8 +98,10 @@ void CreateDirectoryHandler::handle(Client &client) {
}
void CreateDirectoryHandler::handleError(Client &client, Common::String message) const {
if (client.queryParameter("answer_json") == "true") setJsonResponseHandler(client, "error", message);
else HandlerUtils::setFilesManagerErrorMessageHandler(client, message);
if (client.queryParameter("answer_json") == "true")
setJsonResponseHandler(client, "error", message);
else
HandlerUtils::setFilesManagerErrorMessageHandler(client, message);
}
void CreateDirectoryHandler::setJsonResponseHandler(Client &client, Common::String type, Common::String message) const {

View file

@ -42,7 +42,9 @@ Common::String encodeDoubleQuotesAndSlashes(Common::String s) {
result += "\\\"";
} else if (s[i] == '\\') {
result += "\\\\";
} else result += s[i];
} else {
result += s[i];
}
return result;
}

View file

@ -40,20 +40,24 @@ Common::String FilesBaseHandler::parentPath(Common::String path) {
break;
}
}
if (path.size() && path.lastChar() != '/' && path.lastChar() != '\\') path += '/';
if (path.size() && path.lastChar() != '/' && path.lastChar() != '\\')
path += '/';
return path;
}
bool FilesBaseHandler::transformPath(Common::String &path, Common::String &prefixToRemove, Common::String &prefixToAdd, bool isDirectory) {
// <path> is not empty, but could lack the trailing slash
if (isDirectory && path.lastChar() != '/' && path.lastChar() != '\\') path += '/';
if (isDirectory && path.lastChar() != '/' && path.lastChar() != '\\')
path += '/';
if (path.hasPrefix("/root")) {
prefixToAdd = "/root/";
prefixToRemove = "";
path.erase(0, 5);
if (path == "") path = "/"; // absolute root is '/'
if (path != "/") path.deleteChar(0); // if that was "/root/ab/c", it becomes "/ab/c", but we need "ab/c"
if (path == "")
path = "/"; // absolute root is '/'
if (path != "/")
path.deleteChar(0); // if that was "/root/ab/c", it becomes "/ab/c", but we need "ab/c"
return true;
}

View file

@ -40,17 +40,23 @@ Common::String encodeDoubleQuotes(Common::String s) {
for (uint32 i = 0; i < s.size(); ++i)
if (s[i] == '"') {
result += "\\\"";
} else result += s[i];
} else {
result += s[i];
}
return result;
}
Common::String encodeHtmlEntities(Common::String s) {
Common::String result = "";
for (uint32 i = 0; i < s.size(); ++i)
if (s[i] == '<') result += "&lt;";
else if (s[i] == '>') result += "&gt;";
else if (s[i] == '&') result += "&amp;";
else if (s[i] > 0x7F) result += Common::String::format("&#%d;", (int)s[i]);
if (s[i] == '<')
result += "&lt;";
else if (s[i] == '>')
result += "&gt;";
else if (s[i] == '&')
result += "&amp;";
else if (s[i] > 0x7F)
result += Common::String::format("&#%d;", (int)s[i]);
else result += s[i];
return result;
}
@ -58,9 +64,12 @@ Common::String encodeHtmlEntities(Common::String s) {
Common::String getDisplayPath(Common::String s) {
Common::String result = "";
for (uint32 i = 0; i < s.size(); ++i)
if (s[i] == '\\') result += '/';
else result += s[i];
if (result == "") return "/";
if (s[i] == '\\')
result += '/';
else
result += s[i];
if (result == "")
return "/";
return result;
}
}
@ -93,7 +102,8 @@ void FilesPageHandler::handle(Client &client) {
// load stylish response page from the archive
Common::SeekableReadStream *const stream = HandlerUtils::getArchiveFile(FILES_PAGE_NAME);
if (stream) response = HandlerUtils::readEverythingFromStream(stream);
if (stream)
response = HandlerUtils::readEverythingFromStream(stream);
Common::String path = client.queryParameter("path");
Common::String content = "";
@ -127,11 +137,14 @@ bool FilesPageHandler::listDirectory(Common::String path, Common::String &conten
}
Common::String prefixToRemove = "", prefixToAdd = "";
if (!transformPath(path, prefixToRemove, prefixToAdd)) return false;
if (!transformPath(path, prefixToRemove, prefixToAdd))
return false;
Common::FSNode node = Common::FSNode(path);
if (path == "/") node = node.getParent(); // absolute root
if (!node.isDirectory()) return false;
if (path == "/")
node = node.getParent(); // absolute root
if (!node.isDirectory())
return false;
// list directory
Common::FSList _nodeContent;
@ -155,7 +168,8 @@ bool FilesPageHandler::listDirectory(Common::String path, Common::String &conten
// fill the content
for (Common::FSList::iterator i = _nodeContent.begin(); i != _nodeContent.end(); ++i) {
Common::String name = i->getDisplayName();
if (i->isDirectory()) name += "/";
if (i->isDirectory())
name += "/";
Common::String filePath = i->getPath();
if (filePath.hasPrefix(prefixToRemove))
@ -169,10 +183,14 @@ bool FilesPageHandler::listDirectory(Common::String path, Common::String &conten
}
FilesPageHandler::ItemType FilesPageHandler::detectType(bool isDirectory, const Common::String &name) {
if (isDirectory) return IT_DIRECTORY;
if (name.hasSuffix(".txt")) return IT_TXT;
if (name.hasSuffix(".zip")) return IT_ZIP;
if (name.hasSuffix(".7z")) return IT_7Z;
if (isDirectory)
return IT_DIRECTORY;
if (name.hasSuffix(".txt"))
return IT_TXT;
if (name.hasSuffix(".zip"))
return IT_ZIP;
if (name.hasSuffix(".7z"))
return IT_7Z;
return IT_UNKNOWN;
}
@ -180,12 +198,23 @@ void FilesPageHandler::addItem(Common::String &content, const Common::String &it
Common::String item = itemTemplate, icon;
bool isDirectory = (itemType == IT_DIRECTORY || itemType == IT_PARENT_DIRECTORY);
switch (itemType) {
case IT_DIRECTORY: icon = "dir.png"; break;
case IT_PARENT_DIRECTORY: icon = "up.png"; break;
case IT_TXT: icon = "txt.png"; break;
case IT_ZIP: icon = "zip.png"; break;
case IT_7Z: icon = "7z.png"; break;
default: icon = "unk.png";
case IT_DIRECTORY:
icon = "dir.png";
break;
case IT_PARENT_DIRECTORY:
icon = "up.png";
break;
case IT_TXT:
icon = "txt.png";
break;
case IT_ZIP:
icon = "zip.png";
break;
case IT_7Z:
icon = "7z.png";
break;
default:
icon = "unk.png";
}
replace(item, "{icon}", icon);
replace(item, "{link}", (isDirectory ? "files?path=" : "download?path=") + LocalWebserver::urlEncodeQueryParameterValue(path));

View file

@ -54,11 +54,14 @@ Common::JSONObject ListAjaxHandler::listDirectory(Common::String path) {
}
Common::String prefixToRemove = "", prefixToAdd = "";
if (!transformPath(path, prefixToRemove, prefixToAdd)) return errorResult;
if (!transformPath(path, prefixToRemove, prefixToAdd))
return errorResult;
Common::FSNode node = Common::FSNode(path);
if (path == "/") node = node.getParent(); // absolute root
if (!node.isDirectory()) return errorResult;
if (path == "/")
node = node.getParent(); // absolute root
if (!node.isDirectory())
return errorResult;
// list directory
Common::FSList _nodeContent;
@ -97,10 +100,14 @@ Common::JSONObject ListAjaxHandler::listDirectory(Common::String path) {
}
ListAjaxHandler::ItemType ListAjaxHandler::detectType(bool isDirectory, const Common::String &name) {
if (isDirectory) return IT_DIRECTORY;
if (name.hasSuffix(".txt")) return IT_TXT;
if (name.hasSuffix(".zip")) return IT_ZIP;
if (name.hasSuffix(".7z")) return IT_7Z;
if (isDirectory)
return IT_DIRECTORY;
if (name.hasSuffix(".txt"))
return IT_TXT;
if (name.hasSuffix(".zip"))
return IT_ZIP;
if (name.hasSuffix(".7z"))
return IT_7Z;
return IT_UNKNOWN;
}
@ -108,12 +115,23 @@ void ListAjaxHandler::addItem(Common::JSONArray &responseItemsList, ItemType ite
Common::String icon;
bool isDirectory = (itemType == IT_DIRECTORY || itemType == IT_PARENT_DIRECTORY);
switch (itemType) {
case IT_DIRECTORY: icon = "dir.png"; break;
case IT_PARENT_DIRECTORY: icon = "up.png"; break;
case IT_TXT: icon = "txt.png"; break;
case IT_ZIP: icon = "zip.png"; break;
case IT_7Z: icon = "7z.png"; break;
default: icon = "unk.png";
case IT_DIRECTORY:
icon = "dir.png";
break;
case IT_PARENT_DIRECTORY:
icon = "up.png";
break;
case IT_TXT:
icon = "txt.png";
break;
case IT_ZIP:
icon = "zip.png";
break;
case IT_7Z:
icon = "7z.png";
break;
default:
icon = "unk.png";
}
Common::JSONObject item;

View file

@ -35,11 +35,13 @@ void ResourceHandler::handle(Client &client) {
filename.deleteChar(0);
// if archive hidden file is requested, ignore
if (filename.size() && filename[0] == '.') return;
if (filename.size() && filename[0] == '.')
return;
// if file not found, don't set handler either
Common::SeekableReadStream *file = HandlerUtils::getArchiveFile(filename);
if (file == nullptr) return;
if (file == nullptr)
return;
LocalWebserver::setClientGetHandler(client, file, 200, LocalWebserver::determineMimeType(filename));
}

View file

@ -45,7 +45,8 @@ Common::Archive *HandlerUtils::getZipArchive() {
if (fileNode.exists() && fileNode.isReadable() && !fileNode.isDirectory()) {
Common::SeekableReadStream *const stream = fileNode.createReadStream();
Common::Archive *zipArchive = Common::makeZipArchive(stream);
if (zipArchive) return zipArchive;
if (zipArchive)
return zipArchive;
}
}
@ -56,7 +57,8 @@ Common::Archive *HandlerUtils::getZipArchive() {
Common::ArchiveMember const &m = **it;
Common::SeekableReadStream *const stream = m.createReadStream();
Common::Archive *zipArchive = Common::makeZipArchive(stream);
if (zipArchive) return zipArchive;
if (zipArchive)
return zipArchive;
}
return nullptr;
@ -77,7 +79,8 @@ Common::SeekableReadStream *HandlerUtils::getArchiveFile(Common::String name) {
Common::Archive *zipArchive = getZipArchive();
if (zipArchive) {
const Common::ArchiveMemberPtr ptr = zipArchive->getMember(name);
if (ptr.get() == nullptr) return nullptr;
if (ptr.get() == nullptr)
return nullptr;
result = ptr->createReadStream();
delete zipArchive;
}
@ -100,11 +103,14 @@ void HandlerUtils::setMessageHandler(Client &client, Common::String message, Com
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
if (stream)
response = readEverythingFromStream(stream);
replace(response, "{message}", message);
if (redirectTo.empty()) LocalWebserver::setClientGetHandler(client, response);
else LocalWebserver::setClientRedirectHandler(client, response, redirectTo);
if (redirectTo.empty())
LocalWebserver::setClientGetHandler(client, response);
else
LocalWebserver::setClientRedirectHandler(client, response, redirectTo);
}
void HandlerUtils::setFilesManagerErrorMessageHandler(Client &client, Common::String message, Common::String redirectTo) {

View file

@ -125,7 +125,8 @@ void LocalWebserver::start() {
void LocalWebserver::stop() {
_handleMutex.lock();
if (_timerStarted) stopTimer();
if (_timerStarted)
stopTimer();
if (_serverSocket) {
SDLNet_TCP_Close(_serverSocket);
@ -147,12 +148,14 @@ void LocalWebserver::stop() {
void LocalWebserver::stopOnIdle() { _stopOnIdle = true; }
void LocalWebserver::addPathHandler(Common::String path, ClientHandlerCallback handler) {
if (_pathHandlers.contains(path)) warning("LocalWebserver::addPathHandler: path already had a handler");
if (_pathHandlers.contains(path))
warning("LocalWebserver::addPathHandler: path already had a handler");
_pathHandlers[path] = handler;
}
void LocalWebserver::removePathHandler(Common::String path) {
if (!_pathHandlers.contains(path)) warning("LocalWebserver::removePathHandler: no handler known for this path");
if (!_pathHandlers.contains(path))
warning("LocalWebserver::removePathHandler: no handler known for this path");
_pathHandlers.erase(path);
}
@ -181,7 +184,9 @@ void LocalWebserver::handle() {
int numready = SDLNet_CheckSockets(_set, 0);
if (numready == -1) {
error("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
} else if (numready) acceptClient();
} else if (numready) {
acceptClient();
}
for (uint32 i = 0; i < MAX_CONNECTIONS; ++i)
handleClient(i);
@ -191,8 +196,10 @@ void LocalWebserver::handle() {
if (_client[i].state() != INVALID)
++_clients;
if (_clients == 0) ++_idlingFrames;
else _idlingFrames = 0;
if (_clients == 0)
++_idlingFrames;
else
_idlingFrames = 0;
if (_idlingFrames > FRAMES_PER_SECOND && _stopOnIdle) {
_handleMutex.unlock();
@ -218,7 +225,8 @@ void LocalWebserver::handleClient(uint32 i) {
else if (_defaultHandler)
(*_defaultHandler)(_client[i]); //try default handler
if (_client[i].state() == BEING_HANDLED || _client[i].state() == INVALID) break;
if (_client[i].state() == BEING_HANDLED || _client[i].state() == INVALID)
break;
//if no handler, answer with default BAD REQUEST
//fallthrough
case BAD_REQUEST:
@ -231,10 +239,12 @@ void LocalWebserver::handleClient(uint32 i) {
}
void LocalWebserver::acceptClient() {
if (!SDLNet_SocketReady(_serverSocket)) return;
if (!SDLNet_SocketReady(_serverSocket))
return;
TCPsocket client = SDLNet_TCP_Accept(_serverSocket);
if (!client) return;
if (!client)
return;
if (_clients == MAX_CONNECTIONS) { //drop the connection
SDLNet_TCP_Close(client);
@ -304,15 +314,16 @@ void LocalWebserver::resolveAddress(void *ipAddress) {
// IPv6
/*
if (i->ifa_addr->sa_family == AF_INET6) {
tmpAddrPtr = &((struct sockaddr_in6 *)i->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
debug("%s IP Address %s", i->ifa_name, addressBuffer);
addr = addressBuffer;
tmpAddrPtr = &((struct sockaddr_in6 *)i->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
debug("%s IP Address %s", i->ifa_name, addressBuffer);
addr = addressBuffer;
}
*/
if (addr.empty()) continue;
if (addr.empty())
continue;
// ignored IPv4 addresses
if (addr.equals("127.0.0.1") || addr.equals("0.0.0.0") || addr.equals("localhost"))
@ -321,7 +332,7 @@ void LocalWebserver::resolveAddress(void *ipAddress) {
// ignored IPv6 addresses
/*
if (addr.equals("::1"))
continue;
continue;
*/
// use the address found
@ -342,7 +353,8 @@ void LocalWebserver::setClientGetHandler(Client &client, Common::String response
void LocalWebserver::setClientGetHandler(Client &client, Common::SeekableReadStream *responseStream, long code, const char *mimeType) {
GetClientHandler *handler = new GetClientHandler(responseStream);
handler->setResponseCode(code);
if (mimeType) handler->setHeader("Content-Type", mimeType);
if (mimeType)
handler->setHeader("Content-Type", mimeType);
client.setHandler(handler);
}
@ -357,7 +369,8 @@ void LocalWebserver::setClientRedirectHandler(Client &client, Common::SeekableRe
GetClientHandler *handler = new GetClientHandler(responseStream);
handler->setResponseCode(302); //redirect
handler->setHeader("Location", location);
if (mimeType) handler->setHeader("Content-Type", mimeType);
if (mimeType)
handler->setHeader("Content-Type", mimeType);
client.setHandler(handler);
}

View file

@ -51,7 +51,8 @@ Reader::~Reader() {
}
Reader &Reader::operator=(Reader &r) {
if (this == &r) return *this;
if (this == &r)
return *this;
cleanup();
_state = r._state;
@ -83,7 +84,8 @@ Reader &Reader::operator=(Reader &r) {
void Reader::cleanup() {
//_content is not to be freed, it's not owned by Reader
if (_window != nullptr) freeWindow();
if (_window != nullptr)
freeWindow();
}
bool Reader::readAndHandleFirstHeaders() {
@ -94,7 +96,8 @@ bool Reader::readAndHandleFirstHeaders() {
}
while (readOneByteInString(_headers, boundary)) {
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
}
handleFirstHeaders(_headers);
@ -108,7 +111,8 @@ bool Reader::readBlockHeadersIntoStream(Common::WriteStream *stream) {
if (_window == nullptr) makeWindow(boundary.size());
while (readOneByteInStream(stream, boundary)) {
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
}
if (stream) stream->flush();
@ -124,7 +128,8 @@ void readFromThatUntilLineEnd(const char *cstr, Common::String needle, Common::S
if (position) {
char c;
for (const char *i = position + needle.size(); c = *i, c != 0; ++i) {
if (c == '\n' || c == '\r') break;
if (c == '\n' || c == '\r')
break;
result += c;
}
}
@ -166,14 +171,19 @@ void Reader::parseFirstLine(const Common::String &headers) {
//"<METHOD> <path> HTTP/<VERSION>\r\n"
Common::String method, path, http, buf;
uint32 length = position - cstr;
if (headersSize > length) headersSize = length;
if (headersSize > length)
headersSize = length;
for (uint32 i = 0; i < headersSize; ++i) {
if (headers[i] != ' ') buf += headers[i];
if (headers[i] != ' ')
buf += headers[i];
if (headers[i] == ' ' || i == headersSize - 1) {
if (method == "") method = buf;
else if (path == "") path = buf;
else if (http == "") http = buf;
else {
if (method == "") {
method = buf;
} else if (path == "") {
path = buf;
} else if (http == "") {
http = buf;
} else {
bad = true;
break;
}
@ -182,10 +192,12 @@ void Reader::parseFirstLine(const Common::String &headers) {
}
//check that method is supported
if (method != "GET" && method != "PUT" && method != "POST") bad = true;
if (method != "GET" && method != "PUT" && method != "POST")
bad = true;
//check that HTTP/<VERSION> is OK
if (!http.hasPrefix("HTTP/")) bad = true;
if (!http.hasPrefix("HTTP/"))
bad = true;
_method = method;
parsePathQueryAndAnchor(path);
@ -208,12 +220,18 @@ void Reader::parsePathQueryAndAnchor(Common::String path) {
if (path[i] == '?') {
readingPath = false;
readingQuery = true;
} else _path += path[i];
} else {
_path += path[i];
}
} else if (readingQuery) {
if (path[i] == '#') {
readingQuery = false;
} else _query += path[i];
} else _anchor += path[i];
} else {
_query += path[i];
}
} else {
_anchor += path[i];
}
}
parseQueryParameters();
@ -228,35 +246,48 @@ void Reader::parseQueryParameters() {
if (_query[i] == '=') {
readingKey = false;
value = "";
} else key += _query[i];
} else {
key += _query[i];
}
} else {
if (_query[i] == '&') {
if (_queryParameters.contains(key)) warning("Query parameter \"%s\" is already set!", key.c_str());
else _queryParameters[key] = LocalWebserver::urlDecode(value);
if (_queryParameters.contains(key))
warning("Query parameter \"%s\" is already set!", key.c_str());
else
_queryParameters[key] = LocalWebserver::urlDecode(value);
readingKey = true;
key = "";
} else value += _query[i];
} else {
value += _query[i];
}
}
}
if (!key.empty()) {
if (_queryParameters.contains(key)) warning("Query parameter \"%s\" is already set!", key.c_str());
else _queryParameters[key] = LocalWebserver::urlDecode(value);
if (_queryParameters.contains(key))
warning("Query parameter \"%s\" is already set!", key.c_str());
else
_queryParameters[key] = LocalWebserver::urlDecode(value);
}
}
bool Reader::readContentIntoStream(Common::WriteStream *stream) {
Common::String boundary = "--" + _boundary;
if (!_firstBlock) boundary = "\r\n" + boundary;
if (_boundary.empty()) boundary = "\r\n";
if (_window == nullptr) makeWindow(boundary.size());
if (!_firstBlock)
boundary = "\r\n" + boundary;
if (_boundary.empty())
boundary = "\r\n";
if (_window == nullptr)
makeWindow(boundary.size());
while (readOneByteInStream(stream, boundary)) {
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
}
_firstBlock = false;
if (stream) stream->flush();
if (stream)
stream->flush();
freeWindow();
_state = RS_READING_HEADERS;
@ -280,14 +311,16 @@ void Reader::freeWindow() {
bool Reader::readOneByteInStream(Common::WriteStream *stream, const Common::String &boundary) {
byte b = readOne();
_window[_windowUsed++] = b;
if (_windowUsed < _windowSize) return true;
if (_windowUsed < _windowSize)
return true;
//when window is filled, check whether that's the boundary
if (Common::String((char *)_window, _windowSize) == boundary)
return false;
//if not, add the first byte of the window to the string
if (stream) stream->writeByte(_window[0]);
if (stream)
stream->writeByte(_window[0]);
for (uint32 i = 1; i < _windowSize; ++i)
_window[i - 1] = _window[i];
--_windowUsed;
@ -297,7 +330,8 @@ bool Reader::readOneByteInStream(Common::WriteStream *stream, const Common::Stri
bool Reader::readOneByteInString(Common::String &buffer, const Common::String &boundary) {
byte b = readOne();
_window[_windowUsed++] = b;
if (_windowUsed < _windowSize) return true;
if (_windowUsed < _windowSize)
return true;
//when window is filled, check whether that's the boundary
if (Common::String((char *)_window, _windowSize) == boundary)
@ -322,9 +356,11 @@ byte Reader::readOne() {
/// public
bool Reader::readFirstHeaders() {
if (_state == RS_NONE) _state = RS_READING_HEADERS;
if (_state == RS_NONE)
_state = RS_READING_HEADERS;
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
if (_state == RS_READING_HEADERS)
return readAndHandleFirstHeaders();
@ -349,7 +385,8 @@ bool Reader::readBlockHeaders(Common::WriteStream *stream) {
return false;
}
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
return readBlockHeadersIntoStream(stream);
}
@ -360,7 +397,8 @@ bool Reader::readBlockContent(Common::WriteStream *stream) {
return false;
}
if (!bytesLeft()) return false;
if (!bytesLeft())
return false;
if (!readContentIntoStream(stream))
return false;
@ -369,7 +407,8 @@ bool Reader::readBlockContent(Common::WriteStream *stream) {
Common::String bts;
bts += readOne();
bts += readOne();
if (bts == "--") _allContentRead = true;
if (bts == "--")
_allContentRead = true;
else if (bts != "\r\n")
warning("strange bytes: \"%s\"", bts.c_str());
} else {

View file

@ -89,7 +89,8 @@ void readFromThatUntilDoubleQuote(const char *cstr, Common::String needle, Commo
if (position) {
char c;
for (const char *i = position + needle.size(); c = *i, c != 0; ++i) {
if (c == '"') break;
if (c == '"')
break;
result += c;
}
}
@ -101,7 +102,8 @@ Common::String readEverythingFromMemoryStream(Common::MemoryReadWriteStream *str
uint32 readBytes;
while (true) {
readBytes = stream->read(buf, 1024);
if (readBytes == 0) break;
if (readBytes == 0)
break;
result += Common::String(buf, readBytes);
}
return result;
@ -115,17 +117,20 @@ void UploadFileClientHandler::handleBlockHeaders(Client *client) {
Common::String headers = readEverythingFromMemoryStream(_headersStream);
Common::String fieldName = "";
readFromThatUntilDoubleQuote(headers.c_str(), "name=\"", fieldName);
if (!fieldName.hasPrefix("upload_file")) return;
if (!fieldName.hasPrefix("upload_file"))
return;
Common::String filename = "";
readFromThatUntilDoubleQuote(headers.c_str(), "filename=\"", filename);
// skip block if <filename> is empty
if (filename.empty()) return;
if (filename.empty())
return;
// check that <path>/<filename> doesn't exist
Common::String path = _parentDirectoryPath;
if (path.lastChar() != '/' && path.lastChar() != '\\') path += '/';
if (path.lastChar() != '/' && path.lastChar() != '\\')
path += '/';
AbstractFSNode *originalNode = g_system->getFilesystemFactory()->makeFileNodePath(path + filename);
if (originalNode->exists()) {
setErrorMessageHandler(*client, _("There is a file with that name in the parent directory!"));
@ -174,7 +179,9 @@ void UploadFileClientHandler::handleBlockContent(Client *client) {
// if no file field was found - failure
if (_uploadedFiles == 0) {
setErrorMessageHandler(*client, _("No file was passed!"));
} else _state = UFH_STOP;
} else {
_state = UFH_STOP;
}
return;
}
}