|
| 1 | +############################################################################# |
| 2 | +# Copyright (c) 2018, Voilà Contributors # |
| 3 | +# Copyright (c) 2018, QuantStack # |
| 4 | +# # |
| 5 | +# Distributed under the terms of the BSD 3-Clause License. # |
| 6 | +# # |
| 7 | +# The full license is in the file LICENSE, distributed with this software. # |
| 8 | +############################################################################# |
| 9 | +import os |
| 10 | + |
| 11 | +from jupyter_server.utils import url_escape, url_path_join |
| 12 | +from nbclient.util import ensure_async |
| 13 | +from tornado import web |
| 14 | + |
| 15 | +from ..treehandler import VoilaTreeHandler |
| 16 | +from ..utils import get_server_root_dir |
| 17 | + |
| 18 | + |
| 19 | +class TornadoVoilaTreeHandler(VoilaTreeHandler): |
| 20 | + @web.authenticated |
| 21 | + async def get(self, path=""): |
| 22 | + cm = self.contents_manager |
| 23 | + dir_exists = await ensure_async(cm.dir_exists(path=path)) |
| 24 | + file_exists = await ensure_async(cm.file_exists(path)) |
| 25 | + if dir_exists: |
| 26 | + is_hidden = await ensure_async(cm.is_hidden(path)) |
| 27 | + if is_hidden and not cm.allow_hidden: |
| 28 | + self.log.info("Refusing to serve hidden directory, via 404 Error") |
| 29 | + raise web.HTTPError(404) |
| 30 | + breadcrumbs = self.generate_breadcrumbs(path) |
| 31 | + page_title = self.generate_page_title(path) |
| 32 | + contents = await ensure_async(cm.get(path)) |
| 33 | + |
| 34 | + def allowed_content(content): |
| 35 | + if content["type"] in ["directory", "notebook"]: |
| 36 | + return True |
| 37 | + __, ext = os.path.splitext(content.get("path")) |
| 38 | + return ext in self.allowed_extensions |
| 39 | + |
| 40 | + contents["content"] = sorted(contents["content"], key=lambda i: i["name"]) |
| 41 | + contents["content"] = filter(allowed_content, contents["content"]) |
| 42 | + |
| 43 | + self.write( |
| 44 | + self.render_template( |
| 45 | + "tree.html", |
| 46 | + frontend="voila", |
| 47 | + main_js="voila.js", |
| 48 | + page_title=page_title, |
| 49 | + notebook_path=path, |
| 50 | + breadcrumbs=breadcrumbs, |
| 51 | + contents=contents, |
| 52 | + terminals_available=False, |
| 53 | + server_root=get_server_root_dir(self.settings), |
| 54 | + query=self.request.query, |
| 55 | + ) |
| 56 | + ) |
| 57 | + elif file_exists: |
| 58 | + # it's not a directory, we have redirecting to do |
| 59 | + model = await ensure_async(cm.get(path, content=False)) |
| 60 | + # redirect to /api/notebooks if it's a notebook, otherwise /api/files |
| 61 | + service = "notebooks" if model["type"] == "notebook" else "files" |
| 62 | + url = url_path_join( |
| 63 | + self.base_url, |
| 64 | + service, |
| 65 | + url_escape(path), |
| 66 | + ) |
| 67 | + self.log.debug("Redirecting %s to %s", self.request.path, url) |
| 68 | + self.redirect(url) |
| 69 | + else: |
| 70 | + raise web.HTTPError(404) |
0 commit comments