-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontents.ts
426 lines (368 loc) · 10.2 KB
/
contents.ts
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { URLExt } from '@jupyterlab/coreutils';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { Contents } from '@jupyterlab/services';
import { APIRequestContext, APIResponse, Page } from '@playwright/test';
import fetch, { RequestInit, Response } from 'node-fetch';
import * as path from 'path';
import {
IPluginNameToInterfaceMap,
PLUGIN_ID_DOC_MANAGER
} from './inpage/tokens';
import * as Utils from './utils';
/**
* Helper class to interact with contents server API
*
* Those helpers are directly requesting the Jupyter server to
* carry contents tasks; except rename operations if the page model
* is provided.
*/
export class ContentsHelper {
/**
* Construct a new instance of ContentsHelper
*
* @param baseURL Server base URL
* @param page Playwright page model object
* @param request Playwright API request context
*/
constructor(
readonly baseURL: string,
readonly page?: Page,
request?: APIRequestContext
) {
if (request) {
this.request = request;
} else if (page) {
this.request = page.context().request;
}
}
/**
* Return the model for a path.
*
* @param path Path
* @param type Path type
* @returns Element metadata
*/
async getContentMetadata(
path: string,
type: 'file' | 'directory' = 'file'
): Promise<Contents.IModel | null> {
const data = {
type,
// Get the content only for directory
content: type === 'directory' ? 1 : 0
};
let response = null;
try {
response = await this._fetch(path + URLExt.objectToQueryString(data));
} catch (error) {
console.error(`Fail to get content metadata for ${path}`, error);
}
const succeeded =
(typeof response?.status === 'function'
? response.status()
: response?.status) === 200;
if (succeeded) {
return response!.json();
}
return null;
}
/**
* Whether a directory exists or not
*
* @param dirPath Directory path
* @returns Directory existence status
*/
async directoryExists(dirPath: string): Promise<boolean> {
const content = await this.getContentMetadata(dirPath, 'directory');
return content?.type === 'directory';
}
/**
* Whether a file exists or not
*
* @param filePath File path
* @returns File existence status
*/
async fileExists(filePath: string): Promise<boolean> {
const content = await this.getContentMetadata(filePath);
return content?.type === 'notebook' || content?.type === 'file';
}
/**
* Create a directory
*
* @param dirPath Directory path
* @returns Action success status
*/
async createDirectory(dirPath: string): Promise<boolean> {
const directories = dirPath.split('/');
let path = '';
for (const directory of directories) {
if (directory.trim() === '') {
continue;
}
if (path !== '') {
path += '/';
}
path += directory;
await this._createDirectory(path);
}
return true;
}
/**
* Upload a directory recursively in the Jupyter server
*
* @param sourcePath Local source path
* @param destinationPath Server destination path
* @returns Action success status
*/
async uploadDirectory(
sourcePath: string,
destinationPath?: string
): Promise<boolean> {
const pos = sourcePath.lastIndexOf('/');
const sourceDirName = sourcePath.substring(pos + 1);
destinationPath = destinationPath ?? sourceDirName;
const files = Utils.getFilesInDirectory(sourcePath);
for (const file of files) {
const relativePath = file.substring(sourcePath.length + 1);
await this.uploadFile(file, `${destinationPath}/${relativePath}`);
}
return true;
}
/**
* Upload content as file to JupyterLab.
*
* Note: the destinationPath is the filepath on the server.
*
* @param content Content file to upload
* @param format Content format
* @param destinationPath Destination filepath
* @returns Whether the action succeeded or not.
*/
async uploadContent(
content: string,
format: 'base64' | 'text' | 'json',
destinationPath: string
): Promise<boolean> {
const pos = destinationPath.lastIndexOf('/');
if (pos !== -1) {
const destDir = destinationPath?.substring(0, pos);
if (destDir && !(await this.directoryExists(destDir))) {
await this.createDirectory(destDir);
}
}
const data = JSON.stringify({
content,
format,
type: 'file'
});
let response = null;
try {
response = await this._fetch(destinationPath, {
method: 'PUT',
body: data
});
} catch (error) {
console.error(
`Failed to upload content to server ${destinationPath}`,
error
);
}
const succeeded =
(typeof response?.status === 'function'
? response.status()
: response?.status) === 201;
if (succeeded) {
return await this.fileExists(destinationPath);
}
return false;
}
/**
* Upload a file to JupyterLab.
*
* Note: the destinationPath is the filepath on the server.
*
* @param sourcePath Filepath to upload
* @param destinationPath Destination filepath
* @returns Whether the action succeeded or not.
*/
async uploadFile(
sourcePath: string,
destinationPath?: string
): Promise<boolean> {
return this.uploadContent(
Utils.base64EncodeFile(sourcePath),
'base64',
destinationPath ?? path.basename(sourcePath)
);
}
/**
* Delete a file
*
* @param filePath File path
* @returns Action success status
*/
async deleteFile(filePath: string): Promise<boolean> {
const fileName = filePath;
let response = null;
try {
response = await this._fetch(fileName, {
method: 'DELETE'
});
} catch (error) {
console.error(`Failed to delete file ${filePath}`, error);
}
const succeeded =
(typeof response?.status === 'function'
? response.status()
: response?.status) === 204;
if (succeeded) {
return !(await this.fileExists(fileName));
}
return false;
}
/**
* Delete recursively a directory
*
* @param dirPath Directory path
* @returns Action success status
*/
async deleteDirectory(dirPath: string): Promise<boolean> {
const dirContent = await this.getContentMetadata(dirPath, 'directory');
if (!(dirContent && dirContent.type === 'directory')) {
return false;
}
let anyFailed = false;
// delete directory contents first
for (const item of dirContent.content) {
if (item.type === 'directory') {
if (!(await this.deleteDirectory(item.path))) {
anyFailed = true;
}
} else {
if (!(await this.deleteFile(item.path))) {
anyFailed = true;
}
}
}
if (!(await this.deleteFile(dirPath))) {
anyFailed = true;
}
return !anyFailed;
}
/**
* Rename a file
*
* @param oldName Old name
* @param newName New name
* @returns Action success status
*/
async renameFile(oldName: string, newName: string): Promise<boolean> {
if (this.page) {
// Rename through REST API does not propagate to opened widgets
// => Use galata in-page if page is available
return await this.page.evaluate(
async ({ pluginId, oldName, newName }) => {
const docManager = (await window.galataip.getPlugin(
pluginId
)) as IDocumentManager;
const result = await docManager.rename(oldName, newName);
return result !== null;
},
{
pluginId: PLUGIN_ID_DOC_MANAGER as keyof IPluginNameToInterfaceMap,
oldName: oldName,
newName: newName
}
);
}
let response = null;
try {
response = await this._fetch(oldName, {
method: 'PATCH',
body: JSON.stringify({ path: newName })
});
} catch (error) {
console.error(`Failed to rename file ${oldName} to ${newName}`, error);
}
const succeeded =
(typeof response?.status === 'function'
? response.status()
: response?.status) === 200;
if (succeeded) {
return await this.fileExists(newName);
}
return false;
}
/**
* Rename a directory
*
* @param oldName Old name
* @param newName New name
* @returns Action success status
*/
async renameDirectory(oldName: string, newName: string): Promise<boolean> {
return await this.renameFile(oldName, newName);
}
/**
* Wait for a contents API response
*
* @param trigger Action to trigger while waiting
*/
async waitForAPIResponse(
trigger?: () => Promise<void> | void
): Promise<void> {
if (!this.page) {
return Promise.reject('No page available.');
}
await Promise.all([
this.page.waitForResponse(response =>
response.url().includes('api/contents')
),
Promise.resolve(trigger?.call(this))
]);
}
protected async _createDirectory(dirPath: string): Promise<boolean> {
const body = JSON.stringify({
format: 'json',
type: 'directory'
});
let response = null;
try {
response = await this._fetch(dirPath, {
method: 'PUT',
body
});
} catch (error) {
console.error(`Failed to create directory ${dirPath}`, error);
}
return (
(typeof response?.status === 'function'
? response.status()
: response?.status) === 201
);
}
private async _fetch(
path: string,
request: RequestInit = { method: 'GET' }
): Promise<APIResponse | Response | null> {
const baseUrl = this.page ? await Utils.getBaseUrl(this.page) : '/';
const token = this.page ? await Utils.getToken(this.page) : '';
let url = URLExt.join(baseUrl, 'api/contents', path);
if (token) {
request.headers = { Authorization: `Token ${token}` };
}
let response: APIResponse | Response | null = null;
if (this.request) {
response = await this.request.fetch(url, {
...(request as any),
data: request.body
});
} else {
response = await fetch(url, request);
}
return response;
}
readonly request: APIRequestContext | null = null;
}