This repository has been archived by the owner on Aug 3, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
contents.ts
474 lines (443 loc) · 13 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { Signal, ISignal } from '@phosphor/signaling';
import { PathExt } from '@jupyterlab/coreutils';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { Contents, ServerConnection } from '@jupyterlab/services';
import * as drive from './drive';
import { makeError } from './gapi';
/**
* A contents manager that passes file operations to the server.
*
* This includes checkpointing with the normal file operations.
*/
export class GoogleDrive implements Contents.IDrive {
/**
* Construct a new contents manager object.
*
* @param options - The options used to initialize the object.
*/
constructor(registry: DocumentRegistry) {
this._docRegistry = registry;
// Construct a function to make a best-guess IFileType
// for a given path.
this._fileTypeForPath = (path: string) => {
const fileTypes = registry.getFileTypesForPath(path);
return fileTypes.length === 0
? registry.getFileType('text')!
: fileTypes[0];
};
// Construct a function to return a best-guess IFileType
// for a given contents model.
this._fileTypeForContentsModel = (model: Partial<Contents.IModel>) => {
return registry.getFileTypeForModel(model);
};
}
/**
* The name of the drive.
*/
get name(): 'GDrive' {
return 'GDrive';
}
/**
* Server settings (unused for interfacing with Google Drive).
*/
readonly serverSettings: ServerConnection.ISettings;
/**
* A signal emitted when a file operation takes place.
*/
get fileChanged(): ISignal<this, Contents.IChangedArgs> {
return this._fileChanged;
}
/**
* Test whether the manager has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**h
* Dispose of the resources held by the manager.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Get the base url of the manager.
*/
get baseUrl(): string {
return this._baseUrl;
}
/**
* Get a file or directory.
*
* @param path: The path to the file.
*
* @param options: The options used to fetch the file.
*
* @returns A promise which resolves with the file content.
*/
async get(
path: string,
options?: Contents.IFetchOptions
): Promise<Contents.IModel> {
const getContent = options ? !!options.content : true;
// TODO: the contents manager probably should not be passing in '.'.
path = path === '.' ? '' : path;
const contents = await drive.contentsModelForPath(
path,
getContent,
this._fileTypeForPath
);
try {
Contents.validateContentsModel(contents);
} catch (error) {
throw makeError(200, error.message);
}
return contents;
}
/**
* Get an encoded download url given a file path.
*
* @param path - An absolute POSIX file path on the server.
*
* #### Notes
* It is expected that the path contains no relative paths,
* use [[ContentsManager.getAbsolutePath]] to get an absolute
* path if necessary.
*/
getDownloadUrl(path: string): Promise<string> {
return drive.urlForFile(path);
}
/**
* Create a new untitled file or directory in the specified directory path.
*
* @param options: The options used to create the file.
*
* @returns A promise which resolves with the created file content when the
* file is created.
*/
async newUntitled(
options: Contents.ICreateOptions = {}
): Promise<Contents.IModel> {
// Set default values.
let ext = '';
let baseName = 'Untitled';
let path = '';
let contentType: Contents.ContentType = 'notebook';
let fileType: DocumentRegistry.IFileType;
if (options) {
// Add leading `.` to extension if necessary.
ext = options.ext ? PathExt.normalizeExtension(options.ext) : ext;
// If we are not creating in the root directory.
path = options.path || '';
contentType = options.type || 'notebook';
}
let model: Partial<Contents.IModel>;
if (contentType === 'notebook') {
fileType = DocumentRegistry.defaultNotebookFileType;
ext = ext || fileType.extensions[0];
baseName = 'Untitled';
const modelFactory = this._docRegistry.getModelFactory('Notebook');
if (!modelFactory) {
throw Error('No model factory is registered with the DocRegistry');
}
model = {
type: fileType.contentType,
content: modelFactory.createNew().toJSON(),
mimetype: fileType.mimeTypes[0],
format: fileType.fileFormat
};
} else if (contentType === 'file') {
fileType = DocumentRegistry.defaultTextFileType;
ext = ext || fileType.extensions[0];
baseName = 'untitled';
model = {
type: fileType.contentType,
content: '',
mimetype: fileType.mimeTypes[0],
format: fileType.fileFormat
};
} else if (contentType === 'directory') {
fileType = DocumentRegistry.defaultDirectoryFileType;
ext = ext || '';
baseName = 'Untitled Folder';
model = {
type: fileType.contentType,
content: [],
format: fileType.fileFormat
};
} else {
throw new Error('Unrecognized type ' + contentType);
}
const name = await this._getNewFilename(path, ext, baseName);
const m = { ...model, name };
path = PathExt.join(path, name);
const contents = await drive.uploadFile(
path,
m,
fileType,
false,
this._fileTypeForPath
);
try {
Contents.validateContentsModel(contents);
} catch (error) {
throw makeError(201, error.message);
}
this._fileChanged.emit({
type: 'new',
oldValue: null,
newValue: contents
});
return contents;
}
/**
* Delete a file.
*
* @param path - The path to the file.
*
* @returns A promise which resolves when the file is deleted.
*/
async delete(path: string): Promise<void> {
await drive.deleteFile(path);
this._fileChanged.emit({
type: 'delete',
oldValue: { path },
newValue: null
});
}
/**
* Rename a file or directory.
*
* @param path - The original file path.
*
* @param newPath - The new file path.
*
* @returns A promise which resolves with the new file contents model when
* the file is renamed.
*/
async rename(path: string, newPath: string): Promise<Contents.IModel> {
if (path === newPath) {
return this.get(path);
}
const contents = await drive.moveFile(path, newPath, this._fileTypeForPath);
try {
Contents.validateContentsModel(contents);
} catch (error) {
throw makeError(200, error.message);
}
this._fileChanged.emit({
type: 'rename',
oldValue: { path },
newValue: contents
});
return contents;
}
/**
* Save a file.
*
* @param path - The desired file path.
*
* @param options - Optional overrides to the model.
*
* @returns A promise which resolves with the file content model when the
* file is saved.
*/
async save(
path: string,
options: Partial<Contents.IModel>
): Promise<Contents.IModel> {
const fileType = this._fileTypeForContentsModel(options);
const contents = await this.get(path).then(
contents => {
// The file exists.
if (options) {
// Overwrite the existing file.
return drive.uploadFile(
path,
options,
fileType,
true,
this._fileTypeForPath
);
} else {
// File exists, but we are not saving anything
// to it? Just return the contents.
return contents;
}
},
() => {
// The file does not exist already, create a new one.
return drive.uploadFile(
path,
options,
fileType,
false,
this._fileTypeForPath
);
}
);
try {
Contents.validateContentsModel(contents);
} catch (error) {
throw makeError(200, error.message);
}
this._fileChanged.emit({
type: 'save',
oldValue: null,
newValue: contents
});
return contents;
}
/**
* Copy a file into a given directory.
*
* @param path - The original file path.
*
* @param toDir - The destination directory path.
*
* @returns A promise which resolves with the new contents model when the
* file is copied.
*/
async copy(fromFile: string, toDir: string): Promise<Contents.IModel> {
let fileBasename = PathExt.basename(fromFile).split('.')[0];
fileBasename += '-Copy';
const ext = PathExt.extname(fromFile);
const name = await this._getNewFilename(toDir, ext, fileBasename);
const contents = await drive.copyFile(
fromFile,
PathExt.join(toDir, name),
this._fileTypeForPath
);
try {
Contents.validateContentsModel(contents);
} catch (error) {
throw makeError(201, error.message);
}
this._fileChanged.emit({
type: 'new',
oldValue: null,
newValue: contents
});
return contents;
}
/**
* Create a checkpoint for a file.
*
* @param path - The path of the file.
*
* @returns A promise which resolves with the new checkpoint model when the
* checkpoint is created.
*/
async createCheckpoint(path: string): Promise<Contents.ICheckpointModel> {
const checkpoint = await drive.pinCurrentRevision(path);
try {
Contents.validateCheckpointModel(checkpoint);
} catch (error) {
throw makeError(200, error.message);
}
return checkpoint;
}
/**
* List available checkpoints for a file.
*
* @param path - The path of the file.
*
* @returns A promise which resolves with a list of checkpoint models for
* the file.
*/
async listCheckpoints(path: string): Promise<Contents.ICheckpointModel[]> {
const checkpoints = await drive.listRevisions(path);
try {
for (let checkpoint of checkpoints) {
Contents.validateCheckpointModel(checkpoint);
}
} catch (error) {
throw makeError(200, error.message);
}
return checkpoints;
}
/**
* Restore a file to a known checkpoint state.
*
* @param path - The path of the file.
*
* @param checkpointID - The id of the checkpoint to restore.
*
* @returns A promise which resolves when the checkpoint is restored.
*/
async restoreCheckpoint(path: string, checkpointID: string): Promise<void> {
// TODO: should this emit a signal?
const fileType = this._fileTypeForPath(path);
return drive.revertToRevision(path, checkpointID, fileType);
}
/**
* Delete a checkpoint for a file.
*
* @param path - The path of the file.
*
* @param checkpointID - The id of the checkpoint to delete.
*
* @returns A promise which resolves when the checkpoint is deleted.
*/
async deleteCheckpoint(path: string, checkpointID: string): Promise<void> {
return drive.unpinRevision(path, checkpointID);
}
/**
* Obtains the filename that should be used for a new file in a given
* folder. This is the next file in the series Untitled0, Untitled1, ... in
* the given drive folder. As a fallback, returns Untitled.
*
* @param path - The path of the directory in which we are making the file.
* @param ext - The file extension.
* @param baseName - The base name of the new file
* @return A promise fullfilled with the new filename.
*/
private async _getNewFilename(
path: string,
ext: string,
baseName: string
): Promise<string> {
// Check that the target directory is a valid
// directory (i.e., not the pseudo-root or
// the "Shared with me" directory).
if (drive.isDummy(path)) {
throw makeError(
400,
`Google Drive: "${path}"` + ' is not a valid save directory'
);
}
// Get the file listing for the directory.
const query =
"name contains '" + baseName + "' and name contains '" + ext + "'";
const resourceList = await drive.searchDirectory(path, query);
const existingNames: any = {};
for (let i = 0; i < resourceList.length; i++) {
existingNames[resourceList[i].name!] = true;
}
// Loop over the list and select the first name that
// does not exist. Note that the loop is N+1 iterations,
// so is guaranteed to come up with a name that is not
// in `existingNames`.
for (let i = 0; i <= resourceList.length; i++) {
const filename = baseName + (i > 0 ? String(i) : '') + ext;
if (!existingNames[filename]) {
return filename;
}
}
// Should not get here.
throw Error('Could not find a valid filename');
}
private _baseUrl = 'https://www.googleapis.com/drive/v3';
private _isDisposed = false;
private _docRegistry: DocumentRegistry;
private _fileTypeForPath: (path: string) => DocumentRegistry.IFileType;
private _fileTypeForContentsModel: (
model: Partial<Contents.IModel>
) => DocumentRegistry.IFileType;
private _fileChanged = new Signal<this, Contents.IChangedArgs>(this);
}