-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathOCSController.php
More file actions
385 lines (348 loc) Β· 13 KB
/
Copy pathOCSController.php
File metadata and controls
385 lines (348 loc) Β· 13 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Richdocuments\Controller;
use Exception;
use GuzzleHttp\Exception\BadResponseException;
use OCA\Richdocuments\AppInfo\Application;
use OCA\Richdocuments\Db\DirectMapper;
use OCA\Richdocuments\DirectEditing\OfficeDirectEditor;
use OCA\Richdocuments\Exceptions\ExpiredTokenException;
use OCA\Richdocuments\Exceptions\UnknownTokenException;
use OCA\Richdocuments\Listener\RegisterDirectEditorListener;
use OCA\Richdocuments\Service\FederationService;
use OCA\Richdocuments\TemplateManager;
use OCA\Richdocuments\TokenManager;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\Constants;
use OCP\DirectEditing\IManager as IDirectEditingManager;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Http\Client\IClientService;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;
class OCSController extends \OCP\AppFramework\OCSController {
/**
* @param string $userId
*/
public function __construct(
string $appName,
IRequest $request,
private IRootFolder $rootFolder,
private IClientService $clientService,
private $userId,
private DirectMapper $directMapper,
private IURLGenerator $urlGenerator,
private TemplateManager $manager,
private TokenManager $tokenManager,
private IManager $shareManager,
private FederationService $federationService,
private IDirectEditingManager $directEditingManager,
private OfficeDirectEditor $officeDirectEditor,
private LoggerInterface $logger,
) {
parent::__construct($appName, $request);
}
/**
* @NoAdminRequired
*
* Init a direct editing session.
*
* @deprecated Use the server's direct editing API at
* POST /ocs/v2.php/apps/files/api/v1/directEditing/open with
* editorId=richdocuments. This endpoint is kept for
* backwards compatibility with older clients and now delegates
* to {@see \OCP\DirectEditing\IManager}.
*
* @param int $fileId
* @return DataResponse
* @throws OCSNotFoundException|OCSBadRequestException
*/
public function createDirect($fileId) {
try {
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$node = $userFolder->getFirstNodeById($fileId);
if ($node === null) {
throw new OCSNotFoundException();
}
if ($node instanceof Folder) {
throw new OCSBadRequestException('Cannot view folder');
}
if ($this->isAndroidV34OrAbove()) {
// Android v34+ uses the server's OCP\DirectEditing API natively
// (via /ocs/v2.php/apps/files/directEditing/open) but may fall back
// to this legacy endpoint β serve the server-managed URL so the
// TextEditorWebView flow works end-to-end.
$path = $userFolder->getRelativePath($node->getPath()) ?? $node->getName();
$this->directEditingManager->registerDirectEditor($this->officeDirectEditor);
/** @psalm-suppress UndefinedInterfaceMethod IManager does not expose open() but the concrete Manager does, same pattern as files-app DirectEditingController */
$token = $this->directEditingManager->open($path, Application::APPNAME, $node->getId());
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('files.DirectEditingView.edit', [
'token' => $token,
]),
]);
}
// iOS (all versions) and Android < 34: use the legacy richdocuments direct
// token. These clients open the URL in RichDocumentsEditorWebView which
// injects window.RichDocumentsMobileInterface. The server's generic
// TextEditorWebView (used for Android v34+) injects a different interface
// and these older clients cannot drive it.
$direct = $this->directMapper->newDirect($this->userId, $node->getId());
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('richdocuments.directView.show', [
'token' => $direct->getToken(),
]),
]);
} catch (NotFoundException) {
throw new OCSNotFoundException();
}
}
private function isAndroidV34OrAbove(): bool {
$userAgent = $this->request->getHeader('User-Agent');
if (preg_match(IRequest::USER_AGENT_CLIENT_ANDROID, $userAgent, $matches) !== 1) {
return false;
}
return (int)explode('.', $matches[1] ?? '0')[0] >= RegisterDirectEditorListener::MIN_MOBILE_CLIENT_VERSION;
}
/**
* Generate a direct editing link for a file in a public share to open with the current user
*
* @NoAdminRequired
* @BruteForceProtection(action=richdocumentsCreatePublic)
* @PublicPage
* @throws OCSForbiddenException
*/
public function createPublic(
string $shareToken,
?string $host = null,
string $path = '',
?string $password = null,
): DataResponse {
if ($host) {
$remoteCollabora = $this->federationService->getRemoteCollaboraURL($host);
if ($remoteCollabora === '') {
throw new OCSNotFoundException('Failed to connect to remote collabora instance.');
}
$wopi = $this->tokenManager->newInitiatorToken($host, null, $shareToken, true, $this->userId);
$client = $this->clientService->newClient();
try {
$response = $client->post(rtrim($host, '/') . '/ocs/v2.php/apps/richdocuments/api/v1/direct/share/initiator?format=json', [
'body' => [
'initiatorServer' => $this->urlGenerator->getAbsoluteURL(''),
'initiatorToken' => $wopi->getToken(),
'shareToken' => $shareToken,
'path' => $path,
'password' => $password
],
'timeout' => 30
]);
} catch (BadResponseException $e) {
$status = $e->getResponse()->getStatusCode();
if ($status === Http::STATUS_NOT_FOUND || $status === Http::STATUS_FORBIDDEN) {
$this->logger->debug('Failed to create link from initiator token. Remote denied access.');
$response = new DataResponse([], HTTP::STATUS_FORBIDDEN);
$response->throttle();
return $response;
}
$this->logger->error('Failed to create link from initiator token. Unexpected status code ' . $status, ['exception' => $e]);
return new DataResponse([], HTTP::STATUS_INTERNAL_SERVER_ERROR);
} catch (Exception $e) {
$this->logger->error('Failed to create link from initiator token. Unexpected response.', ['exception' => $e]);
return new DataResponse([], HTTP::STATUS_INTERNAL_SERVER_ERROR);
}
$url = \json_decode($response->getBody(), true)['ocs']['data']['url'];
return new DataResponse([
'url' => $url,
]);
}
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound) {
$response = new DataResponse([], HTTP::STATUS_NOT_FOUND);
$response->throttle();
return $response;
}
if ($share->getPassword() && !$this->shareManager->checkPassword($share, $password)) {
$response = new DataResponse([], HTTP::STATUS_FORBIDDEN);
$response->throttle();
return $response;
}
if (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {
$response = new DataResponse([], HTTP::STATUS_FORBIDDEN);
$response->throttle();
return $response;
}
$node = $share->getNode();
if ($node instanceof Folder) {
$node = $node->get($path);
}
$direct = $this->directMapper->newDirect($this->userId, $node->getId(), 0, $shareToken);
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('richdocuments.directView.show', [
'token' => $direct->getToken()
])
]);
}
/**
* @PublicPage
* @NoCSRFRequired
* @BruteForceProtection(action=richdocumentsCreatePublicFromInitiator)
* @throws OCSForbiddenException
*/
public function createPublicFromInitiator(
string $initiatorServer,
string $initiatorToken,
string $shareToken,
string $path = '',
?string $password = null,
): DataResponse {
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound) {
$response = new DataResponse([], HTTP::STATUS_NOT_FOUND);
$response->throttle();
return $response;
}
if ($share->getPassword() && !$this->shareManager->checkPassword($share, $password)) {
$response = new DataResponse([], HTTP::STATUS_FORBIDDEN);
$response->throttle();
return $response;
}
$node = $share->getNode();
if ($node instanceof Folder) {
$node = $node->get($path);
}
if (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {
return new DataResponse([], Http::STATUS_FORBIDDEN);
}
$direct = $this->directMapper->newDirect(null, $node->getId(), null, $shareToken, $initiatorServer, $initiatorToken);
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('richdocuments.directView.show', [
'token' => $direct->getToken()
])
]);
}
/**
* Generate a direct editing link for a file in a public share to open with the current user
*
* @NoAdminRequired
* @BruteForceProtection(action=richdocumentsCreatePublic)
* @PublicPage
*/
public function updateGuestName(string $access_token, string $guestName): DataResponse {
try {
$this->tokenManager->updateGuestName($access_token, $guestName);
return new DataResponse([], Http::STATUS_OK);
} catch (UnknownTokenException) {
$response = new DataResponse([], Http::STATUS_FORBIDDEN);
$response->throttle();
return $response;
} catch (ExpiredTokenException) {
$response = new DataResponse([], Http::STATUS_UNAUTHORIZED);
$response->throttle();
return $response;
}
}
/**
* @NoAdminRequired
* @PublicPage
*
* @deprecated Use the server's direct editing API at
* GET /ocs/v2.php/apps/files/api/v1/directEditing/templates/richdocuments/{creatorId}.
* This endpoint is kept for backwards compatibility and reads
* from the same {@see \OCA\Richdocuments\TemplateManager} as
* the new flow.
*
* @param string $type The template type
* @return DataResponse
* @throws OCSBadRequestException
*/
public function getTemplates($type) {
if (array_key_exists($type, TemplateManager::$tplTypes)) {
$templates = $this->manager->getAllFormatted($type);
return new DataResponse($templates);
}
throw new OCSBadRequestException('Wrong type');
}
/**
* @NoAdminRequired
*
* @deprecated Use the server's direct editing API at
* POST /ocs/v2.php/apps/files/api/v1/directEditing/create with
* editorId=richdocuments. This endpoint is kept for
* backwards compatibility with older clients and now delegates
* to {@see \OCP\DirectEditing\IManager}.
*
* @param string $path Where to create the document
* @param int $template The template id
*/
public function createFromTemplate($path, $template) {
if ($path === null || $template === null) {
throw new OCSBadRequestException('path and template must be set');
}
if (!$this->manager->isTemplate($template)) {
throw new OCSBadRequestException('Invalid template provided');
}
try {
$info = $this->mb_pathinfo($path);
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$folder = isset($info['dirname']) ? $userFolder->get($info['dirname']) : $userFolder;
$name = $folder->getNonExistingName($info['basename']);
$dirPath = isset($info['dirname']) ? rtrim($info['dirname'], '/') : '';
$targetPath = $dirPath === '' ? '/' . $name : $dirPath . '/' . $name;
// Derive the creator from the selected template's mimetype rather
// than the target filename: the latter is optional and can
// disagree with the template, which would route the request to
// the wrong creator and fail.
$templateFile = $this->manager->get($template);
$creatorId = $this->manager->getTemplateTypeForMime($templateFile->getMimeType());
if ($creatorId === null) {
throw new OCSBadRequestException('Unsupported template type');
}
$this->directEditingManager->registerDirectEditor($this->officeDirectEditor);
/** @psalm-suppress InvalidArgument IManager::create accepts mixed templateId despite an outdated nullable docblock */
$token = $this->directEditingManager->create($targetPath, Application::APPNAME, $creatorId, (string)$template);
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('files.DirectEditingView.edit', [
'token' => $token,
]),
]);
} catch (NotFoundException) {
throw new OCSNotFoundException();
} catch (OCSBadRequestException $e) {
throw $e;
} catch (\Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e]);
throw new OCSException('Failed to create new file from template.');
}
}
private function mb_pathinfo($filepath) {
$result = [];
preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', ltrim('/' . $filepath), $matches);
if ($matches[1]) {
$result['dirname'] = $matches[1];
}
if ($matches[2]) {
$result['basename'] = $matches[2];
}
if ($matches[5]) {
$result['extension'] = $matches[5];
}
if ($matches[3]) {
$result['filename'] = $matches[3];
}
return $result;
}
}