Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Intercept webbrowser open requests for local html files as well as localhost #4178

Merged
merged 4 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions extensions/positron-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ pyright
Install the test requirements that are used in CI:

```sh
pip install -r ../build/pinned-test-requirements.txt
pip install -r python_files/positron/pinned-test-requirements.txt
```

Run Positron's unit tests with [pytest](https://docs.pytest.org/en/8.0.x/):

```sh
pytest python_files/positron/
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious, did pytest not work for you?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was trying to use a different python version than which python was giving me. Wasim suggested this change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking was that python -m pytest should work in all cases where pytest works, and more. So it'll probably save folks some headaches.

python -m pytest python_files/positron/
```
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ def show_url_event(url: str) -> Dict[str, Any]:
return json_rpc_notification("show_url", {"url": url})


def show_html_file_event(path: str, is_plot: bool) -> Dict[str, Any]:
return json_rpc_notification("show_html_file", {"path": path, "is_plot": is_plot})


def test_comm_open(ui_service: UiService) -> None:
# Double-check that comm is not yet open
assert ui_service._comm is None
Expand Down Expand Up @@ -149,7 +153,24 @@ def test_shutdown(ui_service: UiService, ui_comm: DummyComm) -> None:

@pytest.mark.parametrize(
("url", "expected"),
[("https://google.com", []), ("localhost:8000", [show_url_event("localhost:8000")])],
[
("https://google.com", []),
("localhost:8000", [show_url_event("localhost:8000")]),
# Unix path
(
"file://hello/my/friend.html",
[show_html_file_event("file://hello/my/friend.html", False)],
),
# Windows path
(
"file:///C:/Users/username/Documents/index.htm",
[show_html_file_event("file:///C:/Users/username/Documents/index.htm", False)],
),
# Not a local html file
("http://example.com/page.html", []),
# Not an html file
("file:///C:/Users/username/Documents/file.txt", []),
],
)
def test_viewer_webbrowser_does_not_open(
url, expected, shell: PositronShell, ui_comm: DummyComm, ui_service: UiService
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
UiFrontendEvent,
WorkingDirectoryParams,
)
from .utils import JsonData, JsonRecord, alias_home
from .utils import JsonData, JsonRecord, alias_home, is_local_html_file

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -179,6 +179,18 @@ def open(self, url, new=0, autoraise=True):
if not self._comm:
return False

# If url is pointing to an HTML file, route to the ShowHtmlFile comm
if is_local_html_file(url):
self._comm.send_event(
name=UiFrontendEvent.ShowHtmlFile,
payload={
"path": url,
# TODO: Figure out if the file being displayed is a plot or not.
"is_plot": False,
},
)
return True

for addr in _localhosts:
if addr in url:
event = ShowUrlParams(url=url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
Union,
cast,
)
from urllib.parse import urlparse, unquote

JsonData = Union[Dict[str, "JsonData"], List["JsonData"], str, int, float, bool, None]
JsonRecord = Dict[str, JsonData]
Expand Down Expand Up @@ -384,3 +385,23 @@ def positron_ipykernel_usage():
"numpy.cdouble",
"numpy.clongdouble",
]


def is_local_html_file(url: str) -> bool:
"""Check if a URL points to a local HTML file."""
try:
parsed_url = urlparse(unquote(url))

# Check if it's a file scheme
if parsed_url.scheme not in ("file"):
return False

# Check if the path contains the .html or .htm extensions
path = parsed_url.path.lower()
if any(ext in path for ext in (".html", ".htm")):
return True

return False

except Exception:
return False
Loading