Initial commit

This commit is contained in:
2026-02-02 04:50:13 +01:00
commit 5b11698731
22592 changed files with 7677434 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "backends/cloud/onedrive/onedrivecreatedirectoryrequest.h"
#include "backends/cloud/onedrive/onedrivestorage.h"
#include "backends/cloud/onedrive/onedrivetokenrefresher.h"
#include "backends/networking/http/connectionmanager.h"
#include "backends/networking/http/httpjsonrequest.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/formats/json.h"
namespace Cloud {
namespace OneDrive {
#define ONEDRIVE_API_SPECIAL_APPROOT "https://graph.microsoft.com/v1.0/drive/special/approot"
OneDriveCreateDirectoryRequest::OneDriveCreateDirectoryRequest(OneDriveStorage *storage, const Common::String &path, Storage::BoolCallback cb, Networking::ErrorCallback ecb):
Networking::Request(nullptr, ecb), _storage(storage), _path(path), _boolCallback(cb),
_workingRequest(nullptr), _ignoreCallback(false) {
start();
}
OneDriveCreateDirectoryRequest::~OneDriveCreateDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
}
void OneDriveCreateDirectoryRequest::start() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
_ignoreCallback = false;
Common::String name = _path, parent = _path;
if (name.size() != 0) {
uint32 i = name.size() - 1;
while (true) {
parent.deleteLastChar();
if (name[i] == '/' || name[i] == '\\') {
name.erase(0, i + 1);
break;
}
if (i == 0)
break;
--i;
}
}
Common::String url = ONEDRIVE_API_SPECIAL_APPROOT;
if (parent != "")
url += ":/" + Common::percentEncodeString(parent) + ":";
url += "/children";
Networking::JsonCallback innerCallback = new Common::Callback<OneDriveCreateDirectoryRequest, const Networking::JsonResponse &>(this, &OneDriveCreateDirectoryRequest::responseCallback);
Networking::ErrorCallback errorResponseCallback = new Common::Callback<OneDriveCreateDirectoryRequest, const Networking::ErrorResponse &>(this, &OneDriveCreateDirectoryRequest::errorCallback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(_storage, innerCallback, errorResponseCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
request->addHeader("Content-Type: application/json");
Common::JSONObject jsonRequestParameters;
jsonRequestParameters.setVal("name", new Common::JSONValue(name));
jsonRequestParameters.setVal("folder", new Common::JSONValue(Common::JSONObject()));
Common::JSONValue value(jsonRequestParameters);
request->addPostField(Common::JSON::stringify(&value));
_workingRequest = ConnMan.addRequest(request);
}
void OneDriveCreateDirectoryRequest::responseCallback(const Networking::JsonResponse &response) {
const Common::JSONValue *json = response.value;
_workingRequest = nullptr;
if (_ignoreCallback) {
delete json;
return;
}
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this, "OneDriveCreateDirectoryRequest::responseCallback: unknown error");
const Networking::HttpJsonRequest *rq = (const Networking::HttpJsonRequest *)response.request;
if (rq && rq->getNetworkReadStream())
error.httpResponseCode = rq->getNetworkReadStream()->httpResponseCode();
if (json == nullptr) {
error.response = "Failed to parse JSON, null passed!";
finishError(error);
return;
}
if (!json->isObject()) {
error.response = "Passed JSON is not an object!";
finishError(error);
delete json;
return;
}
Common::JSONObject info = json->asObject();
if (info.contains("id")) {
finishCreation(true);
} else {
error.response = json->stringify(true);
finishError(error);
}
delete json;
}
void OneDriveCreateDirectoryRequest::errorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
void OneDriveCreateDirectoryRequest::handle() {}
void OneDriveCreateDirectoryRequest::restart() { start(); }
Common::String OneDriveCreateDirectoryRequest::date() const { return _date; }
void OneDriveCreateDirectoryRequest::finishCreation(bool success) {
Request::finishSuccess();
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
} // End of namespace OneDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,58 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BACKENDS_CLOUD_ONEDRIVE_ONEDRIVECREATEDIRECTORYREQUEST_H
#define BACKENDS_CLOUD_ONEDRIVE_ONEDRIVECREATEDIRECTORYREQUEST_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/request.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace OneDrive {
class OneDriveStorage;
class OneDriveCreateDirectoryRequest: public Networking::Request {
OneDriveStorage *_storage;
Common::String _path;
Storage::BoolCallback _boolCallback;
Request *_workingRequest;
bool _ignoreCallback;
Common::String _date;
void start();
void responseCallback(const Networking::JsonResponse &response);
void errorCallback(const Networking::ErrorResponse &error);
void finishCreation(bool success);
public:
OneDriveCreateDirectoryRequest(OneDriveStorage *storage, const Common::String &path, Storage::BoolCallback cb, Networking::ErrorCallback ecb);
~OneDriveCreateDirectoryRequest() override;
void handle() override;
void restart() override;
Common::String date() const override;
};
} // End of namespace OneDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,194 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "backends/cloud/onedrive/onedrivelistdirectoryrequest.h"
#include "backends/cloud/onedrive/onedrivestorage.h"
#include "backends/cloud/onedrive/onedrivetokenrefresher.h"
#include "backends/cloud/iso8601.h"
#include "backends/networking/http/connectionmanager.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/formats/json.h"
namespace Cloud {
namespace OneDrive {
#define ONEDRIVE_API_SPECIAL_APPROOT_CHILDREN "https://graph.microsoft.com/v1.0/drive/special/approot:/%s:/children"
#define ONEDRIVE_API_SPECIAL_APPROOT_CHILDREN_ROOT_ITSELF "https://graph.microsoft.com/v1.0/drive/special/approot/children"
OneDriveListDirectoryRequest::OneDriveListDirectoryRequest(OneDriveStorage *storage, const Common::String &path, Storage::ListDirectoryCallback cb, Networking::ErrorCallback ecb, bool recursive):
Networking::Request(nullptr, ecb),
_requestedPath(path), _requestedRecursive(recursive), _storage(storage), _listDirectoryCallback(cb),
_workingRequest(nullptr), _ignoreCallback(false) {
start();
}
OneDriveListDirectoryRequest::~OneDriveListDirectoryRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void OneDriveListDirectoryRequest::start() {
//cleanup
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
_workingRequest = nullptr;
_files.clear();
_directoriesQueue.clear();
_currentDirectory = "";
_ignoreCallback = false;
_directoriesQueue.push_back(_requestedPath);
listNextDirectory();
}
void OneDriveListDirectoryRequest::listNextDirectory() {
if (_directoriesQueue.empty()) {
finishListing(_files);
return;
}
_currentDirectory = _directoriesQueue.back();
_directoriesQueue.pop_back();
if (_currentDirectory != "" && _currentDirectory.lastChar() != '/' && _currentDirectory.lastChar() != '\\')
_currentDirectory += '/';
Common::String dir = _currentDirectory;
dir.deleteLastChar();
Common::String url = Common::String::format(ONEDRIVE_API_SPECIAL_APPROOT_CHILDREN, Common::percentEncodeString(dir).c_str());
if (dir == "") url = Common::String(ONEDRIVE_API_SPECIAL_APPROOT_CHILDREN_ROOT_ITSELF);
makeRequest(url);
}
void OneDriveListDirectoryRequest::makeRequest(const Common::String &url) {
Networking::JsonCallback callback = new Common::Callback<OneDriveListDirectoryRequest, const Networking::JsonResponse &>(this, &OneDriveListDirectoryRequest::listedDirectoryCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<OneDriveListDirectoryRequest, const Networking::ErrorResponse &>(this, &OneDriveListDirectoryRequest::listedDirectoryErrorCallback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: bearer " + _storage->accessToken());
_workingRequest = ConnMan.addRequest(request);
}
void OneDriveListDirectoryRequest::listedDirectoryCallback(const Networking::JsonResponse &response) {
_workingRequest = nullptr;
const Common::JSONValue *json = response.value;
if (_ignoreCallback) {
delete json;
return;
}
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this, "OneDriveListDirectoryRequest::listedDirectoryCallback: unknown error");
const Networking::HttpJsonRequest *rq = (const Networking::HttpJsonRequest *)response.request;
if (rq && rq->getNetworkReadStream())
error.httpResponseCode = rq->getNetworkReadStream()->httpResponseCode();
if (json == nullptr) {
error.response = "Failed to parse JSON, null passed!";
finishError(error);
return;
}
if (!json->isObject()) {
error.response = "Passed JSON is not an object!";
finishError(error);
delete json;
return;
}
Common::JSONObject object = json->asObject();
//check that ALL keys exist AND HAVE RIGHT TYPE to avoid segfaults
if (!Networking::HttpJsonRequest::jsonContainsArray(object, "value", "OneDriveListDirectoryRequest")) {
error.response = "\"value\" not found or that's not an array!";
finishError(error);
delete json;
return;
}
Common::JSONArray items = object.getVal("value")->asArray();
for (uint32 i = 0; i < items.size(); ++i) {
if (!Networking::HttpJsonRequest::jsonIsObject(items[i], "OneDriveListDirectoryRequest")) continue;
Common::JSONObject item = items[i]->asObject();
if (!Networking::HttpJsonRequest::jsonContainsAttribute(item, "folder", "OneDriveListDirectoryRequest", true)) continue;
if (!Networking::HttpJsonRequest::jsonContainsString(item, "name", "OneDriveListDirectoryRequest")) continue;
if (!Networking::HttpJsonRequest::jsonContainsIntegerNumber(item, "size", "OneDriveListDirectoryRequest")) continue;
if (!Networking::HttpJsonRequest::jsonContainsString(item, "lastModifiedDateTime", "OneDriveListDirectoryRequest")) continue;
Common::String path = _currentDirectory + item.getVal("name")->asString();
bool isDirectory = item.contains("folder");
uint32 size = item.getVal("size")->asIntegerNumber();
uint32 timestamp = ISO8601::convertToTimestamp(item.getVal("lastModifiedDateTime")->asString());
StorageFile file(path, size, timestamp, isDirectory);
_files.push_back(file);
if (_requestedRecursive && file.isDirectory()) {
_directoriesQueue.push_back(file.path());
}
}
bool hasMore = object.contains("@odata.nextLink");
if (hasMore) {
if (!Networking::HttpJsonRequest::jsonContainsString(object, "@odata.nextLink", "OneDriveListDirectoryRequest")) {
error.response = "\"@odata.nextLink\" is not a string!";
finishError(error);
delete json;
return;
}
makeRequest(object.getVal("@odata.nextLink")->asString());
} else {
listNextDirectory();
}
delete json;
}
void OneDriveListDirectoryRequest::listedDirectoryErrorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
void OneDriveListDirectoryRequest::handle() {}
void OneDriveListDirectoryRequest::restart() { start(); }
Common::String OneDriveListDirectoryRequest::date() const { return _date; }
void OneDriveListDirectoryRequest::finishListing(const Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace OneDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,65 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BACKENDS_CLOUD_ONEDRIVE_ONEDRIVELISTDIRECTORYREQUEST_H
#define BACKENDS_CLOUD_ONEDRIVE_ONEDRIVELISTDIRECTORYREQUEST_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/httpjsonrequest.h"
#include "backends/networking/http/request.h"
#include "common/callback.h"
namespace Cloud {
namespace OneDrive {
class OneDriveStorage;
class OneDriveListDirectoryRequest: public Networking::Request {
Common::String _requestedPath;
bool _requestedRecursive;
OneDriveStorage *_storage;
Storage::ListDirectoryCallback _listDirectoryCallback;
Common::Array<StorageFile> _files;
Common::Array<Common::String> _directoriesQueue;
Common::String _currentDirectory;
Request *_workingRequest;
bool _ignoreCallback;
Common::String _date;
void start();
void listNextDirectory();
void listedDirectoryCallback(const Networking::JsonResponse &response);
void listedDirectoryErrorCallback(const Networking::ErrorResponse &error);
void makeRequest(const Common::String &url);
void finishListing(const Common::Array<StorageFile> &files);
public:
OneDriveListDirectoryRequest(OneDriveStorage *storage, const Common::String &path, Storage::ListDirectoryCallback cb, Networking::ErrorCallback ecb, bool recursive = false);
~OneDriveListDirectoryRequest() override;
void handle() override;
void restart() override;
Common::String date() const override;
};
} // End of namespace OneDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,220 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "backends/cloud/onedrive/onedrivestorage.h"
#include "backends/cloud/cloudmanager.h"
#include "backends/cloud/onedrive/onedrivecreatedirectoryrequest.h"
#include "backends/cloud/onedrive/onedrivetokenrefresher.h"
#include "backends/cloud/onedrive/onedrivelistdirectoryrequest.h"
#include "backends/cloud/onedrive/onedriveuploadrequest.h"
#include "backends/networking/http/connectionmanager.h"
#include "backends/networking/http/httpjsonrequest.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/config-manager.h"
#include "common/debug.h"
#include "common/formats/json.h"
namespace Cloud {
namespace OneDrive {
#define ONEDRIVE_API_SPECIAL_APPROOT_ID "https://graph.microsoft.com/v1.0/drive/special/approot:/"
#define ONEDRIVE_API_SPECIAL_APPROOT "https://graph.microsoft.com/v1.0/drive/special/approot"
OneDriveStorage::OneDriveStorage(const Common::String &token, const Common::String &refreshToken, bool enabled):
BaseStorage(token, refreshToken, enabled) {}
OneDriveStorage::OneDriveStorage(const Common::String &code, Networking::ErrorCallback cb) {
getAccessToken(code, cb);
}
OneDriveStorage::OneDriveStorage(const Networking::JsonResponse &codeFlowJson, Networking::ErrorCallback cb) {
codeFlowComplete(cb, codeFlowJson);
}
OneDriveStorage::~OneDriveStorage() {}
Common::String OneDriveStorage::cloudProvider() { return "onedrive"; }
uint32 OneDriveStorage::storageIndex() { return kStorageOneDriveId; }
bool OneDriveStorage::needsRefreshToken() { return true; }
bool OneDriveStorage::canReuseRefreshToken() { return false; }
void OneDriveStorage::saveConfig(const Common::String &keyPrefix) {
ConfMan.set(keyPrefix + "access_token", _token, ConfMan.kCloudDomain);
ConfMan.set(keyPrefix + "refresh_token", _refreshToken, ConfMan.kCloudDomain);
saveIsEnabledFlag(keyPrefix);
}
Common::String OneDriveStorage::name() const {
return "OneDrive";
}
void OneDriveStorage::infoInnerCallback(StorageInfoCallback outerCallback, const Networking::JsonResponse &response) {
const Common::JSONValue *json = response.value;
if (!json) {
warning("OneDriveStorage::infoInnerCallback: NULL passed instead of JSON");
delete outerCallback;
return;
}
if (!Networking::HttpJsonRequest::jsonIsObject(json, "OneDriveStorage::infoInnerCallback")) {
delete json;
delete outerCallback;
return;
}
Common::JSONObject jsonInfo = json->asObject();
Common::String uid, displayName, email;
uint64 quotaUsed = 0, quotaAllocated = 26843545600LL; // 25 GB, because I actually don't know any way to find out the real one
if (Networking::HttpJsonRequest::jsonContainsObject(jsonInfo, "createdBy", "OneDriveStorage::infoInnerCallback")) {
Common::JSONObject createdBy = jsonInfo.getVal("createdBy")->asObject();
if (Networking::HttpJsonRequest::jsonContainsObject(createdBy, "user", "OneDriveStorage::infoInnerCallback")) {
Common::JSONObject user = createdBy.getVal("user")->asObject();
if (Networking::HttpJsonRequest::jsonContainsString(user, "id", "OneDriveStorage::infoInnerCallback"))
uid = user.getVal("id")->asString();
if (Networking::HttpJsonRequest::jsonContainsString(user, "displayName", "OneDriveStorage::infoInnerCallback"))
displayName = user.getVal("displayName")->asString();
}
}
if (Networking::HttpJsonRequest::jsonContainsIntegerNumber(jsonInfo, "size", "OneDriveStorage::infoInnerCallback")) {
quotaUsed = jsonInfo.getVal("size")->asIntegerNumber();
}
Common::String username = email;
if (username == "")
username = displayName;
if (username == "")
username = uid;
CloudMan.setStorageUsername(kStorageOneDriveId, username);
if (outerCallback) {
(*outerCallback)(StorageInfoResponse(nullptr, StorageInfo(uid, displayName, email, quotaUsed, quotaAllocated)));
delete outerCallback;
}
delete json;
}
void OneDriveStorage::fileInfoCallback(Networking::NetworkReadStreamCallback outerCallback, const Networking::JsonResponse &response) {
const Common::JSONValue *json = response.value;
if (!json) {
warning("OneDriveStorage::fileInfoCallback: NULL passed instead of JSON");
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
delete outerCallback;
return;
}
if (!Networking::HttpJsonRequest::jsonIsObject(json, "OneDriveStorage::fileInfoCallback")) {
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
delete json;
delete outerCallback;
return;
}
Common::JSONObject result = response.value->asObject();
if (!Networking::HttpJsonRequest::jsonContainsString(result, "@microsoft.graph.downloadUrl", "OneDriveStorage::fileInfoCallback")) {
warning("OneDriveStorage: downloadUrl not found in passed JSON");
debug(9, "%s", response.value->stringify().c_str());
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(response.request, nullptr));
delete json;
delete outerCallback;
return;
}
const char *url = result.getVal("@microsoft.graph.downloadUrl")->asString().c_str();
if (outerCallback)
(*outerCallback)(Networking::NetworkReadStreamResponse(
response.request,
Networking::NetworkReadStream::make(url, nullptr, "")
));
delete json;
delete outerCallback;
}
Networking::Request *OneDriveStorage::listDirectory(const Common::String &path, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback, bool recursive) {
debug(9, "OneDrive: `ls \"%s\"`", path.c_str());
return addRequest(new OneDriveListDirectoryRequest(this, path, callback, errorCallback, recursive));
}
Networking::Request *OneDriveStorage::upload(const Common::String &path, Common::SeekableReadStream *contents, UploadCallback callback, Networking::ErrorCallback errorCallback) {
debug(9, "OneDrive: `upload \"%s\"`", path.c_str());
return addRequest(new OneDriveUploadRequest(this, path, contents, callback, errorCallback));
}
Networking::Request *OneDriveStorage::streamFileById(const Common::String &path, Networking::NetworkReadStreamCallback outerCallback, Networking::ErrorCallback errorCallback) {
debug(9, "OneDrive: `download \"%s\"`", path.c_str());
Common::String url = ONEDRIVE_API_SPECIAL_APPROOT_ID + Common::percentEncodeString(path);
Networking::JsonCallback innerCallback = new Common::CallbackBridge<OneDriveStorage, const Networking::NetworkReadStreamResponse &, const Networking::JsonResponse &>(this, &OneDriveStorage::fileInfoCallback, outerCallback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(this, innerCallback, errorCallback, url.c_str());
request->addHeader("Authorization: bearer " + _token);
return addRequest(request);
}
Networking::Request *OneDriveStorage::createDirectory(const Common::String &path, BoolCallback callback, Networking::ErrorCallback errorCallback) {
debug(9, "OneDrive: `mkdir \"%s\"`", path.c_str());
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
return addRequest(new OneDriveCreateDirectoryRequest(this, path, callback, errorCallback));
}
Networking::Request *OneDriveStorage::info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
debug(9, "OneDrive: `info`");
Networking::JsonCallback innerCallback = new Common::CallbackBridge<OneDriveStorage, const StorageInfoResponse &, const Networking::JsonResponse &>(this, &OneDriveStorage::infoInnerCallback, callback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(this, innerCallback, errorCallback, ONEDRIVE_API_SPECIAL_APPROOT);
request->addHeader("Authorization: bearer " + _token);
return addRequest(request);
}
Common::String OneDriveStorage::savesDirectoryPath() { return "saves/"; }
OneDriveStorage *OneDriveStorage::loadFromConfig(const Common::String &keyPrefix) {
if (!ConfMan.hasKey(keyPrefix + "access_token", ConfMan.kCloudDomain)) {
warning("OneDriveStorage: no access_token found");
return nullptr;
}
if (!ConfMan.hasKey(keyPrefix + "refresh_token", ConfMan.kCloudDomain)) {
warning("OneDriveStorage: no refresh_token found");
return nullptr;
}
Common::String accessToken = ConfMan.get(keyPrefix + "access_token", ConfMan.kCloudDomain);
Common::String refreshToken = ConfMan.get(keyPrefix + "refresh_token", ConfMan.kCloudDomain);
return new OneDriveStorage(accessToken, refreshToken, loadIsEnabledFlag(keyPrefix));
}
void OneDriveStorage::removeFromConfig(const Common::String &keyPrefix) {
ConfMan.removeKey(keyPrefix + "access_token", ConfMan.kCloudDomain);
ConfMan.removeKey(keyPrefix + "refresh_token", ConfMan.kCloudDomain);
removeIsEnabledFlag(keyPrefix);
}
} // End of namespace OneDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,120 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BACKENDS_CLOUD_ONEDRIVE_ONEDRIVESTORAGE_H
#define BACKENDS_CLOUD_ONEDRIVE_ONEDRIVESTORAGE_H
#include "backends/cloud/basestorage.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace OneDrive {
class OneDriveStorage: public Cloud::BaseStorage {
/** This private constructor is called from loadFromConfig(). */
OneDriveStorage(const Common::String &token, const Common::String &refreshToken, bool enabled);
/** Constructs StorageInfo based on JSON response from cloud. */
void infoInnerCallback(StorageInfoCallback outerCallback, const Networking::JsonResponse &json);
void fileInfoCallback(Networking::NetworkReadStreamCallback outerCallback, const Networking::JsonResponse &response);
protected:
/**
* @return "onedrive"
*/
Common::String cloudProvider() override;
/**
* @return kStorageOneDriveId
*/
uint32 storageIndex() override;
bool needsRefreshToken() override;
bool canReuseRefreshToken() override;
public:
/** This constructor uses OAuth code flow to get tokens. */
OneDriveStorage(const Common::String &code, Networking::ErrorCallback cb);
/** This constructor extracts tokens from JSON acquired via OAuth code flow. */
OneDriveStorage(const Networking::JsonResponse &codeFlowJson, Networking::ErrorCallback cb);
~OneDriveStorage() override;
/**
* Storage methods, which are used by CloudManager to save
* storage in configuration file.
*/
/**
* Save storage data using ConfMan.
* @param keyPrefix all saved keys must start with this prefix.
* @note every Storage must write keyPrefix + "type" key
* with common value (e.g. "Dropbox").
*/
void saveConfig(const Common::String &keyPrefix) override;
/**
* Return unique storage name.
* @returns some unique storage name (for example, "Dropbox (user@example.com)")
*/
Common::String name() const override;
/** Public Cloud API comes down there. */
/** Returns ListDirectoryStatus struct with list of files. */
Networking::Request *listDirectory(const Common::String &path, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback, bool recursive = false) override;
/** Returns UploadStatus struct with info about uploaded file. */
Networking::Request *upload(const Common::String &path, Common::SeekableReadStream *contents, UploadCallback callback, Networking::ErrorCallback errorCallback) override;
/** Returns pointer to Networking::NetworkReadStream. */
Networking::Request *streamFileById(const Common::String &path, Networking::NetworkReadStreamCallback callback, Networking::ErrorCallback errorCallback) override;
/** Calls the callback when finished. */
Networking::Request *createDirectory(const Common::String &path, BoolCallback callback, Networking::ErrorCallback errorCallback) override;
/** Returns the StorageInfo struct. */
Networking::Request *info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) override;
/** Returns storage's saves directory path with the trailing slash. */
Common::String savesDirectoryPath() override;
/**
* Load token and user id from configs and return OneDriveStorage for those.
* @return pointer to the newly created OneDriveStorage or 0 if some problem occurred.
*/
static OneDriveStorage *loadFromConfig(const Common::String &keyPrefix);
/**
* Remove all OneDriveStorage-related data from config.
*/
static void removeFromConfig(const Common::String &keyPrefix);
Common::String accessToken() const { return _token; }
};
} // End of namespace OneDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,142 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "backends/cloud/onedrive/onedrivetokenrefresher.h"
#include "backends/cloud/onedrive/onedrivestorage.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/debug.h"
#include "common/formats/json.h"
namespace Cloud {
namespace OneDrive {
OneDriveTokenRefresher::OneDriveTokenRefresher(OneDriveStorage *parent, Networking::JsonCallback callback, Networking::ErrorCallback ecb, const char *url):
HttpJsonRequest(callback, ecb, url), _parentStorage(parent) {}
OneDriveTokenRefresher::~OneDriveTokenRefresher() {}
void OneDriveTokenRefresher::tokenRefreshed(const Storage::BoolResponse &response) {
if (!response.value) {
//failed to refresh token, notify user with NULL in original callback
warning("OneDriveTokenRefresher: failed to refresh token");
finishError(Networking::ErrorResponse(this, false, true, "OneDriveTokenRefresher::tokenRefreshed: failed to refresh token", -1));
return;
}
//update headers: first change header with token, then pass those to request
for (uint32 i = 0; i < _headersList.size(); ++i) {
if (_headersList[i].contains("Authorization")) {
_headersList[i] = "Authorization: bearer " + _parentStorage->accessToken();
}
}
//successfully received refreshed token, can restart the original request now
retry(0);
}
void OneDriveTokenRefresher::finishJson(const Common::JSONValue *json) {
if (!json) {
//that's probably not an error (200 OK)
HttpJsonRequest::finishJson(nullptr);
return;
}
if (jsonIsObject(json, "OneDriveTokenRefresher")) {
Common::JSONObject result = json->asObject();
long httpResponseCode = -1;
if (result.contains("error") && jsonIsObject(result.getVal("error"), "OneDriveTokenRefresher")) {
//new token needed => request token & then retry original request
if (_stream) {
httpResponseCode = _stream->httpResponseCode();
debug(9, "OneDriveTokenRefresher: code = %ld", httpResponseCode);
}
Common::JSONObject error = result.getVal("error")->asObject();
bool irrecoverable = true;
Common::String code, message;
if (jsonContainsString(error, "code", "OneDriveTokenRefresher")) {
code = error.getVal("code")->asString();
debug(9, "OneDriveTokenRefresher: code = %s", code.c_str());
}
if (jsonContainsString(error, "message", "OneDriveTokenRefresher")) {
message = error.getVal("message")->asString();
debug(9, "OneDriveTokenRefresher: message = %s", message.c_str());
}
//determine whether token refreshing would help in this situation
if (code == "itemNotFound") {
if (message.contains("application ID"))
irrecoverable = false;
}
if (code == "unauthenticated" || code == "InvalidAuthenticationToken")
irrecoverable = false;
if (irrecoverable) {
Common::String errorContents = json->stringify(true);
finishErrorIrrecoverable(Networking::ErrorResponse(this, false, true, errorContents, httpResponseCode));
delete json;
return;
}
pause();
delete json;
_parentStorage->refreshAccessToken(new Common::Callback<OneDriveTokenRefresher, const Storage::BoolResponse &>(this, &OneDriveTokenRefresher::tokenRefreshed));
return;
}
}
//notify user of success
HttpJsonRequest::finishJson(json);
}
void OneDriveTokenRefresher::finishError(const Networking::ErrorResponse &error, Networking::RequestState state) {
if (error.failed) {
Common::JSONValue *value = Common::JSON::parse(error.response);
//somehow OneDrive returns JSON with '.' in unexpected places, try fixing it
if (!value) {
Common::String fixedResponse = error.response;
for (uint32 i = 0; i < fixedResponse.size(); ++i) {
if (fixedResponse[i] == '.')
fixedResponse.replace(i, 1, " ");
}
value = Common::JSON::parse(fixedResponse);
}
if (value) {
finishJson(value);
return;
}
}
Request::finishError(error, state); //call closest base class's method
}
void OneDriveTokenRefresher::finishErrorIrrecoverable(const Networking::ErrorResponse &error, Networking::RequestState state) {
// don't try to fix JSON as this is irrecoverable version
Request::finishError(error, state); // call closest base class's method
}
} // End of namespace OneDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,50 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BACKENDS_CLOUD_ONEDRIVE_ONEDRIVETOKENREFRESHER_H
#define BACKENDS_CLOUD_ONEDRIVE_ONEDRIVETOKENREFRESHER_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace OneDrive {
class OneDriveStorage;
class OneDriveTokenRefresher: public Networking::HttpJsonRequest {
OneDriveStorage *_parentStorage;
void tokenRefreshed(const Storage::BoolResponse &response);
void finishJson(const Common::JSONValue *json) override;
void finishError(const Networking::ErrorResponse &error, Networking::RequestState state = Networking::FINISHED) override;
void finishErrorIrrecoverable(const Networking::ErrorResponse &error, Networking::RequestState state = Networking::FINISHED);
public:
OneDriveTokenRefresher(OneDriveStorage *parent, Networking::JsonCallback callback, Networking::ErrorCallback ecb, const char *url);
~OneDriveTokenRefresher() override;
};
} // End of namespace OneDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,192 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "backends/cloud/onedrive/onedriveuploadrequest.h"
#include "backends/cloud/onedrive/onedrivestorage.h"
#include "backends/cloud/iso8601.h"
#include "backends/cloud/storage.h"
#include "backends/networking/http/connectionmanager.h"
#include "backends/networking/http/httpjsonrequest.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/formats/json.h"
#include "onedrivetokenrefresher.h"
namespace Cloud {
namespace OneDrive {
#define ONEDRIVE_API_SPECIAL_APPROOT_UPLOAD "https://graph.microsoft.com/v1.0/drive/special/approot:/%s:/upload.createSession"
#define ONEDRIVE_API_SPECIAL_APPROOT_CONTENT "https://graph.microsoft.com/v1.0/drive/special/approot:/%s:/content"
OneDriveUploadRequest::OneDriveUploadRequest(OneDriveStorage *storage, const Common::String &path, Common::SeekableReadStream *contents, Storage::UploadCallback callback, Networking::ErrorCallback ecb):
Networking::Request(nullptr, ecb), _storage(storage), _savePath(path), _contentsStream(contents), _uploadCallback(callback),
_workingRequest(nullptr), _ignoreCallback(false) {
start();
}
OneDriveUploadRequest::~OneDriveUploadRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _contentsStream;
delete _uploadCallback;
}
void OneDriveUploadRequest::start() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
if (_contentsStream == nullptr) {
warning("OneDriveUploadRequest: cannot restart because no stream given");
finishError(Networking::ErrorResponse(this, false, true, "OneDriveUploadRequest::start: can't restart, because no stream given", -1));
return;
}
if (!_contentsStream->seek(0)) {
warning("OneDriveUploadRequest: cannot restart because stream couldn't seek(0)");
finishError(Networking::ErrorResponse(this, false, true, "OneDriveUploadRequest::start: can't restart, because seek(0) didn't work", -1));
return;
}
_ignoreCallback = false;
uploadNextPart();
}
void OneDriveUploadRequest::uploadNextPart() {
const uint32 UPLOAD_PER_ONE_REQUEST = 10 * 1024 * 1024;
if (_uploadUrl == "" && (uint32)_contentsStream->size() > UPLOAD_PER_ONE_REQUEST) {
Common::String url = Common::String::format(ONEDRIVE_API_SPECIAL_APPROOT_UPLOAD, Common::percentEncodeString(_savePath).c_str()); //folder must exist
Networking::JsonCallback callback = new Common::Callback<OneDriveUploadRequest, const Networking::JsonResponse &>(this, &OneDriveUploadRequest::partUploadedCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<OneDriveUploadRequest, const Networking::ErrorResponse &>(this, &OneDriveUploadRequest::partUploadedErrorCallback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
request->setBuffer(new byte[1], 0); //use POST
_workingRequest = ConnMan.addRequest(request);
return;
}
Common::String url;
if (_uploadUrl == "") {
url = Common::String::format(ONEDRIVE_API_SPECIAL_APPROOT_CONTENT, Common::percentEncodeString(_savePath).c_str());
} else {
url = _uploadUrl;
}
Networking::JsonCallback callback = new Common::Callback<OneDriveUploadRequest, const Networking::JsonResponse &>(this, &OneDriveUploadRequest::partUploadedCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<OneDriveUploadRequest, const Networking::ErrorResponse &>(this, &OneDriveUploadRequest::partUploadedErrorCallback);
Networking::HttpJsonRequest *request = new OneDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
request->usePut();
uint32 oldPos = _contentsStream->pos();
byte *buffer = new byte[UPLOAD_PER_ONE_REQUEST];
uint32 size = _contentsStream->read(buffer, UPLOAD_PER_ONE_REQUEST);
request->setBuffer(buffer, size);
if (_uploadUrl != "") {
request->addHeader(Common::String::format("Content-Range: bytes %u-%lu/%lu", oldPos,
static_cast<unsigned long>(_contentsStream->pos() - 1),
static_cast<unsigned long>(_contentsStream->size())));
} else if (_contentsStream->size() == 0) {
warning("\"Sorry, OneDrive can't upload empty files\"");
finishUpload(StorageFile(_savePath, 0, 0, false));
delete request;
return;
}
_workingRequest = ConnMan.addRequest(request);
}
void OneDriveUploadRequest::partUploadedCallback(const Networking::JsonResponse &response) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "", -1);
const Networking::HttpJsonRequest *rq = (const Networking::HttpJsonRequest *)response.request;
if (rq && rq->getNetworkReadStream())
error.httpResponseCode = rq->getNetworkReadStream()->httpResponseCode();
const Common::JSONValue *json = response.value;
if (json == nullptr) {
error.response = "Failed to parse JSON, null passed!";
finishError(error);
return;
}
if (json->isObject()) {
Common::JSONObject object = json->asObject();
if (object.contains("error")) {
warning("OneDriveUploadRequest: error: %s", json->stringify(true).c_str());
error.response = json->stringify(true);
finishError(error);
delete json;
return;
}
if (Networking::HttpJsonRequest::jsonContainsString(object, "id", "OneDriveUploadRequest") &&
Networking::HttpJsonRequest::jsonContainsString(object, "name", "OneDriveUploadRequest") &&
Networking::HttpJsonRequest::jsonContainsIntegerNumber(object, "size", "OneDriveUploadRequest") &&
Networking::HttpJsonRequest::jsonContainsString(object, "lastModifiedDateTime", "OneDriveUploadRequest")) {
//finished
Common::String path = _savePath;
uint32 size = object.getVal("size")->asIntegerNumber();
uint32 timestamp = ISO8601::convertToTimestamp(object.getVal("lastModifiedDateTime")->asString());
finishUpload(StorageFile(path, size, timestamp, false));
return;
}
if (_uploadUrl == "") {
if (Networking::HttpJsonRequest::jsonContainsString(object, "uploadUrl", "OneDriveUploadRequest"))
_uploadUrl = object.getVal("uploadUrl")->asString();
}
}
if (_contentsStream->eos() || _contentsStream->pos() >= _contentsStream->size() - 1) {
warning("OneDriveUploadRequest: no file info to return");
finishUpload(StorageFile(_savePath, 0, 0, false));
} else {
uploadNextPart();
}
delete json;
}
void OneDriveUploadRequest::partUploadedErrorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
finishError(error);
}
void OneDriveUploadRequest::handle() {}
void OneDriveUploadRequest::restart() { start(); }
void OneDriveUploadRequest::finishUpload(const StorageFile &file) {
Request::finishSuccess();
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace OneDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,60 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BACKENDS_CLOUD_ONEDRIVE_ONEDRIVEUPLOADREQUEST_H
#define BACKENDS_CLOUD_ONEDRIVE_ONEDRIVEUPLOADREQUEST_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/httpjsonrequest.h"
#include "backends/networking/http/request.h"
#include "common/callback.h"
namespace Cloud {
namespace OneDrive {
class OneDriveStorage;
class OneDriveUploadRequest: public Networking::Request {
OneDriveStorage *_storage;
Common::String _savePath;
Common::SeekableReadStream *_contentsStream;
Storage::UploadCallback _uploadCallback;
Request *_workingRequest;
bool _ignoreCallback;
Common::String _uploadUrl;
void start();
void uploadNextPart();
void partUploadedCallback(const Networking::JsonResponse &response);
void partUploadedErrorCallback(const Networking::ErrorResponse &error);
void finishUpload(const StorageFile &status);
public:
OneDriveUploadRequest(OneDriveStorage *storage, const Common::String &path, Common::SeekableReadStream *contents, Storage::UploadCallback callback, Networking::ErrorCallback ecb);
~OneDriveUploadRequest() override;
void handle() override;
void restart() override;
};
} // End of namespace OneDrive
} // End of namespace Cloud
#endif