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
|
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Julius Härtl <jus@bitgrid.net>
* @author Tobias Kaminsky <tobias@kaminsky.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\DirectEditing;
use Doctrine\DBAL\FetchMode;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\DirectEditing\ACreateFromTemplate;
use OCP\DirectEditing\IEditor;
use \OCP\DirectEditing\IManager;
use OCP\DirectEditing\IToken;
use OCP\DirectEditing\RegisterDirectEditorEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Security\ISecureRandom;
use OCP\Share\IShare;
use function array_key_exists;
use function in_array;
class Manager implements IManager {
private const TOKEN_CLEANUP_TIME = 12 * 60 * 60 ;
public const TABLE_TOKENS = 'direct_edit';
/** @var IEditor[] */
private $editors = [];
/** @var IDBConnection */
private $connection;
/**
* @var ISecureRandom
*/
private $random;
private $userId;
private $rootFolder;
/** @var IL10N */
private $l10n;
public function __construct(
ISecureRandom $random,
IDBConnection $connection,
IUserSession $userSession,
IRootFolder $rootFolder,
IFactory $l10nFactory
) {
$this->random = $random;
$this->connection = $connection;
$this->userId = $userSession->getUser() ? $userSession->getUser()->getUID() : null;
$this->rootFolder = $rootFolder;
$this->l10n = $l10nFactory->get('core');
}
public function registerDirectEditor(IEditor $directEditor): void {
$this->editors[$directEditor->getId()] = $directEditor;
}
public function getEditors(): array {
return $this->editors;
}
public function getTemplates(string $editor, string $type): array {
if (!array_key_exists($editor, $this->editors)) {
throw new \RuntimeException('No matching editor found');
}
$templates = [];
foreach ($this->editors[$editor]->getCreators() as $creator) {
if ($creator->getId() === $type) {
$templates = [
'empty' => [
'id' => 'empty',
'title' => $this->l10n->t('Empty file'),
'preview' => null
]
];
if ($creator instanceof ACreateFromTemplate) {
$templates = $creator->getTemplates();
}
$templates = array_map(function ($template) use ($creator) {
$template['extension'] = $creator->getExtension();
$template['mimetype'] = $creator->getMimetype();
return $template;
}, $templates);
}
}
$return = [];
$return['templates'] = $templates;
return $return;
}
public function create(string $path, string $editorId, string $creatorId, $templateId = null): string {
$userFolder = $this->rootFolder->getUserFolder($this->userId);
if ($userFolder->nodeExists($path)) {
throw new \RuntimeException('File already exists');
} else {
$file = $userFolder->newFile($path);
$editor = $this->getEditor($editorId);
$creators = $editor->getCreators();
foreach ($creators as $creator) {
if ($creator->getId() === $creatorId) {
$creator->create($file, $creatorId, $templateId);
return $this->createToken($editorId, $file, $path);
}
}
}
throw new \RuntimeException('No creator found');
}
public function open(string $filePath, string $editorId = null): string {
/** @var File $file */
$file = $this->rootFolder->getUserFolder($this->userId)->get($filePath);
if ($editorId === null) {
$editorId = $this->findEditorForFile($file);
}
if (!array_key_exists($editorId, $this->editors)) {
throw new \RuntimeException("Editor $editorId is unknown");
}
return $this->createToken($editorId, $file, $filePath);
}
private function findEditorForFile(File $file) {
foreach ($this->editors as $editor) {
if (in_array($file->getMimeType(), $editor->getMimetypes())) {
return $editor->getId();
}
}
throw new \RuntimeException('No default editor found for files mimetype');
}
public function edit(string $token): Response {
try {
/** @var IEditor $editor */
$tokenObject = $this->getToken($token);
if ($tokenObject->hasBeenAccessed()) {
throw new \RuntimeException('Token has already been used and can only be used for followup requests');
}
$editor = $this->getEditor($tokenObject->getEditor());
$this->accessToken($token);
} catch (\Throwable $throwable) {
$this->invalidateToken($token);
return new NotFoundResponse();
}
return $editor->open($tokenObject);
}
public function editSecure(File $file, string $editorId): TemplateResponse {
// TODO: Implementation in follow up
}
private function getEditor($editorId): IEditor {
if (!array_key_exists($editorId, $this->editors)) {
throw new \RuntimeException('No editor found');
}
return $this->editors[$editorId];
}
public function getToken(string $token): IToken {
$query = $this->connection->getQueryBuilder();
$query->select('*')->from(self::TABLE_TOKENS)
->where($query->expr()->eq('token', $query->createNamedParameter($token, IQueryBuilder::PARAM_STR)));
$result = $query->execute();
if ($tokenRow = $result->fetch(FetchMode::ASSOCIATIVE)) {
return new Token($this, $tokenRow);
}
throw new \RuntimeException('Failed to validate the token');
}
public function cleanup(): int {
$query = $this->connection->getQueryBuilder();
$query->delete(self::TABLE_TOKENS)
->where($query->expr()->lt('timestamp', $query->createNamedParameter(time() - self::TOKEN_CLEANUP_TIME)));
return $query->execute();
}
public function refreshToken(string $token): bool {
$query = $this->connection->getQueryBuilder();
$query->update(self::TABLE_TOKENS)
->set('timestamp', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('token', $query->createNamedParameter($token, IQueryBuilder::PARAM_STR)));
$result = $query->execute();
return $result !== 0;
}
public function invalidateToken(string $token): bool {
$query = $this->connection->getQueryBuilder();
$query->delete(self::TABLE_TOKENS)
->where($query->expr()->eq('token', $query->createNamedParameter($token, IQueryBuilder::PARAM_STR)));
$result = $query->execute();
return $result !== 0;
}
public function accessToken(string $token): bool {
$query = $this->connection->getQueryBuilder();
$query->update(self::TABLE_TOKENS)
->set('accessed', $query->createNamedParameter(true, IQueryBuilder::PARAM_BOOL))
->set('timestamp', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('token', $query->createNamedParameter($token, IQueryBuilder::PARAM_STR)));
$result = $query->execute();
return $result !== 0;
}
public function invokeTokenScope($userId): void {
\OC_User::setIncognitoMode(true);
\OC_User::setUserId($userId);
}
public function createToken($editorId, File $file, string $filePath, IShare $share = null): string {
$token = $this->random->generate(64, ISecureRandom::CHAR_HUMAN_READABLE);
$query = $this->connection->getQueryBuilder();
$query->insert(self::TABLE_TOKENS)
->values([
'token' => $query->createNamedParameter($token),
'editor_id' => $query->createNamedParameter($editorId),
'file_id' => $query->createNamedParameter($file->getId()),
'file_path' => $query->createNamedParameter($filePath),
'user_id' => $query->createNamedParameter($this->userId),
'share_id' => $query->createNamedParameter($share !== null ? $share->getId(): null),
'timestamp' => $query->createNamedParameter(time())
]);
$query->execute();
return $token;
}
/**
* @param $userId
* @param $fileId
* @param null $filePath
* @return Node
* @throws NotFoundException
*/
public function getFileForToken($userId, $fileId, $filePath = null): Node {
$userFolder = $this->rootFolder->getUserFolder($userId);
if ($filePath !== null) {
return $userFolder->get($filePath);
}
$files = $userFolder->getById($fileId);
if (count($files) === 0) {
throw new NotFoundException('File nound found by id ' . $fileId);
}
return $files[0];
}
}
|