Skip to content

Commit 811c12c

Browse files
authored
Merge pull request #67 from DenisaCG/driveOperations
Add drive handling operations
2 parents 3121c8f + 283377c commit 811c12c

File tree

6 files changed

+239
-36
lines changed

6 files changed

+239
-36
lines changed

jupyter_drives/handlers.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,10 @@ async def get(self, drive: str = "", path: str = ""):
8989
@tornado.web.authenticated
9090
async def post(self, drive: str = "", path: str = ""):
9191
body = self.get_json_body()
92-
result = await self._manager.new_file(drive, path, **body)
92+
if 'location' in body:
93+
result = await self._manager.new_drive(drive, **body)
94+
else:
95+
result = await self._manager.new_file(drive, path, **body)
9396
self.finish(result)
9497

9598
@tornado.web.authenticated

jupyter_drives/manager.py

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -445,17 +445,22 @@ async def delete_file(self, drive_name, path):
445445
try:
446446
# eliminate leading and trailing backslashes
447447
path = path.strip('/')
448-
is_dir = await self._file_system._isdir(drive_name + '/' + path)
449-
if is_dir == True:
450-
await self._fix_dir(drive_name, path)
451-
await self._file_system._rm(drive_name + '/' + path, recursive = True)
448+
object_name = drive_name # in case we are only deleting the drive itself
449+
if path != '':
450+
# deleting objects within a drive
451+
is_dir = await self._file_system._isdir(drive_name + '/' + path)
452+
if is_dir == True:
453+
await self._fix_dir(drive_name, path)
454+
object_name = drive_name + '/' + path
455+
await self._file_system._rm(object_name, recursive = True)
452456

453457
# checking for remaining directories and deleting them
454-
stream = obs.list(self._content_managers[drive_name]["store"], path, chunk_size=100, return_arrow=True)
455-
async for batch in stream:
456-
contents_list = pyarrow.record_batch(batch).to_pylist()
457-
for object in contents_list:
458-
await self._fix_dir(drive_name, object["path"], delete_only = True)
458+
if object_name != drive_name:
459+
stream = obs.list(self._content_managers[drive_name]["store"], path, chunk_size=100, return_arrow=True)
460+
async for batch in stream:
461+
contents_list = pyarrow.record_batch(batch).to_pylist()
462+
for object in contents_list:
463+
await self._fix_dir(drive_name, object["path"], delete_only = True)
459464

460465
except Exception as e:
461466
raise tornado.web.HTTPError(
@@ -563,6 +568,23 @@ async def check_file(self, drive_name, path):
563568

564569
return
565570

571+
async def new_drive(self, new_drive_name, location='us-east-1'):
572+
"""Create a new drive in the given location.
573+
574+
Args:
575+
new_drive_name: name of new drive to create
576+
location: (optional) region of bucket
577+
"""
578+
try:
579+
await self._file_system._mkdir(new_drive_name, region_name = location)
580+
except Exception as e:
581+
raise tornado.web.HTTPError(
582+
status_code= httpx.codes.BAD_REQUEST,
583+
reason=f"The following error occured when creating the new drive: {e}",
584+
)
585+
586+
return
587+
566588
async def _get_drive_location(self, drive_name):
567589
"""Helping function for getting drive region.
568590

src/contents.ts

Lines changed: 56 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ import {
1919
countObjectNameAppearances,
2020
renameObjects,
2121
copyObjects,
22-
presignedLink
22+
presignedLink,
23+
createDrive,
24+
getDrivesList
2325
} from './requests';
2426

2527
let data: Contents.IModel = {
@@ -244,28 +246,37 @@ export class Drive implements Contents.IDrive {
244246
} else {
245247
// retriving list of contents from root
246248
// in our case: list available drives
247-
const drivesList: Contents.IModel[] = [];
248-
for (const drive of this._drivesList) {
249-
drivesList.push({
250-
name: drive.name,
251-
path: drive.name,
252-
last_modified: '',
253-
created: drive.creationDate,
254-
content: [],
255-
format: 'json',
256-
mimetype: '',
257-
size: undefined,
258-
writable: true,
259-
type: 'directory'
260-
});
249+
const drivesListInfo: Contents.IModel[] = [];
250+
// fetch list of available drives
251+
try {
252+
this._drivesList = await getDrivesList();
253+
for (const drive of this._drivesList) {
254+
drivesListInfo.push({
255+
name: drive.name,
256+
path: drive.name,
257+
last_modified: '',
258+
created: drive.creationDate,
259+
content: [],
260+
format: 'json',
261+
mimetype: '',
262+
size: undefined,
263+
writable: true,
264+
type: 'directory'
265+
});
266+
}
267+
} catch (error) {
268+
console.log(
269+
'Failed loading available drives list, with error: ',
270+
error
271+
);
261272
}
262273

263274
data = {
264275
name: this._name,
265276
path: this._name,
266277
last_modified: '',
267278
created: '',
268-
content: drivesList,
279+
content: drivesListInfo,
269280
format: 'json',
270281
mimetype: '',
271282
size: undefined,
@@ -390,16 +401,11 @@ export class Drive implements Contents.IDrive {
390401
* @returns A promise which resolves when the file is deleted.
391402
*/
392403
async delete(localPath: string): Promise<void> {
393-
if (localPath !== '') {
394-
const currentDrive = extractCurrentDrive(localPath, this._drivesList);
404+
const currentDrive = extractCurrentDrive(localPath, this._drivesList);
395405

396-
await deleteObjects(currentDrive.name, {
397-
path: formatPath(localPath)
398-
});
399-
} else {
400-
// create new element at root would mean modifying a drive
401-
console.warn('Operation not supported.');
402-
}
406+
await deleteObjects(currentDrive.name, {
407+
path: formatPath(localPath)
408+
});
403409

404410
this._fileChanged.emit({
405411
type: 'delete',
@@ -630,6 +636,31 @@ export class Drive implements Contents.IDrive {
630636
return data;
631637
}
632638

639+
/**
640+
* Create a new drive.
641+
*
642+
* @param options: The options used to create the drive.
643+
*
644+
* @returns A promise which resolves with the contents model.
645+
*/
646+
async newDrive(
647+
newDriveName: string,
648+
region: string
649+
): Promise<Contents.IModel> {
650+
data = await createDrive(newDriveName, {
651+
location: region
652+
});
653+
654+
Contents.validateContentsModel(data);
655+
this._fileChanged.emit({
656+
type: 'new',
657+
oldValue: null,
658+
newValue: data
659+
});
660+
661+
return data;
662+
}
663+
633664
/**
634665
* Create a checkpoint for a file.
635666
*

src/plugins/driveBrowserPlugin.ts

Lines changed: 114 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@ import { ITranslator } from '@jupyterlab/translation';
1414
import {
1515
createToolbarFactory,
1616
IToolbarWidgetRegistry,
17-
setToolbar
17+
setToolbar,
18+
showDialog,
19+
Dialog
1820
} from '@jupyterlab/apputils';
1921
import { ISettingRegistry } from '@jupyterlab/settingregistry';
2022
import { FilenameSearcher, IScore } from '@jupyterlab/ui-components';
2123
import { CommandRegistry } from '@lumino/commands';
24+
import { Widget } from '@lumino/widgets';
2225

2326
import { driveBrowserIcon } from '../icons';
2427
import { Drive } from '../contents';
@@ -35,6 +38,16 @@ const FILE_BROWSER_FACTORY = 'DriveBrowser';
3538
*/
3639
const FILTERBOX_CLASS = 'jp-drive-browser-search-box';
3740

41+
/**
42+
* The class name added to dialogs.
43+
*/
44+
const FILE_DIALOG_CLASS = 'jp-FileDialog';
45+
46+
/**
47+
* The class name added for the new drive label in the creating new drive dialog.
48+
*/
49+
const CREATE_DRIVE_TITLE_CLASS = 'jp-new-drive-title';
50+
3851
/**
3952
* The drives list provider.
4053
*/
@@ -184,6 +197,9 @@ export const driveFileBrowser: JupyterFrontEndPlugin<void> = {
184197

185198
// Listen for your plugin setting changes using Signal
186199
setting.changed.connect(loadSetting);
200+
201+
// Add commands
202+
Private.addCommands(app, drive);
187203
})
188204
.catch(reason => {
189205
console.error(
@@ -246,4 +262,101 @@ namespace Private {
246262
};
247263
router.routed.connect(listener);
248264
}
265+
266+
/**
267+
* Create the node for a creating a new drive handler.
268+
*/
269+
const createNewDriveNode = (newDriveName: string): HTMLElement => {
270+
const body = document.createElement('div');
271+
272+
const drive = document.createElement('label');
273+
drive.textContent = 'Name';
274+
drive.className = CREATE_DRIVE_TITLE_CLASS;
275+
const driveName = document.createElement('input');
276+
277+
const region = document.createElement('label');
278+
region.textContent = 'Region';
279+
region.className = CREATE_DRIVE_TITLE_CLASS;
280+
const regionName = document.createElement('input');
281+
regionName.placeholder = 'us-east-1';
282+
283+
body.appendChild(drive);
284+
body.appendChild(driveName);
285+
body.appendChild(region);
286+
body.appendChild(regionName);
287+
return body;
288+
};
289+
290+
/**
291+
* A widget used to create a new drive.
292+
*/
293+
export class CreateDriveHandler extends Widget {
294+
/**
295+
* Construct a new "create-drive" dialog.
296+
*/
297+
constructor(newDriveName: string) {
298+
super({ node: createNewDriveNode(newDriveName) });
299+
this.onAfterAttach();
300+
}
301+
302+
protected onAfterAttach(): void {
303+
this.addClass(FILE_DIALOG_CLASS);
304+
const drive = this.driveInput.value;
305+
this.driveInput.setSelectionRange(0, drive.length);
306+
const region = this.regionInput.value;
307+
this.regionInput.setSelectionRange(0, region.length);
308+
}
309+
310+
/**
311+
* Get the input text node for drive name.
312+
*/
313+
get driveInput(): HTMLInputElement {
314+
return this.node.getElementsByTagName('input')[0] as HTMLInputElement;
315+
}
316+
317+
/**
318+
* Get the input text node for region.
319+
*/
320+
get regionInput(): HTMLInputElement {
321+
return this.node.getElementsByTagName('input')[1] as HTMLInputElement;
322+
}
323+
324+
/**
325+
* Get the value of the widget.
326+
*/
327+
getValue(): string[] {
328+
return [this.driveInput.value, this.regionInput.value];
329+
}
330+
}
331+
332+
export function addCommands(app: JupyterFrontEnd, drive: Drive): void {
333+
app.commands.addCommand(CommandIDs.createNewDrive, {
334+
execute: async () => {
335+
return showDialog({
336+
title: 'New Drive',
337+
body: new Private.CreateDriveHandler(drive.name),
338+
focusNodeSelector: 'input',
339+
buttons: [
340+
Dialog.cancelButton(),
341+
Dialog.okButton({
342+
label: 'Create',
343+
ariaLabel: 'Create New Drive'
344+
})
345+
]
346+
}).then(result => {
347+
if (result.value) {
348+
drive.newDrive(result.value[0], result.value[1]);
349+
}
350+
});
351+
},
352+
label: 'New Drive',
353+
icon: driveBrowserIcon.bindprops({ stylesheet: 'menuItem' })
354+
});
355+
356+
app.contextMenu.addItem({
357+
command: CommandIDs.createNewDrive,
358+
selector: '#drive-file-browser.jp-SidePanel .jp-DirListing-content',
359+
rank: 100
360+
});
361+
}
249362
}

src/requests.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,39 @@ export const countObjectNameAppearances = async (
500500
return counter;
501501
};
502502

503+
/**
504+
* Create a new drive.
505+
*
506+
* @param newDriveName The new drive name.
507+
* @param options.location The region where drive should be located.
508+
*
509+
* @returns A promise which resolves with the contents model.
510+
*/
511+
export async function createDrive(
512+
newDriveName: string,
513+
options: {
514+
location: string;
515+
}
516+
) {
517+
await requestAPI<any>('drives/' + newDriveName + '/', 'POST', {
518+
location: options.location
519+
});
520+
521+
data = {
522+
name: newDriveName,
523+
path: newDriveName,
524+
last_modified: '',
525+
created: '',
526+
content: [],
527+
format: 'json',
528+
mimetype: '',
529+
size: 0,
530+
writable: true,
531+
type: 'directory'
532+
};
533+
return data;
534+
}
535+
503536
namespace Private {
504537
/**
505538
* Helping function for renaming files inside

src/token.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export namespace CommandIDs {
88
export const openDrivesDialog = 'drives:open-drives-dialog';
99
export const openPath = 'drives:open-path';
1010
export const toggleBrowser = 'drives:toggle-main';
11+
export const createNewDrive = 'drives:create-new-drive';
1112
export const launcher = 'launcher:create';
1213
}
1314

0 commit comments

Comments
 (0)