2021-03-28 18:28:35 +02:00
|
|
|
"""Local files browser."""
|
|
|
|
|
2021-06-03 17:14:32 +02:00
|
|
|
import logging
|
|
|
|
from pathlib import Path
|
2021-06-03 21:47:28 +02:00
|
|
|
from urllib.parse import quote, unquote
|
2021-06-03 17:14:32 +02:00
|
|
|
|
2021-03-28 18:28:35 +02:00
|
|
|
from bebop.browser.browser import Browser
|
2021-06-28 00:49:44 +02:00
|
|
|
from bebop.page import Page, get_render_options
|
2021-03-28 18:28:35 +02:00
|
|
|
|
|
|
|
|
2021-05-08 22:41:42 +02:00
|
|
|
def open_file(browser: Browser, filepath: str, encoding="utf-8"):
|
2021-03-28 18:28:35 +02:00
|
|
|
"""Open a file and render it.
|
|
|
|
|
2021-06-03 21:47:28 +02:00
|
|
|
This should be used only text files or directories. Anything else will
|
|
|
|
produce garbage and may crash the program. In the future this should be able
|
|
|
|
to use a different parser according to a MIME type or something.
|
2021-05-08 22:41:42 +02:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
- browser: Browser object making the request.
|
|
|
|
- filepath: a text file path on disk.
|
|
|
|
- encoding: file's encoding.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The loaded file URI on success, None otherwise (e.g. file not found).
|
2021-03-28 18:28:35 +02:00
|
|
|
"""
|
2021-06-03 21:47:28 +02:00
|
|
|
path = Path(unquote(filepath))
|
2021-06-03 17:14:32 +02:00
|
|
|
if not path.exists():
|
2021-06-03 21:47:28 +02:00
|
|
|
logging.error(f"File {path} does not exist.")
|
2021-05-08 22:41:42 +02:00
|
|
|
return None
|
2021-06-03 17:14:32 +02:00
|
|
|
|
|
|
|
if path.is_file():
|
|
|
|
try:
|
2021-06-03 21:47:28 +02:00
|
|
|
with open(path, "rt", encoding=encoding) as f:
|
2021-06-03 17:14:32 +02:00
|
|
|
text = f.read()
|
|
|
|
except (OSError, ValueError) as exc:
|
|
|
|
browser.set_status_error(f"Failed to open file: {exc}")
|
|
|
|
return None
|
2021-06-18 01:44:48 +02:00
|
|
|
if path.suffix == ".gmi":
|
2021-06-28 00:49:44 +02:00
|
|
|
page = Page.from_gemtext(text, get_render_options(browser.config))
|
2021-06-18 01:44:48 +02:00
|
|
|
else:
|
|
|
|
page = Page.from_text(text)
|
|
|
|
browser.load_page(page)
|
2021-06-03 17:14:32 +02:00
|
|
|
elif path.is_dir():
|
2021-06-03 21:47:28 +02:00
|
|
|
gemtext = str(path) + "\n\n"
|
2021-06-03 17:14:32 +02:00
|
|
|
for entry in sorted(path.iterdir()):
|
2021-06-03 21:47:28 +02:00
|
|
|
entry_path = quote(str(entry.absolute()))
|
2021-06-03 17:14:32 +02:00
|
|
|
name = entry.name
|
|
|
|
if entry.is_dir():
|
|
|
|
name += "/"
|
2021-06-03 21:47:28 +02:00
|
|
|
gemtext += f"=> {entry_path} {name}\n"
|
2021-06-28 00:49:44 +02:00
|
|
|
render_opts = get_render_options(browser.config)
|
|
|
|
browser.load_page(Page.from_gemtext(gemtext, render_opts))
|
2021-06-03 21:47:28 +02:00
|
|
|
file_url = f"file://{path}"
|
2021-03-28 18:28:35 +02:00
|
|
|
browser.current_url = file_url
|
2021-05-08 22:41:42 +02:00
|
|
|
return file_url
|