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,162 @@
/* 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/googledrive/googledrivelistdirectorybyidrequest.h"
#include "backends/cloud/googledrive/googledrivestorage.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 "googledrivetokenrefresher.h"
namespace Cloud {
namespace GoogleDrive {
#define GOOGLEDRIVE_API_FILES "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
GoogleDriveListDirectoryByIdRequest::GoogleDriveListDirectoryByIdRequest(GoogleDriveStorage *storage, const Common::String &id, Storage::ListDirectoryCallback cb, Networking::ErrorCallback ecb):
Networking::Request(nullptr, ecb), _requestedId(id), _storage(storage), _listDirectoryCallback(cb),
_workingRequest(nullptr), _ignoreCallback(false) {
start();
}
GoogleDriveListDirectoryByIdRequest::~GoogleDriveListDirectoryByIdRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _listDirectoryCallback;
}
void GoogleDriveListDirectoryByIdRequest::start() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
_files.clear();
_ignoreCallback = false;
makeRequest("");
}
void GoogleDriveListDirectoryByIdRequest::makeRequest(const Common::String &pageToken) {
Common::String url = GOOGLEDRIVE_API_FILES;
if (pageToken != "")
url += "&pageToken=" + pageToken;
url += "&q=%27" + _requestedId + "%27+in+parents";
Networking::JsonCallback callback = new Common::Callback<GoogleDriveListDirectoryByIdRequest, const Networking::JsonResponse &>(this, &GoogleDriveListDirectoryByIdRequest::responseCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<GoogleDriveListDirectoryByIdRequest, const Networking::ErrorResponse &>(this, &GoogleDriveListDirectoryByIdRequest::errorCallback);
Networking::HttpJsonRequest *request = new GoogleDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
_workingRequest = ConnMan.addRequest(request);
}
void GoogleDriveListDirectoryByIdRequest::responseCallback(const Networking::JsonResponse &response) {
_workingRequest = nullptr;
if (_ignoreCallback) {
delete response.value;
return;
}
if (response.request)
_date = response.request->date();
Networking::ErrorResponse error(this, "GoogleDriveListDirectoryByIdRequest::responseCallback");
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) {
Common::JSONObject responseObject = json->asObject();
///debug("%s", json->stringify(true).c_str());
if (responseObject.contains("error") || responseObject.contains("error_summary")) {
warning("GoogleDrive returned error: %s", responseObject.getVal("error_summary")->asString().c_str());
error.failed = true;
error.response = json->stringify();
finishError(error);
delete json;
return;
}
//TODO: check that ALL keys exist AND HAVE RIGHT TYPE to avoid segfaults
if (responseObject.contains("files") && responseObject.getVal("files")->isArray()) {
Common::JSONArray items = responseObject.getVal("files")->asArray();
for (uint32 i = 0; i < items.size(); ++i) {
Common::JSONObject item = items[i]->asObject();
Common::String id = item.getVal("id")->asString();
Common::String name = item.getVal("name")->asString();
bool isDirectory = (item.getVal("mimeType")->asString() == "application/vnd.google-apps.folder");
uint32 size = 0, timestamp = 0;
if (item.contains("size") && item.getVal("size")->isString())
size = item.getVal("size")->asString().asUint64();
if (item.contains("modifiedTime") && item.getVal("modifiedTime")->isString())
timestamp = ISO8601::convertToTimestamp(item.getVal("modifiedTime")->asString());
//as we list directory by id, we can't determine full path for the file, so we leave it empty
_files.push_back(StorageFile(id, "", name, size, timestamp, isDirectory));
}
}
bool hasMore = (responseObject.contains("nextPageToken"));
if (hasMore) {
Common::String token = responseObject.getVal("nextPageToken")->asString();
makeRequest(token);
} else {
finishListing(_files);
}
} else {
warning("null, not json");
error.failed = true;
finishError(error);
}
delete json;
}
void GoogleDriveListDirectoryByIdRequest::errorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
if (error.request)
_date = error.request->date();
finishError(error);
}
void GoogleDriveListDirectoryByIdRequest::handle() {}
void GoogleDriveListDirectoryByIdRequest::restart() { start(); }
Common::String GoogleDriveListDirectoryByIdRequest::date() const { return _date; }
void GoogleDriveListDirectoryByIdRequest::finishListing(Common::Array<StorageFile> &files) {
Request::finishSuccess();
if (_listDirectoryCallback)
(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
}
} // End of namespace GoogleDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,62 @@
/* 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_GOOGLEDRIVE_GOOGLEDRIVELISTDIRECTORYBYIDREQUEST_H
#define BACKENDS_CLOUD_GOOGLEDRIVE_GOOGLEDRIVELISTDIRECTORYBYIDREQUEST_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/request.h"
#include "common/callback.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace GoogleDrive {
class GoogleDriveStorage;
class GoogleDriveListDirectoryByIdRequest: public Networking::Request {
Common::String _requestedId;
GoogleDriveStorage *_storage;
Storage::ListDirectoryCallback _listDirectoryCallback;
Common::Array<StorageFile> _files;
Request *_workingRequest;
bool _ignoreCallback;
Common::String _date;
void start();
void makeRequest(const Common::String &pageToken);
void responseCallback(const Networking::JsonResponse &response);
void errorCallback(const Networking::ErrorResponse &error);
void finishListing(Common::Array<StorageFile> &files);
public:
GoogleDriveListDirectoryByIdRequest(GoogleDriveStorage *storage, const Common::String &id, Storage::ListDirectoryCallback cb, Networking::ErrorCallback ecb);
~GoogleDriveListDirectoryByIdRequest() override;
void handle() override;
void restart() override;
Common::String date() const override;
};
} // End of namespace GoogleDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,249 @@
/* 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/googledrive/googledrivestorage.h"
#include "backends/cloud/cloudmanager.h"
#include "backends/cloud/googledrive/googledrivetokenrefresher.h"
#include "backends/cloud/googledrive/googledrivelistdirectorybyidrequest.h"
#include "backends/cloud/googledrive/googledriveuploadrequest.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"
#include "common/debug.h"
namespace Cloud {
namespace GoogleDrive {
#define GOOGLEDRIVE_API_FILES_ALT_MEDIA "https://www.googleapis.com/drive/v3/files/%s?alt=media"
#define GOOGLEDRIVE_API_FILES "https://www.googleapis.com/drive/v3/files"
#define GOOGLEDRIVE_API_ABOUT "https://www.googleapis.com/drive/v3/about?fields=storageQuota,user"
GoogleDriveStorage::GoogleDriveStorage(const Common::String &token, const Common::String &refreshToken, bool enabled):
IdStorage(token, refreshToken, enabled) {}
GoogleDriveStorage::GoogleDriveStorage(const Common::String &code, Networking::ErrorCallback cb) {
getAccessToken(code, cb);
}
GoogleDriveStorage::GoogleDriveStorage(const Networking::JsonResponse &codeFlowJson, Networking::ErrorCallback cb) {
codeFlowComplete(cb, codeFlowJson);
}
GoogleDriveStorage::~GoogleDriveStorage() {}
Common::String GoogleDriveStorage::cloudProvider() { return "gdrive"; }
uint32 GoogleDriveStorage::storageIndex() { return kStorageGoogleDriveId; }
bool GoogleDriveStorage::needsRefreshToken() { return true; }
bool GoogleDriveStorage::canReuseRefreshToken() { return true; }
void GoogleDriveStorage::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 GoogleDriveStorage::name() const {
return "Google Drive";
}
void GoogleDriveStorage::infoInnerCallback(StorageInfoCallback outerCallback, const Networking::JsonResponse &response) {
const Common::JSONValue *json = response.value;
if (!json) {
warning("GoogleDriveStorage::infoInnerCallback: NULL passed instead of JSON");
delete outerCallback;
return;
}
if (!Networking::HttpJsonRequest::jsonIsObject(json, "GoogleDriveStorage::infoInnerCallback")) {
delete json;
delete outerCallback;
return;
}
Common::JSONObject jsonInfo = json->asObject();
Common::String uid, displayName, email;
uint64 quotaUsed = 0, quotaAllocated = 0;
if (Networking::HttpJsonRequest::jsonContainsAttribute(jsonInfo, "user", "GoogleDriveStorage::infoInnerCallback") &&
Networking::HttpJsonRequest::jsonIsObject(jsonInfo.getVal("user"), "GoogleDriveStorage::infoInnerCallback")) {
//"me":true, "kind":"drive#user","photoLink": "",
//"displayName":"Alexander Tkachev","emailAddress":"alexander@tkachov.ru","permissionId":""
Common::JSONObject user = jsonInfo.getVal("user")->asObject();
if (Networking::HttpJsonRequest::jsonContainsString(user, "permissionId", "GoogleDriveStorage::infoInnerCallback"))
uid = user.getVal("permissionId")->asString(); //not sure it's user's id, but who cares anyway?
if (Networking::HttpJsonRequest::jsonContainsString(user, "displayName", "GoogleDriveStorage::infoInnerCallback"))
displayName = user.getVal("displayName")->asString();
if (Networking::HttpJsonRequest::jsonContainsString(user, "emailAddress", "GoogleDriveStorage::infoInnerCallback"))
email = user.getVal("emailAddress")->asString();
}
if (Networking::HttpJsonRequest::jsonContainsAttribute(jsonInfo, "storageQuota", "GoogleDriveStorage::infoInnerCallback") &&
Networking::HttpJsonRequest::jsonIsObject(jsonInfo.getVal("storageQuota"), "GoogleDriveStorage::infoInnerCallback")) {
//"usageInDrive":"6332462","limit":"18253611008","usage":"6332462","usageInDriveTrash":"0"
Common::JSONObject storageQuota = jsonInfo.getVal("storageQuota")->asObject();
if (Networking::HttpJsonRequest::jsonContainsString(storageQuota, "usage", "GoogleDriveStorage::infoInnerCallback")) {
Common::String usage = storageQuota.getVal("usage")->asString();
quotaUsed = usage.asUint64();
}
if (Networking::HttpJsonRequest::jsonContainsString(storageQuota, "limit", "GoogleDriveStorage::infoInnerCallback")) {
Common::String limit = storageQuota.getVal("limit")->asString();
quotaAllocated = limit.asUint64();
}
}
CloudMan.setStorageUsername(kStorageGoogleDriveId, email);
if (outerCallback) {
(*outerCallback)(StorageInfoResponse(nullptr, StorageInfo(uid, displayName, email, quotaUsed, quotaAllocated)));
delete outerCallback;
}
delete json;
}
void GoogleDriveStorage::createDirectoryInnerCallback(BoolCallback outerCallback, const Networking::JsonResponse &response) {
const Common::JSONValue *json = response.value;
if (!json) {
warning("GoogleDriveStorage::createDirectoryInnerCallback: NULL passed instead of JSON");
delete outerCallback;
return;
}
if (outerCallback) {
if (Networking::HttpJsonRequest::jsonIsObject(json, "GoogleDriveStorage::createDirectoryInnerCallback")) {
Common::JSONObject jsonInfo = json->asObject();
(*outerCallback)(BoolResponse(nullptr, jsonInfo.contains("id")));
} else {
(*outerCallback)(BoolResponse(nullptr, false));
}
delete outerCallback;
}
delete json;
}
Networking::Request *GoogleDriveStorage::listDirectoryById(const Common::String &id, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
if (!callback)
callback = new Common::Callback<GoogleDriveStorage, const FileArrayResponse &>(this, &GoogleDriveStorage::printFiles);
return addRequest(new GoogleDriveListDirectoryByIdRequest(this, id, callback, errorCallback));
}
Networking::Request *GoogleDriveStorage::upload(const Common::String &path, Common::SeekableReadStream *contents, UploadCallback callback, Networking::ErrorCallback errorCallback) {
return addRequest(new GoogleDriveUploadRequest(this, path, contents, callback, errorCallback));
}
Networking::Request *GoogleDriveStorage::streamFileById(const Common::String &id, Networking::NetworkReadStreamCallback callback, Networking::ErrorCallback errorCallback) {
if (callback) {
Common::String url = Common::String::format(GOOGLEDRIVE_API_FILES_ALT_MEDIA, Common::percentEncodeString(id).c_str());
Common::String header = "Authorization: Bearer " + _token;
Networking::RequestHeaders *headersList = new Networking::RequestHeaders();
headersList->push_back(header);
Networking::NetworkReadStream *stream = Networking::NetworkReadStream::make(url.c_str(), headersList, "");
(*callback)(Networking::NetworkReadStreamResponse(nullptr, stream));
}
delete callback;
delete errorCallback;
return nullptr;
}
void GoogleDriveStorage::printInfo(const StorageInfoResponse &response) {
debug(9, "\nGoogleDriveStorage: user info:");
debug(9, "\tname: %s", response.value.name().c_str());
debug(9, "\temail: %s", response.value.email().c_str());
debug(9, "\tdisk usage: %llu/%llu",
(unsigned long long)response.value.used(),
(unsigned long long)response.value.available());
}
Networking::Request *GoogleDriveStorage::createDirectoryWithParentId(const Common::String &parentId, const Common::String &directoryName, BoolCallback callback, Networking::ErrorCallback errorCallback) {
if (!errorCallback)
errorCallback = getErrorPrintingCallback();
Common::String url = GOOGLEDRIVE_API_FILES;
Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, const BoolResponse &, const Networking::JsonResponse &>(this, &GoogleDriveStorage::createDirectoryInnerCallback, callback);
Networking::HttpJsonRequest *request = new GoogleDriveTokenRefresher(this, innerCallback, errorCallback, url.c_str());
request->addHeader("Authorization: Bearer " + accessToken());
request->addHeader("Content-Type: application/json");
Common::JSONArray parentsArray;
parentsArray.push_back(new Common::JSONValue(parentId));
Common::JSONObject jsonRequestParameters;
jsonRequestParameters.setVal("mimeType", new Common::JSONValue("application/vnd.google-apps.folder"));
jsonRequestParameters.setVal("name", new Common::JSONValue(directoryName));
jsonRequestParameters.setVal("parents", new Common::JSONValue(parentsArray));
Common::JSONValue value(jsonRequestParameters);
request->addPostField(Common::JSON::stringify(&value));
return addRequest(request);
}
Networking::Request *GoogleDriveStorage::info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
if (!callback)
callback = new Common::Callback<GoogleDriveStorage, const StorageInfoResponse &>(this, &GoogleDriveStorage::printInfo);
Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, const StorageInfoResponse &, const Networking::JsonResponse &>(this, &GoogleDriveStorage::infoInnerCallback, callback);
Networking::HttpJsonRequest *request = new GoogleDriveTokenRefresher(this, innerCallback, errorCallback, GOOGLEDRIVE_API_ABOUT);
request->addHeader("Authorization: Bearer " + _token);
return addRequest(request);
}
Common::String GoogleDriveStorage::savesDirectoryPath() { return "scummvm/saves/"; }
GoogleDriveStorage *GoogleDriveStorage::loadFromConfig(const Common::String &keyPrefix) {
if (!ConfMan.hasKey(keyPrefix + "access_token", ConfMan.kCloudDomain)) {
warning("GoogleDriveStorage: no access_token found");
return nullptr;
}
if (!ConfMan.hasKey(keyPrefix + "refresh_token", ConfMan.kCloudDomain)) {
warning("GoogleDriveStorage: 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 GoogleDriveStorage(accessToken, refreshToken, loadIsEnabledFlag(keyPrefix));
}
void GoogleDriveStorage::removeFromConfig(const Common::String &keyPrefix) {
ConfMan.removeKey(keyPrefix + "access_token", ConfMan.kCloudDomain);
ConfMan.removeKey(keyPrefix + "refresh_token", ConfMan.kCloudDomain);
removeIsEnabledFlag(keyPrefix);
}
Common::String GoogleDriveStorage::getRootDirectoryId() {
return "root";
}
} // End of namespace GoogleDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,125 @@
/* 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_GOOGLEDRIVE_GOOGLEDRIVESTORAGE_H
#define BACKENDS_CLOUD_GOOGLEDRIVE_GOOGLEDRIVESTORAGE_H
#include "backends/cloud/id/idstorage.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace GoogleDrive {
class GoogleDriveStorage: public Id::IdStorage {
/** This private constructor is called from loadFromConfig(). */
GoogleDriveStorage(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);
/** Returns bool based on JSON response from cloud. */
void createDirectoryInnerCallback(BoolCallback outerCallback, const Networking::JsonResponse &json);
void printInfo(const StorageInfoResponse &response);
protected:
/**
* @return "gdrive"
*/
Common::String cloudProvider() override;
/**
* @return kStorageGoogleDriveId
*/
uint32 storageIndex() override;
bool needsRefreshToken() override;
bool canReuseRefreshToken() override;
public:
/** This constructor uses OAuth code flow to get tokens. */
GoogleDriveStorage(const Common::String &code, Networking::ErrorCallback cb);
/** This constructor extracts tokens from JSON acquired via OAuth code flow. */
GoogleDriveStorage(const Networking::JsonResponse &codeFlowJson, Networking::ErrorCallback cb);
~GoogleDriveStorage() 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 Array<StorageFile> - the list of files. */
Networking::Request *listDirectoryById(const Common::String &id, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback) 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 &id, Networking::NetworkReadStreamCallback callback, Networking::ErrorCallback errorCallback) override;
/** Calls the callback when finished. */
Networking::Request *createDirectoryWithParentId(const Common::String &parentId, const Common::String &directoryName, 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 GoogleDriveStorage for those.
* @return pointer to the newly created GoogleDriveStorage or 0 if some problem occurred.
*/
static GoogleDriveStorage *loadFromConfig(const Common::String &keyPrefix);
/**
* Remove all GoogleDriveStorage-related data from config.
*/
static void removeFromConfig(const Common::String &keyPrefix);
Common::String getRootDirectoryId() override;
Common::String accessToken() const { return _token; }
};
} // End of namespace GoogleDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,108 @@
/* 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/googledrive/googledrivetokenrefresher.h"
#include "backends/cloud/googledrive/googledrivestorage.h"
#include "backends/networking/http/networkreadstream.h"
#include "common/debug.h"
#include "common/formats/json.h"
namespace Cloud {
namespace GoogleDrive {
GoogleDriveTokenRefresher::GoogleDriveTokenRefresher(GoogleDriveStorage *parent, Networking::JsonCallback callback, Networking::ErrorCallback ecb, const char *url):
HttpJsonRequest(callback, ecb, url), _parentStorage(parent) {}
GoogleDriveTokenRefresher::~GoogleDriveTokenRefresher() {}
void GoogleDriveTokenRefresher::tokenRefreshed(const Storage::BoolResponse &response) {
if (!response.value) {
//failed to refresh token, notify user with NULL in original callback
warning("GoogleDriveTokenRefresher: failed to refresh token");
finishError(Networking::ErrorResponse(this, false, true, "GoogleDriveTokenRefresher::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 GoogleDriveTokenRefresher::finishJson(const Common::JSONValue *json) {
if (!json) {
//that's probably not an error (200 OK)
HttpJsonRequest::finishJson(nullptr);
return;
}
if (jsonIsObject(json, "GoogleDriveTokenRefresher")) {
Common::JSONObject result = json->asObject();
long httpResponseCode = -1;
if (result.contains("error") && jsonIsObject(result.getVal("error"), "GoogleDriveTokenRefresher")) {
//new token needed => request token & then retry original request
if (_stream) {
httpResponseCode = _stream->httpResponseCode();
debug(9, "GoogleDriveTokenRefresher: code = %ld", httpResponseCode);
}
Common::JSONObject error = result.getVal("error")->asObject();
bool irrecoverable = true;
uint32 code = 0xFFFFFFFF; // Invalid
Common::String message;
if (jsonContainsIntegerNumber(error, "code", "GoogleDriveTokenRefresher")) {
code = error.getVal("code")->asIntegerNumber();
debug(9, "GoogleDriveTokenRefresher: code = %u", code);
}
if (jsonContainsString(error, "message", "GoogleDriveTokenRefresher")) {
message = error.getVal("message")->asString();
debug(9, "GoogleDriveTokenRefresher: message = %s", message.c_str());
}
if (code == 401 || message == "Invalid Credentials")
irrecoverable = false;
if (irrecoverable) {
finishError(Networking::ErrorResponse(this, false, true, json->stringify(true), httpResponseCode));
delete json;
return;
}
pause();
delete json;
_parentStorage->refreshAccessToken(new Common::Callback<GoogleDriveTokenRefresher, const Storage::BoolResponse &>(this, &GoogleDriveTokenRefresher::tokenRefreshed));
return;
}
}
//notify user of success
HttpJsonRequest::finishJson(json);
}
} // End of namespace GoogleDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,47 @@
/* 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_GOOGLEDRIVE_GOOGLEDRIVETOKENREFRESHER_H
#define BACKENDS_CLOUD_GOOGLEDRIVE_GOOGLEDRIVETOKENREFRESHER_H
#include "backends/cloud/storage.h"
#include "backends/networking/http/httpjsonrequest.h"
namespace Cloud {
namespace GoogleDrive {
class GoogleDriveStorage;
class GoogleDriveTokenRefresher: public Networking::HttpJsonRequest {
GoogleDriveStorage *_parentStorage;
void tokenRefreshed(const Storage::BoolResponse &response);
void finishJson(const Common::JSONValue *json) override;
public:
GoogleDriveTokenRefresher(GoogleDriveStorage *parent, Networking::JsonCallback callback, Networking::ErrorCallback ecb, const char *url);
~GoogleDriveTokenRefresher() override;
};
} // End of namespace GoogleDrive
} // End of namespace Cloud
#endif

View File

@@ -0,0 +1,344 @@
/* 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/googledrive/googledriveuploadrequest.h"
#include "backends/cloud/googledrive/googledrivestorage.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 "googledrivetokenrefresher.h"
namespace Cloud {
namespace GoogleDrive {
#define GOOGLEDRIVE_API_FILES "https://www.googleapis.com/upload/drive/v3/files"
GoogleDriveUploadRequest::GoogleDriveUploadRequest(GoogleDriveStorage *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();
}
GoogleDriveUploadRequest::~GoogleDriveUploadRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _contentsStream;
delete _uploadCallback;
}
void GoogleDriveUploadRequest::start() {
_ignoreCallback = true;
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, "GoogleDriveUploadRequest::start: couldn't restart because failed to seek(0)", -1));
return;
}
_resolvedId = ""; //used to update file contents
_parentId = ""; //used to create file within parent directory
_serverReceivedBytes = 0;
_ignoreCallback = false;
resolveId();
}
void GoogleDriveUploadRequest::resolveId() {
//check whether such file already exists
Storage::UploadCallback innerCallback = new Common::Callback<GoogleDriveUploadRequest, const Storage::UploadResponse &>(this, &GoogleDriveUploadRequest::idResolvedCallback);
Networking::ErrorCallback innerErrorCallback = new Common::Callback<GoogleDriveUploadRequest, const Networking::ErrorResponse &>(this, &GoogleDriveUploadRequest::idResolveFailedCallback);
_workingRequest = _storage->resolveFileId(_savePath, innerCallback, innerErrorCallback);
}
void GoogleDriveUploadRequest::idResolvedCallback(const Storage::UploadResponse &response) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
_resolvedId = response.value.id();
startUpload();
}
void GoogleDriveUploadRequest::idResolveFailedCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
//not resolved => error or no such file
if (error.response.contains("no such file found in its parent directory")) {
//parent's id after the '\n'
Common::String parentId = error.response;
for (uint32 i = 0; i < parentId.size(); ++i)
if (parentId[i] == '\n') {
parentId.erase(0, i + 1);
break;
}
_parentId = parentId;
startUpload();
return;
}
finishError(error);
}
void GoogleDriveUploadRequest::startUpload() {
Common::String name = _savePath;
for (uint32 i = name.size(); i > 0; --i) {
if (name[i - 1] == '/' || name[i - 1] == '\\') {
name.erase(0, i);
break;
}
}
Common::String url = GOOGLEDRIVE_API_FILES;
if (_resolvedId != "")
url += "/" + Common::percentEncodeString(_resolvedId);
url += "?uploadType=resumable&fields=id,mimeType,modifiedTime,name,size";
Networking::JsonCallback callback = new Common::Callback<GoogleDriveUploadRequest, const Networking::JsonResponse &>(this, &GoogleDriveUploadRequest::startUploadCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<GoogleDriveUploadRequest, const Networking::ErrorResponse &>(this, &GoogleDriveUploadRequest::startUploadErrorCallback);
Networking::HttpJsonRequest *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();
Common::JSONObject jsonRequestParameters;
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));
}
jsonRequestParameters.setVal("name", new Common::JSONValue(name));
Common::JSONValue value(jsonRequestParameters);
request->addPostField(Common::JSON::stringify(&value));
_workingRequest = ConnMan.addRequest(request);
}
void GoogleDriveUploadRequest::startUploadCallback(const Networking::JsonResponse &response) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
Networking::ErrorResponse error(this, false, true, "GoogleDriveUploadRequest::startUploadCallback", -1);
const Networking::HttpJsonRequest *rq = (const Networking::HttpJsonRequest *)response.request;
if (rq) {
const Networking::NetworkReadStream *stream = rq->getNetworkReadStream();
if (stream) {
long code = stream->httpResponseCode();
if (code == 200) {
Common::HashMap<Common::String, Common::String> headers = stream->responseHeadersMap();
if (headers.contains("location")) {
_uploadUrl = headers["location"];
uploadNextPart();
return;
} else {
error.response += ": response must provide Location header, but it's not there";
}
} else {
error.response += ": response is not 200 OK";
}
error.httpResponseCode = code;
} else {
error.response += ": missing response stream [improbable]";
}
} else {
error.response += ": missing request object [improbable]";
}
const Common::JSONValue *json = response.value;
delete json;
finishError(error);
}
void GoogleDriveUploadRequest::startUploadErrorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
finishError(error);
}
void GoogleDriveUploadRequest::uploadNextPart() {
const uint32 UPLOAD_PER_ONE_REQUEST = 10 * 1024 * 1024;
Common::String url = _uploadUrl;
Networking::JsonCallback callback = new Common::Callback<GoogleDriveUploadRequest, const Networking::JsonResponse &>(this, &GoogleDriveUploadRequest::partUploadedCallback);
Networking::ErrorCallback failureCallback = new Common::Callback<GoogleDriveUploadRequest, const Networking::ErrorResponse &>(this, &GoogleDriveUploadRequest::partUploadedErrorCallback);
Networking::HttpJsonRequest *request = new GoogleDriveTokenRefresher(_storage, callback, failureCallback, url.c_str());
request->addHeader("Authorization: Bearer " + _storage->accessToken());
request->usePut();
uint32 oldPos = _contentsStream->pos();
if (oldPos != _serverReceivedBytes) {
if (!_contentsStream->seek(_serverReceivedBytes)) {
warning("GoogleDriveUploadRequest: cannot upload because stream couldn't seek(%llu)", (unsigned long long)_serverReceivedBytes);
finishError(Networking::ErrorResponse(this, false, true, "GoogleDriveUploadRequest::uploadNextPart: seek() didn't work", -1));
return;
}
oldPos = _serverReceivedBytes;
}
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 (_uploadUrl != "") {
if (_contentsStream->pos() == 0)
request->addHeader(Common::String::format("Content-Length: 0"));
else
request->addHeader(Common::String::format("Content-Range: bytes %u-%lu/%lu", oldPos, long(_contentsStream->pos() - 1), long(_contentsStream->size())));
}
_workingRequest = ConnMan.addRequest(request);
}
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
Common::HashMap<Common::String, Common::String> headers = stream->responseHeadersMap();
if (headers.contains("range")) {
Common::String range = headers["range"];
for (int rangeTry = 0; rangeTry < 2; ++rangeTry) {
const char *needle = (rangeTry == 0 ? "0-" : "bytes=0-"); //if it lost the first part, I refuse to talk with it
uint32 needleLength = (rangeTry == 0 ? 2 : 8);
if (range.hasPrefix(needle)) {
range.erase(0, needleLength);
_serverReceivedBytes = range.asUint64() + 1;
uploadNextPart();
return true;
}
}
}
return false;
}
void GoogleDriveUploadRequest::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) {
const Networking::NetworkReadStream *stream = rq->getNetworkReadStream();
if (stream) {
long code = stream->httpResponseCode();
error.httpResponseCode = code;
if (code == 308 && handleHttp308(stream)) {
delete response.value;
return;
}
}
}
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("GoogleDrive returned error: %s", json->stringify(true).c_str());
error.response = json->stringify(true);
finishError(error);
delete json;
return;
}
if (Networking::HttpJsonRequest::jsonContainsString(object, "id", "GoogleDriveUploadRequest") &&
Networking::HttpJsonRequest::jsonContainsString(object, "name", "GoogleDriveUploadRequest") &&
Networking::HttpJsonRequest::jsonContainsString(object, "mimeType", "GoogleDriveUploadRequest")) {
//finished
Common::String id = object.getVal("id")->asString();
Common::String name = object.getVal("name")->asString();
bool isDirectory = (object.getVal("mimeType")->asString() == "application/vnd.google-apps.folder");
uint32 size = 0, timestamp = 0;
if (Networking::HttpJsonRequest::jsonContainsString(object, "size", "GoogleDriveUploadRequest", true))
size = object.getVal("size")->asString().asUint64();
if (Networking::HttpJsonRequest::jsonContainsString(object, "modifiedTime", "GoogleDriveUploadRequest", true))
timestamp = ISO8601::convertToTimestamp(object.getVal("modifiedTime")->asString());
finishUpload(StorageFile(id, _savePath, name, size, timestamp, isDirectory));
return;
}
}
if (_contentsStream->eos() || _contentsStream->pos() >= _contentsStream->size() - 1) {
warning("GoogleDriveUploadRequest: no file info to return");
finishUpload(StorageFile(_savePath, 0, 0, false));
} else {
uploadNextPart();
}
delete json;
}
void GoogleDriveUploadRequest::partUploadedErrorCallback(const Networking::ErrorResponse &error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
Networking::HttpJsonRequest *rq = (Networking::HttpJsonRequest *)error.request;
if (rq) {
const Networking::NetworkReadStream *stream = rq->getNetworkReadStream();
if (stream) {
long code = stream->httpResponseCode();
if (code == 308 && handleHttp308(stream)) {
return;
}
}
}
finishError(error);
}
void GoogleDriveUploadRequest::handle() {}
void GoogleDriveUploadRequest::restart() { start(); }
void GoogleDriveUploadRequest::finishUpload(const StorageFile &file) {
Request::finishSuccess();
if (_uploadCallback)
(*_uploadCallback)(Storage::UploadResponse(this, file));
}
} // End of namespace GoogleDrive
} // End of namespace Cloud

View File

@@ -0,0 +1,69 @@
/* 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_GOOGLEDRIVE_GOOGLEDRIVEUPLOADREQUEST_H
#define BACKENDS_CLOUD_GOOGLEDRIVE_GOOGLEDRIVEUPLOADREQUEST_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 GoogleDrive {
class GoogleDriveStorage;
class GoogleDriveUploadRequest: public Networking::Request {
GoogleDriveStorage *_storage;
Common::String _savePath;
Common::SeekableReadStream *_contentsStream;
Storage::UploadCallback _uploadCallback;
Request *_workingRequest;
bool _ignoreCallback;
Common::String _resolvedId, _parentId;
Common::String _uploadUrl;
uint64 _serverReceivedBytes;
void start();
void resolveId();
void idResolvedCallback(const Storage::UploadResponse &response);
void idResolveFailedCallback(const Networking::ErrorResponse &error);
void startUpload();
void startUploadCallback(const Networking::JsonResponse &response);
void startUploadErrorCallback(const Networking::ErrorResponse &error);
void uploadNextPart();
void partUploadedCallback(const Networking::JsonResponse &response);
void partUploadedErrorCallback(const Networking::ErrorResponse &error);
bool handleHttp308(const Networking::NetworkReadStream *stream);
void finishUpload(const StorageFile &status);
public:
GoogleDriveUploadRequest(GoogleDriveStorage *storage, const Common::String &path, Common::SeekableReadStream *contents, Storage::UploadCallback callback, Networking::ErrorCallback ecb);
~GoogleDriveUploadRequest() override;
void handle() override;
void restart() override;
};
} // End of namespace GoogleDrive
} // End of namespace Cloud
#endif