1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 #include "backends/cloud/dropbox/dropboxlistdirectoryrequest.h"
24 #include "backends/cloud/iso8601.h"
25 #include "backends/cloud/storage.h"
26 #include "backends/networking/curl/connectionmanager.h"
27 #include "backends/networking/curl/curljsonrequest.h"
28 #include "backends/networking/curl/networkreadstream.h"
29 #include "common/json.h"
30 #include "common/debug.h"
31 
32 namespace Cloud {
33 namespace Dropbox {
34 
35 #define DROPBOX_API_LIST_FOLDER "https://api.dropboxapi.com/2/files/list_folder"
36 #define DROPBOX_API_LIST_FOLDER_CONTINUE "https://api.dropboxapi.com/2/files/list_folder/continue"
37 
DropboxListDirectoryRequest(Common::String token,Common::String path,Storage::ListDirectoryCallback cb,Networking::ErrorCallback ecb,bool recursive)38 DropboxListDirectoryRequest::DropboxListDirectoryRequest(Common::String token, Common::String path, Storage::ListDirectoryCallback cb, Networking::ErrorCallback ecb, bool recursive):
39 	Networking::Request(nullptr, ecb), _requestedPath(path), _requestedRecursive(recursive), _listDirectoryCallback(cb),
40 	_token(token), _workingRequest(nullptr), _ignoreCallback(false) {
41 	start();
42 }
43 
~DropboxListDirectoryRequest()44 DropboxListDirectoryRequest::~DropboxListDirectoryRequest() {
45 	_ignoreCallback = true;
46 	if (_workingRequest)
47 		_workingRequest->finish();
48 	delete _listDirectoryCallback;
49 }
50 
start()51 void DropboxListDirectoryRequest::start() {
52 	_ignoreCallback = true;
53 	if (_workingRequest)
54 		_workingRequest->finish();
55 	_files.clear();
56 	_ignoreCallback = false;
57 
58 	Networking::JsonCallback callback = new Common::Callback<DropboxListDirectoryRequest, Networking::JsonResponse>(this, &DropboxListDirectoryRequest::responseCallback);
59 	Networking::ErrorCallback failureCallback = new Common::Callback<DropboxListDirectoryRequest, Networking::ErrorResponse>(this, &DropboxListDirectoryRequest::errorCallback);
60 	Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(callback, failureCallback, DROPBOX_API_LIST_FOLDER);
61 	request->addHeader("Authorization: Bearer " + _token);
62 	request->addHeader("Content-Type: application/json");
63 
64 	Common::JSONObject jsonRequestParameters;
65 	jsonRequestParameters.setVal("path", new Common::JSONValue(_requestedPath));
66 	jsonRequestParameters.setVal("recursive", new Common::JSONValue(_requestedRecursive));
67 	jsonRequestParameters.setVal("include_media_info", new Common::JSONValue(false));
68 	jsonRequestParameters.setVal("include_deleted", new Common::JSONValue(false));
69 
70 	Common::JSONValue value(jsonRequestParameters);
71 	request->addPostField(Common::JSON::stringify(&value));
72 
73 	_workingRequest = ConnMan.addRequest(request);
74 }
75 
responseCallback(Networking::JsonResponse response)76 void DropboxListDirectoryRequest::responseCallback(Networking::JsonResponse response) {
77 	_workingRequest = nullptr;
78 
79 	if (_ignoreCallback) {
80 		delete response.value;
81 		return;
82 	}
83 
84 	if (response.request)
85 		_date = response.request->date();
86 
87 	Networking::ErrorResponse error(this, "DropboxListDirectoryRequest::responseCallback: unknown error");
88 	Networking::CurlJsonRequest *rq = (Networking::CurlJsonRequest *)response.request;
89 	if (rq && rq->getNetworkReadStream())
90 		error.httpResponseCode = rq->getNetworkReadStream()->httpResponseCode();
91 
92 	Common::JSONValue *json = response.value;
93 	if (json == nullptr) {
94 		error.response = "Failed to parse JSON, null passed!";
95 		finishError(error);
96 		return;
97 	}
98 
99 	if (!json->isObject()) {
100 		error.response = "Passed JSON is not an object!";
101 		finishError(error);
102 		delete json;
103 		return;
104 	}
105 
106 	Common::JSONObject responseObject = json->asObject();
107 
108 	if (responseObject.contains("error") || responseObject.contains("error_summary")) {
109 		if (responseObject.contains("error_summary") && responseObject.getVal("error_summary")->isString()) {
110 			warning("Dropbox returned error: %s", responseObject.getVal("error_summary")->asString().c_str());
111 		}
112 		error.failed = true;
113 		error.response = json->stringify();
114 		finishError(error);
115 		delete json;
116 		return;
117 	}
118 
119 	//check that ALL keys exist AND HAVE RIGHT TYPE to avoid segfaults
120 	if (responseObject.contains("entries")) {
121 		if (!responseObject.getVal("entries")->isArray()) {
122 			error.response = Common::String::format(
123 				"\"entries\" found, but that's not an array!\n%s",
124 				responseObject.getVal("entries")->stringify(true).c_str()
125 				);
126 			finishError(error);
127 			delete json;
128 			return;
129 		}
130 
131 		Common::JSONArray items = responseObject.getVal("entries")->asArray();
132 		for (uint32 i = 0; i < items.size(); ++i) {
133 			if (!Networking::CurlJsonRequest::jsonIsObject(items[i], "DropboxListDirectoryRequest"))
134 				continue;
135 
136 			Common::JSONObject item = items[i]->asObject();
137 
138 			if (!Networking::CurlJsonRequest::jsonContainsString(item, "path_lower", "DropboxListDirectoryRequest"))
139 				continue;
140 			if (!Networking::CurlJsonRequest::jsonContainsString(item, ".tag", "DropboxListDirectoryRequest"))
141 				continue;
142 
143 			Common::String path = item.getVal("path_lower")->asString();
144 			bool isDirectory = (item.getVal(".tag")->asString() == "folder");
145 			uint32 size = 0, timestamp = 0;
146 			if (!isDirectory) {
147 				if (!Networking::CurlJsonRequest::jsonContainsString(item, "server_modified", "DropboxListDirectoryRequest"))
148 					continue;
149 				if (!Networking::CurlJsonRequest::jsonContainsIntegerNumber(item, "size", "DropboxListDirectoryRequest"))
150 					continue;
151 
152 				size = item.getVal("size")->asIntegerNumber();
153 				timestamp = ISO8601::convertToTimestamp(item.getVal("server_modified")->asString());
154 			}
155 			_files.push_back(StorageFile(path, size, timestamp, isDirectory));
156 		}
157 	}
158 
159 	bool hasMore = false;
160 	if (responseObject.contains("has_more")) {
161 		if (!responseObject.getVal("has_more")->isBool()) {
162 			warning("DropboxListDirectoryRequest: \"has_more\" is not a boolean");
163 			debug(9, "%s", responseObject.getVal("has_more")->stringify(true).c_str());
164 			error.response = "\"has_more\" is not a boolean!";
165 			finishError(error);
166 			delete json;
167 			return;
168 		}
169 
170 		hasMore = responseObject.getVal("has_more")->asBool();
171 	}
172 
173 	if (hasMore) {
174 		if (!Networking::CurlJsonRequest::jsonContainsString(responseObject, "cursor", "DropboxListDirectoryRequest")) {
175 			error.response = "\"has_more\" found, but \"cursor\" is not (or it's not a string)!";
176 			finishError(error);
177 			delete json;
178 			return;
179 		}
180 
181 		Networking::JsonCallback callback = new Common::Callback<DropboxListDirectoryRequest, Networking::JsonResponse>(this, &DropboxListDirectoryRequest::responseCallback);
182 		Networking::ErrorCallback failureCallback = new Common::Callback<DropboxListDirectoryRequest, Networking::ErrorResponse>(this, &DropboxListDirectoryRequest::errorCallback);
183 		Networking::CurlJsonRequest *request = new Networking::CurlJsonRequest(callback, failureCallback, DROPBOX_API_LIST_FOLDER_CONTINUE);
184 		request->addHeader("Authorization: Bearer " + _token);
185 		request->addHeader("Content-Type: application/json");
186 
187 		Common::JSONObject jsonRequestParameters;
188 		jsonRequestParameters.setVal("cursor", new Common::JSONValue(responseObject.getVal("cursor")->asString()));
189 
190 		Common::JSONValue value(jsonRequestParameters);
191 		request->addPostField(Common::JSON::stringify(&value));
192 
193 		_workingRequest = ConnMan.addRequest(request);
194 	} else {
195 		finishListing(_files);
196 	}
197 
198 	delete json;
199 }
200 
errorCallback(Networking::ErrorResponse error)201 void DropboxListDirectoryRequest::errorCallback(Networking::ErrorResponse error) {
202 	_workingRequest = nullptr;
203 	if (_ignoreCallback)
204 		return;
205 	if (error.request)
206 		_date = error.request->date();
207 	finishError(error);
208 }
209 
handle()210 void DropboxListDirectoryRequest::handle() {}
211 
restart()212 void DropboxListDirectoryRequest::restart() { start(); }
213 
date() const214 Common::String DropboxListDirectoryRequest::date() const { return _date; }
215 
finishListing(Common::Array<StorageFile> & files)216 void DropboxListDirectoryRequest::finishListing(Common::Array<StorageFile> &files) {
217 	Request::finishSuccess();
218 	if (_listDirectoryCallback)
219 		(*_listDirectoryCallback)(Storage::ListDirectoryResponse(this, files));
220 }
221 
222 } // End of namespace Dropbox
223 } // End of namespace Cloud
224