-
Notifications
You must be signed in to change notification settings - Fork 10
/
DropboxAPIService.php
314 lines (287 loc) · 10.3 KB
/
DropboxAPIService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
/**
* Nextcloud - dropbox
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Julien Veyssier
* @copyright Julien Veyssier 2020
*/
namespace OCA\Dropbox\Service;
use DateTime;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ServerException;
use OCA\Dropbox\AppInfo\Application;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\IL10N;
use OCP\Notification\IManager as INotificationManager;
use Psr\Log\LoggerInterface;
use Throwable;
class DropboxAPIService {
private IClient $client;
/**
* Service to make requests to Dropbox API
*/
public function __construct(
private string $appName,
private LoggerInterface $logger,
private IL10N $l10n,
private IConfig $config,
private INotificationManager $notificationManager,
IClientService $clientService) {
$this->client = $clientService->newClient();
}
/**
* @param string $userId
* @param string $subject
* @param array $params
* @return void
*/
public function sendNCNotification(string $userId, string $subject, array $params): void {
$manager = $this->notificationManager;
$notification = $manager->createNotification();
$notification->setApp(Application::APP_ID)
->setUser($userId)
->setDateTime(new DateTime())
->setObject('dum', 'dum')
->setSubject($subject, $params);
$manager->notify($notification);
}
/**
* @param string $accessToken
* @param string $refreshToken
* @param string $clientID
* @param string $clientSecret
* @param string $userId
* @param string $endPoint
* @param array $params
* @param string $method
* @return array{error?:string}
*/
public function request(string $accessToken, string $refreshToken, string $clientID, string $clientSecret, string $userId,
string $endPoint, array $params = [], string $method = 'GET'): array {
try {
$url = 'https://api.dropboxapi.com/2/' . $endPoint;
$options = [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'User-Agent' => 'Nextcloud Dropbox integration',
],
];
if (count($params) > 0) {
if ($method === 'GET') {
$paramsContent = http_build_query($params);
$url .= '?' . $paramsContent;
} else {
$options['headers']['Content-Type'] = 'application/json';
$options['body'] = json_encode($params);
}
}
if ($method === 'GET') {
$response = $this->client->get($url, $options);
} elseif ($method === 'POST') {
$response = $this->client->post($url, $options);
} elseif ($method === 'PUT') {
$response = $this->client->put($url, $options);
} elseif ($method === 'DELETE') {
$response = $this->client->delete($url, $options);
} else {
return ['error' => $this->l10n->t('Bad HTTP method')];
}
$body = $response->getBody();
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('Bad credentials')];
} else {
if (is_resource($body)) {
$body = stream_get_contents($body);
}
return json_decode($body, true);
}
} catch (ServerException | ClientException $e) {
$response = $e->getResponse();
if ($response->getStatusCode() === 401) {
$this->logger->info('Trying to REFRESH the access token', ['app' => $this->appName]);
// try to refresh the token
$result = $this->requestOAuthAccessToken($clientID, $clientSecret, [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
], 'POST');
if (isset($result['access_token'])) {
$this->logger->info('Dropbox access token successfully refreshed', ['app' => $this->appName]);
$accessToken = $result['access_token'];
$this->config->setUserValue($userId, Application::APP_ID, 'token', $accessToken);
// retry the request with new access token
return $this->request($accessToken, $refreshToken, $clientID, $clientSecret, $userId, $endPoint, $params, $method);
} else {
// impossible to refresh the token
return ['error' => $this->l10n->t('Token is not valid anymore. Impossible to refresh it.') . ' ' . ($result['error'] ?? '')];
}
}
$this->logger->warning('Dropbox API error : '.$e->getMessage(), ['app' => $this->appName]);
return ['error' => $e->getMessage()];
}
}
/**
* @param string $accessToken
* @param string $refreshToken
* @param string $clientID
* @param string $clientSecret
* @param string $userId
* @param resource $resource
* @param string $fileId
* @return array{success?: true, error?: string}
* @throws \OCP\PreConditionNotMetException
*/
public function downloadFile(string $accessToken, string $refreshToken, string $clientID, string $clientSecret, string $userId,
$resource, string $fileId, int $try = 0): array {
try {
// we could use https://content.dropboxapi.com/2/files/download
// with 'Dropbox-API-Arg' => json_encode(['path' => $fileId]),
// but the HTTP client can't return a stream for POST requests
// so this is a trick: we get a link and download from this link with a GET request
$url = 'https://api.dropboxapi.com/2/files/get_temporary_link';
$options = [
'timeout' => 0,
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'User-Agent' => 'Nextcloud Dropbox integration',
'Content-Type' => 'application/json',
],
'body' => json_encode(['path' => $fileId]),
];
$response = $this->client->post($url, $options);
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('Bad credentials')];
}
$body = $response->getBody();
if(is_resource($body)) {
$body = stream_get_contents($body);
}
$responseArray = json_decode($body, true);
if (is_null($responseArray) || !isset($responseArray['link'])) {
return ['error' => $this->l10n->t('Can\'t get the temporary dropbox link')];
}
// now download the file
$options = [
'timeout' => 0,
'stream' => true,
];
/** @var string $url */
$url = $responseArray['link'];
$response = $this->client->get($url, $options);
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('Bad credentials')];
}
$body = $response->getBody();
if (is_resource($body)) {
while (!feof($body)) {
// write ~5 MB chunks
$chunk = fread($body, 5000000);
fwrite($resource, $chunk);
}
} else {
fwrite($resource, $body);
}
return ['success' => true];
} catch (ServerException | ClientException $e) {
$response = $e->getResponse();
if ($response->getStatusCode() === 401) {
if ($try > 3) {
// impossible to refresh the token
$this->logger->info('Received the following response upon trying to download a file: '. $response->getBody()->getContents());
return ['error' => $this->l10n->t('Could not access file due to failed authentication.')];
}
$this->logger->info('Trying to REFRESH the access token', ['app' => $this->appName]);
// try to refresh the token
$result = $this->requestOAuthAccessToken($clientID, $clientSecret, [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
], 'POST');
if (isset($result['access_token'])) {
$this->logger->info('Dropbox access token successfully refreshed', ['app' => $this->appName]);
$accessToken = $result['access_token'];
$this->config->setUserValue($userId, Application::APP_ID, 'token', $accessToken);
// retry the request with new access token
return $this->downloadFile($accessToken, $refreshToken, $clientID, $clientSecret, $userId, $resource, $fileId, $try + 1);
} else {
// impossible to refresh the token
return ['error' => $this->l10n->t('Token is not valid anymore. Impossible to refresh it.') . ' ' . ($result['error'] ?? '')];
}
}
$this->logger->warning('Dropbox API error : '.$e->getMessage(), ['app' => $this->appName]);
return ['error' => $e->getMessage()];
} catch (ConnectException $e) {
$this->logger->warning('Dropbox API connection error : '.$e->getMessage(), ['app' => $this->appName]);
return ['error' => $e->getMessage()];
} catch (Exception | Throwable $e) {
$this->logger->warning('Dropbox API connection error : '.$e->getMessage(), ['app' => $this->appName]);
return ['error' => $e->getMessage()];
}
}
/**
* @param string $clientID
* @param string $clientSecret
* @param array $params
* @param string $method
* @return array{access_token?: string, refresh_token?: string, account_id?: string, uid?: string, error_description?: string, error?: string}
*/
public function requestOAuthAccessToken(string $clientID, string $clientSecret, array $params = [], string $method = 'GET'): array {
try {
$url = 'https://api.dropboxapi.com/oauth2/token';
$options = [
'headers' => [
'Authorization' => 'Basic '. base64_encode($clientID. ':' . $clientSecret),
'User-Agent' => 'Nextcloud Dropbox integration'
],
];
if (count($params) > 0) {
if ($method === 'GET') {
$paramsContent = http_build_query($params);
$url .= '?' . $paramsContent;
} else {
$options['body'] = $params;
}
}
if ($method === 'GET') {
$response = $this->client->get($url, $options);
} elseif ($method === 'POST') {
$response = $this->client->post($url, $options);
} elseif ($method === 'PUT') {
$response = $this->client->put($url, $options);
} elseif ($method === 'DELETE') {
$response = $this->client->delete($url, $options);
} else {
return ['error' => $this->l10n->t('Bad HTTP method')];
}
$body = $response->getBody();
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('OAuth access token refused')];
} else {
if (is_resource($body)) {
$body = stream_get_contents($body);
}
return json_decode($body, true);
}
} catch (ClientException $e) {
$this->logger->warning('Dropbox OAuth error : '.$e->getMessage(), ['app' => $this->appName]);
$result = ['error' => $e->getMessage()];
$response = $e->getResponse();
$body = $response->getBody();
/** @var array{error_description?:string} $decodedBody */
$decodedBody = json_decode($body->getContents(), true);
if (isset($decodedBody['error_description'])) {
$result['error_description'] = $decodedBody['error_description'];
}
return $result;
}
}
}