ResidualVM logo ResidualVM website - Forums - Contact us BuildBot - Doxygen - Wiki curved edge

googledrivestorage.cpp

Go to the documentation of this file.
00001 /* ScummVM - Graphic Adventure Engine
00002  *
00003  * ScummVM is the legal property of its developers, whose names
00004  * are too numerous to list here. Please refer to the COPYRIGHT
00005  * file distributed with this source distribution.
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00020  *
00021  */
00022 
00023 #define FORBIDDEN_SYMBOL_ALLOW_ALL
00024 
00025 #include <curl/curl.h>
00026 #include "backends/cloud/googledrive/googledrivestorage.h"
00027 #include "backends/cloud/cloudmanager.h"
00028 #include "backends/cloud/googledrive/googledrivetokenrefresher.h"
00029 #include "backends/cloud/googledrive/googledrivelistdirectorybyidrequest.h"
00030 #include "backends/cloud/googledrive/googledriveuploadrequest.h"
00031 #include "backends/networking/curl/connectionmanager.h"
00032 #include "backends/networking/curl/curljsonrequest.h"
00033 #include "backends/networking/curl/networkreadstream.h"
00034 #include "common/config-manager.h"
00035 #include "common/debug.h"
00036 #include "common/json.h"
00037 #include "common/debug.h"
00038 
00039 #ifdef ENABLE_RELEASE
00040 #include "dists/clouds/cloud_keys.h"
00041 #endif
00042 
00043 namespace Cloud {
00044 namespace GoogleDrive {
00045 
00046 #define GOOGLEDRIVE_OAUTH2_TOKEN "https://accounts.google.com/o/oauth2/token"
00047 #define GOOGLEDRIVE_API_FILES_ALT_MEDIA "https://www.googleapis.com/drive/v3/files/%s?alt=media"
00048 #define GOOGLEDRIVE_API_FILES "https://www.googleapis.com/drive/v3/files"
00049 #define GOOGLEDRIVE_API_ABOUT "https://www.googleapis.com/drive/v3/about?fields=storageQuota,user"
00050 
00051 char *GoogleDriveStorage::KEY = nullptr; //can't use CloudConfig there yet, loading it on instance creation/auth
00052 char *GoogleDriveStorage::SECRET = nullptr;
00053 
00054 void GoogleDriveStorage::loadKeyAndSecret() {
00055 #ifdef ENABLE_RELEASE
00056     KEY = RELEASE_GOOGLE_DRIVE_KEY;
00057     SECRET = RELEASE_GOOGLE_DRIVE_SECRET;
00058 #else
00059     Common::String k = ConfMan.get("GOOGLE_DRIVE_KEY", ConfMan.kCloudDomain);
00060     KEY = new char[k.size() + 1];
00061     memcpy(KEY, k.c_str(), k.size());
00062     KEY[k.size()] = 0;
00063 
00064     k = ConfMan.get("GOOGLE_DRIVE_SECRET", ConfMan.kCloudDomain);
00065     SECRET = new char[k.size() + 1];
00066     memcpy(SECRET, k.c_str(), k.size());
00067     SECRET[k.size()] = 0;
00068 #endif
00069 }
00070 
00071 GoogleDriveStorage::GoogleDriveStorage(Common::String token, Common::String refreshToken):
00072     _token(token), _refreshToken(refreshToken) {}
00073 
00074 GoogleDriveStorage::GoogleDriveStorage(Common::String code) {
00075     getAccessToken(
00076         new Common::Callback<GoogleDriveStorage, BoolResponse>(this, &GoogleDriveStorage::codeFlowComplete),
00077         new Common::Callback<GoogleDriveStorage, Networking::ErrorResponse>(this, &GoogleDriveStorage::codeFlowFailed),
00078         code
00079     );
00080 }
00081 
00082 GoogleDriveStorage::~GoogleDriveStorage() {}
00083 
00084 void GoogleDriveStorage::getAccessToken(BoolCallback callback, Networking::ErrorCallback errorCallback, Common::String code) {
00085     if (!KEY || !SECRET) loadKeyAndSecret();
00086     bool codeFlow = (code != "");
00087 
00088     if (!codeFlow && _refreshToken == "") {
00089         warning("GoogleDriveStorage: no refresh token available to get new access token.");
00090         if (callback)
00091             (*callback)(BoolResponse(nullptr, false));
00092         return;
00093     }
00094 
00095     Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, BoolResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::tokenRefreshed, callback);
00096     if (errorCallback == nullptr)
00097         errorCallback = getErrorPrintingCallback();
00098     Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(innerCallback, errorCallback, GOOGLEDRIVE_OAUTH2_TOKEN);
00099     if (codeFlow) {
00100         request->addPostField("code=" + code);
00101         request->addPostField("grant_type=authorization_code");
00102     } else {
00103         request->addPostField("refresh_token=" + _refreshToken);
00104         request->addPostField("grant_type=refresh_token");
00105     }
00106     request->addPostField("client_id=" + Common::String(KEY));
00107     request->addPostField("client_secret=" + Common::String(SECRET));
00108     if (Cloud::CloudManager::couldUseLocalServer()) {
00109         request->addPostField("&redirect_uri=http%3A%2F%2Flocalhost%3A12345");
00110     } else {
00111         request->addPostField("&redirect_uri=https%3A%2F%2Fwww.scummvm.org/c/code");
00112     }
00113     addRequest(request);
00114 }
00115 
00116 void GoogleDriveStorage::tokenRefreshed(BoolCallback callback, Networking::JsonResponse response) {
00117     Common::JSONValue *json = response.value;
00118     if (!json) {
00119         warning("GoogleDriveStorage: got NULL instead of JSON");
00120         if (callback)
00121             (*callback)(BoolResponse(nullptr, false));
00122         delete callback;
00123         return;
00124     }
00125 
00126     if (!Networking::CurlJsonRequest::jsonIsObject(json, "GoogleDriveStorage")) {
00127         if (callback)
00128             (*callback)(BoolResponse(nullptr, false));
00129         delete json;
00130         delete callback;
00131         return;
00132     }
00133 
00134     Common::JSONObject result = json->asObject();
00135     if (!Networking::CurlJsonRequest::jsonContainsString(result, "access_token", "GoogleDriveStorage")) {
00136         warning("GoogleDriveStorage: bad response, no token passed");
00137         debug(9, "%s", json->stringify().c_str());
00138         if (callback)
00139             (*callback)(BoolResponse(nullptr, false));
00140     } else {
00141         _token = result.getVal("access_token")->asString();
00142         if (!Networking::CurlJsonRequest::jsonContainsString(result, "refresh_token", "GoogleDriveStorage"))
00143             warning("GoogleDriveStorage: no refresh_token passed");
00144         else
00145             _refreshToken = result.getVal("refresh_token")->asString();
00146         CloudMan.save(); //ask CloudManager to save our new refreshToken
00147         if (callback)
00148             (*callback)(BoolResponse(nullptr, true));
00149     }
00150     delete json;
00151     delete callback;
00152 }
00153 
00154 void GoogleDriveStorage::codeFlowComplete(BoolResponse response) {
00155     if (!response.value) {
00156         warning("GoogleDriveStorage: failed to get access token through code flow");
00157         CloudMan.removeStorage(this);
00158         return;
00159     }
00160 
00161     ConfMan.removeKey("googledrive_code", ConfMan.kCloudDomain);
00162     CloudMan.replaceStorage(this, kStorageGoogleDriveId);
00163     ConfMan.flushToDisk();
00164 }
00165 
00166 void GoogleDriveStorage::codeFlowFailed(Networking::ErrorResponse error) {
00167     debug(9, "GoogleDriveStorage: code flow failed (%s, %ld):", (error.failed ? "failed" : "interrupted"), error.httpResponseCode);
00168     debug(9, "%s", error.response.c_str());
00169     CloudMan.removeStorage(this);
00170 }
00171 
00172 void GoogleDriveStorage::saveConfig(Common::String keyPrefix) {
00173     ConfMan.set(keyPrefix + "access_token", _token, ConfMan.kCloudDomain);
00174     ConfMan.set(keyPrefix + "refresh_token", _refreshToken, ConfMan.kCloudDomain);
00175 }
00176 
00177 Common::String GoogleDriveStorage::name() const {
00178     return "Google Drive";
00179 }
00180 
00181 void GoogleDriveStorage::infoInnerCallback(StorageInfoCallback outerCallback, Networking::JsonResponse response) {
00182     Common::JSONValue *json = response.value;
00183     if (!json) {
00184         warning("GoogleDriveStorage::infoInnerCallback: NULL passed instead of JSON");
00185         delete outerCallback;
00186         return;
00187     }
00188 
00189     if (!Networking::CurlJsonRequest::jsonIsObject(json, "GoogleDriveStorage::infoInnerCallback")) {
00190         delete json;
00191         delete outerCallback;
00192         return;
00193     }
00194 
00195     Common::JSONObject jsonInfo = json->asObject();
00196 
00197     Common::String uid, displayName, email;
00198     uint64 quotaUsed = 0, quotaAllocated = 0;
00199 
00200     if (Networking::CurlJsonRequest::jsonContainsAttribute(jsonInfo, "user", "GoogleDriveStorage::infoInnerCallback") &&
00201         Networking::CurlJsonRequest::jsonIsObject(jsonInfo.getVal("user"), "GoogleDriveStorage::infoInnerCallback")) {
00202         //"me":true, "kind":"drive#user","photoLink": "",
00203         //"displayName":"Alexander Tkachev","emailAddress":"alexander@tkachov.ru","permissionId":""
00204         Common::JSONObject user = jsonInfo.getVal("user")->asObject();
00205         if (Networking::CurlJsonRequest::jsonContainsString(user, "permissionId", "GoogleDriveStorage::infoInnerCallback"))
00206             uid = user.getVal("permissionId")->asString(); //not sure it's user's id, but who cares anyway?
00207         if (Networking::CurlJsonRequest::jsonContainsString(user, "displayName", "GoogleDriveStorage::infoInnerCallback"))
00208             displayName = user.getVal("displayName")->asString();
00209         if (Networking::CurlJsonRequest::jsonContainsString(user, "emailAddress", "GoogleDriveStorage::infoInnerCallback"))
00210             email = user.getVal("emailAddress")->asString();
00211     }
00212 
00213     if (Networking::CurlJsonRequest::jsonContainsAttribute(jsonInfo, "storageQuota", "GoogleDriveStorage::infoInnerCallback") &&
00214         Networking::CurlJsonRequest::jsonIsObject(jsonInfo.getVal("storageQuota"), "GoogleDriveStorage::infoInnerCallback")) {
00215         //"usageInDrive":"6332462","limit":"18253611008","usage":"6332462","usageInDriveTrash":"0"
00216         Common::JSONObject storageQuota = jsonInfo.getVal("storageQuota")->asObject();
00217 
00218         if (Networking::CurlJsonRequest::jsonContainsString(storageQuota, "usage", "GoogleDriveStorage::infoInnerCallback")) {
00219             Common::String usage = storageQuota.getVal("usage")->asString();
00220             quotaUsed = usage.asUint64();
00221         }
00222 
00223         if (Networking::CurlJsonRequest::jsonContainsString(storageQuota, "limit", "GoogleDriveStorage::infoInnerCallback")) {
00224             Common::String limit = storageQuota.getVal("limit")->asString();
00225             quotaAllocated = limit.asUint64();
00226         }
00227     }
00228 
00229     CloudMan.setStorageUsername(kStorageGoogleDriveId, email);
00230 
00231     if (outerCallback) {
00232         (*outerCallback)(StorageInfoResponse(nullptr, StorageInfo(uid, displayName, email, quotaUsed, quotaAllocated)));
00233         delete outerCallback;
00234     }
00235 
00236     delete json;
00237 }
00238 
00239 void GoogleDriveStorage::createDirectoryInnerCallback(BoolCallback outerCallback, Networking::JsonResponse response) {
00240     Common::JSONValue *json = response.value;
00241     if (!json) {
00242         warning("GoogleDriveStorage::createDirectoryInnerCallback: NULL passed instead of JSON");
00243         delete outerCallback;
00244         return;
00245     }
00246 
00247     if (outerCallback) {
00248         if (Networking::CurlJsonRequest::jsonIsObject(json, "GoogleDriveStorage::createDirectoryInnerCallback")) {
00249             Common::JSONObject jsonInfo = json->asObject();
00250             (*outerCallback)(BoolResponse(nullptr, jsonInfo.contains("id")));
00251         } else {
00252             (*outerCallback)(BoolResponse(nullptr, false));
00253         }
00254         delete outerCallback;
00255     }
00256 
00257     delete json;
00258 }
00259 
00260 Networking::Request *GoogleDriveStorage::listDirectoryById(Common::String id, ListDirectoryCallback callback, Networking::ErrorCallback errorCallback) {
00261     if (!errorCallback)
00262         errorCallback = getErrorPrintingCallback();
00263     if (!callback)
00264         callback = new Common::Callback<GoogleDriveStorage, FileArrayResponse>(this, &GoogleDriveStorage::printFiles);
00265     return addRequest(new GoogleDriveListDirectoryByIdRequest(this, id, callback, errorCallback));
00266 }
00267 
00268 Networking::Request *GoogleDriveStorage::upload(Common::String path, Common::SeekableReadStream *contents, UploadCallback callback, Networking::ErrorCallback errorCallback) {
00269     return addRequest(new GoogleDriveUploadRequest(this, path, contents, callback, errorCallback));
00270 }
00271 
00272 Networking::Request *GoogleDriveStorage::streamFileById(Common::String id, Networking::NetworkReadStreamCallback callback, Networking::ErrorCallback errorCallback) {
00273     if (callback) {
00274         Common::String url = Common::String::format(GOOGLEDRIVE_API_FILES_ALT_MEDIA, ConnMan.urlEncode(id).c_str());
00275         Common::String header = "Authorization: Bearer " + _token;
00276         curl_slist *headersList = curl_slist_append(nullptr, header.c_str());
00277         Networking::NetworkReadStream *stream = new Networking::NetworkReadStream(url.c_str(), headersList, "");
00278         (*callback)(Networking::NetworkReadStreamResponse(nullptr, stream));
00279     }
00280     delete callback;
00281     delete errorCallback;
00282     return nullptr;
00283 }
00284 
00285 void GoogleDriveStorage::printInfo(StorageInfoResponse response) {
00286     debug(9, "\nGoogleDriveStorage: user info:");
00287     debug(9, "\tname: %s", response.value.name().c_str());
00288     debug(9, "\temail: %s", response.value.email().c_str());
00289     debug(9, "\tdisk usage: %lu/%lu", response.value.used(), response.value.available());
00290 }
00291 
00292 Networking::Request *GoogleDriveStorage::createDirectoryWithParentId(Common::String parentId, Common::String directoryName, BoolCallback callback, Networking::ErrorCallback errorCallback) {
00293     if (!errorCallback)
00294         errorCallback = getErrorPrintingCallback();
00295 
00296     Common::String url = GOOGLEDRIVE_API_FILES;
00297     Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, BoolResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::createDirectoryInnerCallback, callback);
00298     Networking::CurlJsonRequest *request = new GoogleDriveTokenRefresher(this, innerCallback, errorCallback, url.c_str());
00299     request->addHeader("Authorization: Bearer " + accessToken());
00300     request->addHeader("Content-Type: application/json");
00301 
00302     Common::JSONArray parentsArray;
00303     parentsArray.push_back(new Common::JSONValue(parentId));
00304 
00305     Common::JSONObject jsonRequestParameters;
00306     jsonRequestParameters.setVal("mimeType", new Common::JSONValue("application/vnd.google-apps.folder"));
00307     jsonRequestParameters.setVal("name", new Common::JSONValue(directoryName));
00308     jsonRequestParameters.setVal("parents", new Common::JSONValue(parentsArray));
00309 
00310     Common::JSONValue value(jsonRequestParameters);
00311     request->addPostField(Common::JSON::stringify(&value));
00312 
00313     return addRequest(request);
00314 }
00315 
00316 Networking::Request *GoogleDriveStorage::info(StorageInfoCallback callback, Networking::ErrorCallback errorCallback) {
00317     if (!callback)
00318         callback = new Common::Callback<GoogleDriveStorage, StorageInfoResponse>(this, &GoogleDriveStorage::printInfo);
00319     Networking::JsonCallback innerCallback = new Common::CallbackBridge<GoogleDriveStorage, StorageInfoResponse, Networking::JsonResponse>(this, &GoogleDriveStorage::infoInnerCallback, callback);
00320     Networking::CurlJsonRequest *request = new GoogleDriveTokenRefresher(this, innerCallback, errorCallback, GOOGLEDRIVE_API_ABOUT);
00321     request->addHeader("Authorization: Bearer " + _token);
00322     return addRequest(request);
00323 }
00324 
00325 Common::String GoogleDriveStorage::savesDirectoryPath() { return "scummvm/saves/"; }
00326 
00327 GoogleDriveStorage *GoogleDriveStorage::loadFromConfig(Common::String keyPrefix) {
00328     loadKeyAndSecret();
00329 
00330     if (!ConfMan.hasKey(keyPrefix + "access_token", ConfMan.kCloudDomain)) {
00331         warning("GoogleDriveStorage: no access_token found");
00332         return nullptr;
00333     }
00334 
00335     if (!ConfMan.hasKey(keyPrefix + "refresh_token", ConfMan.kCloudDomain)) {
00336         warning("GoogleDriveStorage: no refresh_token found");
00337         return nullptr;
00338     }
00339 
00340     Common::String accessToken = ConfMan.get(keyPrefix + "access_token", ConfMan.kCloudDomain);
00341     Common::String refreshToken = ConfMan.get(keyPrefix + "refresh_token", ConfMan.kCloudDomain);
00342     return new GoogleDriveStorage(accessToken, refreshToken);
00343 }
00344 
00345 Common::String GoogleDriveStorage::getRootDirectoryId() {
00346     return "root";
00347 }
00348 
00349 } // End of namespace GoogleDrive
00350 } // End of namespace Cloud


Generated on Sat May 25 2019 05:00:46 for ResidualVM by doxygen 1.7.1
curved edge   curved edge