From b8928e4f46f006959f1052a66b666239e40a4208 Mon Sep 17 00:00:00 2001 From: YuviPanda Date: Wed, 9 Jun 2021 04:00:21 +0530 Subject: [PATCH] Mimic classic notebook behavior for /tree/ - Show directory listing if path is a directory - Show notebook if path is a notebook - Return file contents if path is any other file Copied from https://github.com/jupyter/notebook/blob/6fe9755971dba3357054766806d56cb8c6c1bca7/notebook/tree/handlers.py#L39 Fixes https://github.com/jupyterlab/retrolab/issues/153 --- retrolab/app.py | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/retrolab/app.py b/retrolab/app.py index ac9d0ad2..6d276650 100644 --- a/retrolab/app.py +++ b/retrolab/app.py @@ -8,13 +8,14 @@ ExtensionHandlerMixin, ExtensionHandlerJinjaMixin, ) -from jupyter_server.utils import url_path_join as ujoin +from jupyter_server.utils import url_path_join as ujoin, url_escape from jupyterlab.commands import get_app_dir, get_user_settings_dir, get_workspaces_dir from jupyterlab_server import LabServerApp from jupyterlab_server.config import get_page_config, recursive_update, LabConfig from jupyterlab_server.handlers import is_url, _camelCase from nbclassic.shim import NBClassicConfigShimMixin from tornado import web +from tornado.gen import maybe_future from traitlets import Bool from ._version import __version__ @@ -98,9 +99,35 @@ def get(self): class RetroTreeHandler(RetroHandler): @web.authenticated - def get(self, path=None): - tpl = self.render_template("tree.html", page_config=self.get_page_config()) - return self.write(tpl) + async def get(self, path=None): + """ + Display appropriate page for given path. + + - A directory listing is shown if path is a directory + - Redirected to notebook page if path is a notebook + - Render the raw file if path is any other file + """ + path = path.strip('/') + cm = self.contents_manager + + if await maybe_future(cm.dir_exists(path=path)): + if await maybe_future(cm.is_hidden(path)) and not cm.allow_hidden: + self.log.info("Refusing to serve hidden directory, via 404 Error") + raise web.HTTPError(404) + tpl = self.render_template("tree.html", page_config=self.get_page_config()) + return self.write(tpl) + elif await maybe_future(cm.file_exists(path)): + # it's not a directory, we have redirecting to do + model = await maybe_future(cm.get(path, content=False)) + if model['type'] == 'notebook': + url = ujoin(self.base_url, 'retro/notebooks', url_escape(path)) + else: + # Return raw content if file is not a notebook + url = ujoin(self.base_url, 'files', url_escape(path)) + self.log.debug("Redirecting %s to %s", self.request.path, url) + self.redirect(url) + else: + raise web.HTTPError(404) class RetroTerminalHandler(RetroHandler):