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
|
|
|
|
from bebop.page import Page
|
|
|
|
|
|
|
|
|
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
|
|
|
|
browser.load_page(Page.from_text(text))
|
|
|
|
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-03 17:14:32 +02:00
|
|
|
wrap_at = browser.config["text_width"]
|
|
|
|
browser.load_page(Page.from_gemtext(gemtext, wrap_at))
|
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
|