bunko 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. bunko/__init__.py +1 -0
  2. bunko/__main__.py +3 -0
  3. bunko/access.py +225 -0
  4. bunko/cli.py +231 -0
  5. bunko/contents.py +207 -0
  6. bunko/index.py +110 -0
  7. bunko/media.py +178 -0
  8. bunko/office/__init__.py +87 -0
  9. bunko/office/common.py +136 -0
  10. bunko/office/excel.py +322 -0
  11. bunko/office/word.py +615 -0
  12. bunko/paths.py +75 -0
  13. bunko/places.py +262 -0
  14. bunko/server.py +558 -0
  15. bunko/service.py +195 -0
  16. bunko/static/index.html +53 -0
  17. bunko/static/js/api.js +27 -0
  18. bunko/static/js/app.js +299 -0
  19. bunko/static/js/chrome.js +110 -0
  20. bunko/static/js/dom.js +66 -0
  21. bunko/static/js/format.js +44 -0
  22. bunko/static/js/icons.js +45 -0
  23. bunko/static/js/kinds.js +65 -0
  24. bunko/static/js/limits.js +11 -0
  25. bunko/static/js/paths.js +17 -0
  26. bunko/static/js/places.js +435 -0
  27. bunko/static/js/search.js +207 -0
  28. bunko/static/js/settings-panel.js +116 -0
  29. bunko/static/js/sidebar.js +39 -0
  30. bunko/static/js/state.js +16 -0
  31. bunko/static/js/store.js +29 -0
  32. bunko/static/js/tree.js +145 -0
  33. bunko/static/js/viewers/document.js +246 -0
  34. bunko/static/js/viewers/folder.js +185 -0
  35. bunko/static/js/viewers/media.js +228 -0
  36. bunko/static/js/viewers/page.js +64 -0
  37. bunko/static/js/viewers/table.js +415 -0
  38. bunko/static/js/viewers/text.js +117 -0
  39. bunko/static/style.css +1783 -0
  40. bunko/static/theme.js +7 -0
  41. bunko/static/vendor/LICENSES/dompurify-apache-2.0.txt +202 -0
  42. bunko/static/vendor/LICENSES/dompurify-mpl-2.0.txt +373 -0
  43. bunko/static/vendor/LICENSES/highlight.js.txt +29 -0
  44. bunko/static/vendor/LICENSES/marked.txt +44 -0
  45. bunko/static/vendor/VERSIONS.txt +3 -0
  46. bunko/static/vendor/highlight.js +1257 -0
  47. bunko/static/vendor/marked.js +85 -0
  48. bunko/static/vendor/purify.js +6 -0
  49. bunko/storage.py +31 -0
  50. bunko-0.3.0.dist-info/METADATA +169 -0
  51. bunko-0.3.0.dist-info/RECORD +60 -0
  52. bunko-0.3.0.dist-info/WHEEL +5 -0
  53. bunko-0.3.0.dist-info/entry_points.txt +2 -0
  54. bunko-0.3.0.dist-info/licenses/LICENSE +21 -0
  55. bunko-0.3.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +17 -0
  56. bunko-0.3.0.dist-info/licenses/bunko/static/vendor/LICENSES/dompurify-apache-2.0.txt +202 -0
  57. bunko-0.3.0.dist-info/licenses/bunko/static/vendor/LICENSES/dompurify-mpl-2.0.txt +373 -0
  58. bunko-0.3.0.dist-info/licenses/bunko/static/vendor/LICENSES/highlight.js.txt +29 -0
  59. bunko-0.3.0.dist-info/licenses/bunko/static/vendor/LICENSES/marked.txt +44 -0
  60. bunko-0.3.0.dist-info/top_level.txt +1 -0
bunko/index.py ADDED
@@ -0,0 +1,110 @@
1
+ """Search by name: every path under the root, kept in memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import heapq
6
+ import os
7
+ import threading
8
+ import time
9
+
10
+ from .paths import Root
11
+
12
+ FRESH_FOR = 120 # seconds before a search triggers a rebuild in the background
13
+ MAX_PATHS = 2_000_000
14
+ MAX_RESULTS = 100
15
+ SKIP_DIRS = frozenset({"node_modules", "__pycache__", "site-packages", "venv"})
16
+
17
+
18
+ class SearchIndex:
19
+ """A list of (path, lowercased path), rebuilt in the background when stale.
20
+
21
+ Folders end in "/". During the first build the list fills in place, so
22
+ searches work before the walk finishes.
23
+ """
24
+
25
+ def __init__(self, root: Root):
26
+ self.root = root
27
+ self.lock = threading.Lock()
28
+ self.paths: list = []
29
+ self.building = False
30
+ self.built_at = 0.0
31
+ self.truncated = False
32
+
33
+ def refresh(self) -> None:
34
+ """Start a rebuild if the index is stale and none is running."""
35
+ with self.lock:
36
+ if self.building or time.time() - self.built_at < FRESH_FOR:
37
+ return
38
+ self.building = True
39
+ threading.Thread(target=self._build, daemon=True).start()
40
+
41
+ def status(self) -> dict:
42
+ self.refresh()
43
+ return {"indexed": len(self.paths), "indexing": self.building, "truncated": self.truncated}
44
+
45
+ def search(self, query: str) -> list:
46
+ """Paths containing every word of the query, best name matches first."""
47
+ tokens = query.lower().split()
48
+ if not tokens:
49
+ return []
50
+ self.refresh()
51
+ last = tokens[-1]
52
+ hits = []
53
+ for order, (path, lowered) in enumerate(list(self.paths)):
54
+ if all(token in lowered for token in tokens):
55
+ name = lowered.rstrip("/").rsplit("/", 1)[-1]
56
+ hits.append((_rank(name, last), len(path), order, path))
57
+ return [hit[3] for hit in heapq.nsmallest(MAX_RESULTS, hits)]
58
+
59
+ def _build(self) -> None:
60
+ found: list = []
61
+ if not self.built_at:
62
+ self.paths = found
63
+ try:
64
+ self.truncated = self._walk(found)
65
+ finally:
66
+ self.paths = found
67
+ self.built_at = time.time()
68
+ self.building = False
69
+
70
+ def _walk(self, found: list) -> bool:
71
+ """Fill `found`; return True if it stopped at MAX_PATHS."""
72
+ seen = {self.root.real}
73
+ stack = [(self.root.real, "")]
74
+ while stack:
75
+ real, rel = stack.pop()
76
+ try:
77
+ entries = list(os.scandir(real))
78
+ except OSError:
79
+ continue
80
+ for entry in entries:
81
+ if not self.root.visible(entry.name):
82
+ continue
83
+ try:
84
+ is_dir = entry.is_dir()
85
+ except OSError:
86
+ continue
87
+ target = entry.path
88
+ if entry.is_symlink():
89
+ target = os.path.realpath(entry.path)
90
+ if not self.root.allowed_target(target):
91
+ continue
92
+ if len(found) >= MAX_PATHS:
93
+ return True
94
+ child = rel + entry.name
95
+ if not is_dir:
96
+ found.append((child, child.lower()))
97
+ continue
98
+ found.append((child + "/", child.lower()))
99
+ if entry.name not in SKIP_DIRS and target not in seen:
100
+ seen.add(target) # also stops symlink loops
101
+ stack.append((target, child + "/"))
102
+ return False
103
+
104
+
105
+ def _rank(name: str, word: str) -> int:
106
+ if name == word:
107
+ return 0
108
+ if name.startswith(word):
109
+ return 1
110
+ return 2 if word in name else 3
bunko/media.py ADDED
@@ -0,0 +1,178 @@
1
+ """Thumbnails and video metadata, using ffmpeg and ffprobe when installed.
2
+
3
+ Both are optional. Without ffmpeg the gallery falls back to full-size images
4
+ and generic video icons; without ffprobe the video tools estimate frame rate in
5
+ the browser.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ import threading
16
+ from collections import OrderedDict
17
+
18
+ from .storage import cache_dir
19
+
20
+ IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".avif", ".tif", ".tiff"}
21
+ VIDEO_EXTS = {".mp4", ".webm", ".mov", ".m4v", ".mkv", ".avi", ".ogv"}
22
+ SMALL_IMAGE = 96 * 1024 # serve these as they are: a thumbnail would barely help
23
+ THUMB_WIDTH = 360
24
+ TIMEOUT = 30
25
+ PROBE_CACHE = 2000 # videos remembered by the prober
26
+
27
+
28
+ def kind_of(path: str) -> str | None:
29
+ ext = os.path.splitext(path)[1].lower()
30
+ if ext in IMAGE_EXTS:
31
+ return "image"
32
+ if ext in VIDEO_EXTS:
33
+ return "video"
34
+ return None
35
+
36
+
37
+ def file_url(real: str) -> str:
38
+ # The file: prefix stops ffmpeg reading a name like "-i" or "http:x" as
39
+ # an option or a network address.
40
+ return "file:" + real
41
+
42
+
43
+ class Thumbnails:
44
+ """Small JPEGs of large images and of video frames, cached on disk by content."""
45
+
46
+ def __init__(self, directory: str | None = None, enabled: bool = True):
47
+ self.ffmpeg = shutil.which("ffmpeg") if enabled else None
48
+ self.directory = os.path.join(directory or cache_dir(), "thumbs")
49
+ # A gallery asks for dozens at once; this keeps ffmpeg from swamping the box.
50
+ self.slots = threading.BoundedSemaphore(max(2, min(4, (os.cpu_count() or 2) // 2)))
51
+
52
+ @property
53
+ def available(self) -> bool:
54
+ return self.ffmpeg is not None
55
+
56
+ def key(self, real: str, info: os.stat_result) -> str:
57
+ raw = f"{real}\0{info.st_mtime_ns}\0{info.st_size}\0{THUMB_WIDTH}"
58
+ return hashlib.sha1(raw.encode("utf-8", "surrogateescape")).hexdigest()
59
+
60
+ def get(self, real: str):
61
+ """(path to send, is_original), or None when there's no thumbnail."""
62
+ kind = kind_of(real)
63
+ if kind is None:
64
+ return None
65
+ info = os.stat(real)
66
+ if kind == "image" and info.st_size <= SMALL_IMAGE:
67
+ return real, True
68
+ if not self.available:
69
+ return None
70
+ key = self.key(real, info)
71
+ folder = os.path.join(self.directory, key[:2])
72
+ out = os.path.join(folder, key + ".jpg")
73
+ failed = os.path.join(folder, key + ".fail")
74
+ if os.path.exists(out):
75
+ return out, False
76
+ if os.path.exists(failed):
77
+ return None
78
+ with self.slots:
79
+ if os.path.exists(out): # another request made it while we waited
80
+ return out, False
81
+ os.makedirs(folder, exist_ok=True)
82
+ temp = f"{out}.{os.getpid()}.{threading.get_ident()}.jpg"
83
+ # A video's first frame is often black, so try one second in first.
84
+ seeks = ("1", "0") if kind == "video" else (None,)
85
+ for seek in seeks:
86
+ if self._run(real, temp, seek) and os.path.getsize(temp) > 0:
87
+ os.replace(temp, out)
88
+ return out, False
89
+ if os.path.exists(temp):
90
+ os.remove(temp)
91
+ with open(failed, "w"):
92
+ pass # remembered, so a file ffmpeg can't read isn't retried on every view
93
+ return None
94
+
95
+ def _run(self, real: str, out: str, seek: str | None) -> bool:
96
+ command = [self.ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", "-y"]
97
+ if seek:
98
+ command += ["-ss", seek]
99
+ command += [
100
+ "-i",
101
+ file_url(real),
102
+ "-frames:v",
103
+ "1",
104
+ "-vf",
105
+ f"scale=w='min({THUMB_WIDTH},iw)':h=-2",
106
+ "-q:v",
107
+ "5",
108
+ out,
109
+ ]
110
+ try:
111
+ done = subprocess.run(
112
+ command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=TIMEOUT
113
+ )
114
+ except (OSError, subprocess.TimeoutExpired):
115
+ return False
116
+ return done.returncode == 0 and os.path.exists(out)
117
+
118
+
119
+ class Prober:
120
+ """Video facts for the review tools: frame rate, duration, codec."""
121
+
122
+ def __init__(self, enabled: bool = True):
123
+ self.ffprobe = shutil.which("ffprobe") if enabled else None
124
+ self.cache: OrderedDict = OrderedDict()
125
+ self.lock = threading.Lock()
126
+
127
+ def probe(self, real: str) -> dict | None:
128
+ if not self.ffprobe:
129
+ return None
130
+ info = os.stat(real)
131
+ key = (real, info.st_mtime_ns, info.st_size)
132
+ with self.lock:
133
+ if key in self.cache:
134
+ self.cache.move_to_end(key)
135
+ return self.cache[key]
136
+ command = [
137
+ self.ffprobe,
138
+ "-v",
139
+ "error",
140
+ "-select_streams",
141
+ "v:0",
142
+ "-show_entries",
143
+ "stream=codec_name,width,height,avg_frame_rate,r_frame_rate,nb_frames:format=duration",
144
+ "-of",
145
+ "json",
146
+ file_url(real),
147
+ ]
148
+ try:
149
+ done = subprocess.run(command, capture_output=True, timeout=TIMEOUT)
150
+ data = json.loads(done.stdout or b"{}")
151
+ except (OSError, subprocess.TimeoutExpired, ValueError):
152
+ return None
153
+ stream = (data.get("streams") or [{}])[0]
154
+ result = {
155
+ "codec": stream.get("codec_name"),
156
+ "width": stream.get("width"),
157
+ "height": stream.get("height"),
158
+ "fps": self._rate(stream.get("avg_frame_rate"))
159
+ or self._rate(stream.get("r_frame_rate")),
160
+ "frames": int(stream["nb_frames"])
161
+ if str(stream.get("nb_frames", "")).isdigit()
162
+ else None,
163
+ "duration": float(data.get("format", {}).get("duration") or 0) or None,
164
+ }
165
+ with self.lock:
166
+ self.cache[key] = result
167
+ while len(self.cache) > PROBE_CACHE:
168
+ self.cache.popitem(last=False)
169
+ return result
170
+
171
+ @staticmethod
172
+ def _rate(text) -> float | None:
173
+ try:
174
+ top, bottom = str(text).split("/")
175
+ value = float(top) / float(bottom)
176
+ except (ValueError, ZeroDivisionError):
177
+ return None
178
+ return round(value, 3) if 0 < value < 1000 else None
@@ -0,0 +1,87 @@
1
+ """Word and Excel files, converted with the standard library for the viewer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import xml.etree.ElementTree as ET
7
+ import zipfile
8
+
9
+ from .common import OfficeError
10
+ from .excel import xlsx_sheet
11
+ from .word import docx_image, docx_page
12
+
13
+ __all__ = ["Office", "OfficeError", "docx_image", "docx_page", "kind_of", "xlsx_sheet"]
14
+
15
+ WORD_EXTS = {"docx", "docm", "dotx", "dotm"}
16
+ EXCEL_EXTS = {"xlsx", "xlsm", "xltx", "xltm"}
17
+
18
+
19
+ def kind_of(path: str) -> str | None:
20
+ """ "docx", "xlsx", or None, from the file's extension."""
21
+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
22
+ return "docx" if ext in WORD_EXTS else "xlsx" if ext in EXCEL_EXTS else None
23
+
24
+
25
+ class Office:
26
+ """Converts files for the API, remembering the last few results."""
27
+
28
+ KEEP = 8
29
+
30
+ def __init__(self):
31
+ self.lock = threading.Lock()
32
+ self.cache = {} # (real, sheet) -> (mtime, size, result)
33
+
34
+ def read(self, real: str, mtime: float, size: int, sheet=None) -> dict:
35
+ kind = kind_of(real)
36
+ if kind is None:
37
+ raise OfficeError("Not a Word or Excel file.")
38
+ key = (real, sheet if kind == "xlsx" else None)
39
+ with self.lock:
40
+ hit = self.cache.get(key)
41
+ if hit and hit[:2] == (mtime, size):
42
+ return hit[2]
43
+ with _errors():
44
+ result = docx_page(real) if kind == "docx" else xlsx_sheet(real, sheet)
45
+ result = dict(result, type=kind)
46
+ with self.lock:
47
+ self.cache[key] = (mtime, size, result)
48
+ while len(self.cache) > self.KEEP:
49
+ self.cache.pop(next(iter(self.cache)))
50
+ return result
51
+
52
+ def image(self, real: str, part: str):
53
+ if kind_of(real) != "docx":
54
+ raise OfficeError("Not a Word file.")
55
+ with _errors():
56
+ return docx_image(real, part)
57
+
58
+
59
+ class _errors:
60
+ """Turns the ways a damaged file fails into an OfficeError."""
61
+
62
+ def __enter__(self):
63
+ return self
64
+
65
+ def __exit__(self, kind, error, trace):
66
+ if kind is None or issubclass(kind, OfficeError):
67
+ return False
68
+ if issubclass(kind, ET.ParseError):
69
+ raise OfficeError("This file's XML is damaged, so it can't be shown.") from error
70
+ if issubclass(
71
+ kind,
72
+ (
73
+ zipfile.BadZipFile,
74
+ zipfile.LargeZipFile,
75
+ KeyError,
76
+ EOFError,
77
+ OSError,
78
+ RuntimeError,
79
+ NotImplementedError,
80
+ ValueError,
81
+ IndexError,
82
+ ),
83
+ ):
84
+ raise OfficeError(
85
+ "This file couldn't be read. It may be damaged or encrypted."
86
+ ) from error
87
+ return False
bunko/office/common.py ADDED
@@ -0,0 +1,136 @@
1
+ """Reading the zip and XML inside Office files, treating them as untrusted.
2
+
3
+ XML with a DOCTYPE is refused (Office never writes one, and that's where entity
4
+ bombs live), and every part is read with a size cap, however large the zip
5
+ claims it is.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import posixpath
11
+ import xml.etree.ElementTree as ET
12
+ import zipfile
13
+
14
+ PART_MAX = 64 * 1024 * 1024 # most XML read from one part of a document
15
+ REL_NAMESPACES = (
16
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
17
+ "http://purl.oclc.org/ooxml/officeDocument/relationships", # "Strict" files
18
+ )
19
+
20
+
21
+ class OfficeError(ValueError):
22
+ """A file that can't be shown, with a message for the user."""
23
+
24
+
25
+ def plain_name(key: str) -> str:
26
+ """Drop the namespace, keeping r: on relationship attributes (r:id, r:embed)."""
27
+ if key[:1] != "{":
28
+ return key
29
+ namespace, _, local = key[1:].partition("}")
30
+ return "r:" + local if namespace in REL_NAMESPACES else local
31
+
32
+
33
+ def refuse_doctype(*_):
34
+ raise OfficeError("This file contains XML that Office doesn't write (a DOCTYPE).")
35
+
36
+
37
+ class PlainTree(ET.TreeBuilder):
38
+ """Builds elements with plain names, so <w:p> is just "p"."""
39
+
40
+ def start(self, tag, attrs):
41
+ return super().start(
42
+ plain_name(tag), {plain_name(key): value for key, value in attrs.items()}
43
+ )
44
+
45
+ def end(self, tag):
46
+ return super().end(plain_name(tag))
47
+
48
+ doctype = staticmethod(refuse_doctype)
49
+
50
+
51
+ class CappedReader:
52
+ """A file-like reader that fails once more than `cap` bytes have been read."""
53
+
54
+ def __init__(self, handle, cap: int, part: str):
55
+ self.handle, self.left, self.part = handle, cap, part
56
+
57
+ def read(self, size: int) -> bytes:
58
+ chunk = self.handle.read(min(size, self.left + 1))
59
+ self.left -= len(chunk)
60
+ if self.left < 0:
61
+ raise OfficeError(f"Part of this file ({self.part}) is too large to show.")
62
+ return chunk
63
+
64
+
65
+ def feed(archive: zipfile.ZipFile, part: str, target, cap: int):
66
+ parser = ET.XMLParser(target=target)
67
+ with archive.open(part) as handle:
68
+ source = CappedReader(handle, cap, part)
69
+ while True:
70
+ chunk = source.read(1 << 20)
71
+ if not chunk:
72
+ break
73
+ parser.feed(chunk)
74
+ return parser.close()
75
+
76
+
77
+ def parse_part(archive: zipfile.ZipFile, part: str):
78
+ """The part as an element tree, or None if the file doesn't have it."""
79
+ if part not in archive.NameToInfo:
80
+ return None
81
+ return feed(archive, part, PlainTree(), PART_MAX)
82
+
83
+
84
+ def open_package(real: str) -> zipfile.ZipFile:
85
+ try:
86
+ return zipfile.ZipFile(real)
87
+ except (zipfile.BadZipFile, OSError):
88
+ raise OfficeError(
89
+ "This isn't a valid Office file. It may be damaged, password-protected, "
90
+ "or an older format saved with a newer extension."
91
+ ) from None
92
+
93
+
94
+ def relationships(archive: zipfile.ZipFile, part: str) -> dict:
95
+ """A part's relationships: id -> (target, external)."""
96
+ folder, name = posixpath.split(part)
97
+ tree = parse_part(archive, posixpath.join(folder, "_rels", name + ".rels"))
98
+ out = {}
99
+ for rel in tree.iter("Relationship") if tree is not None else ():
100
+ target = rel.get("Target", "")
101
+ external = rel.get("TargetMode") == "External"
102
+ if not external:
103
+ # Targets are relative to the part's folder, or to the package root with a leading slash.
104
+ joined = target[1:] if target.startswith("/") else posixpath.join(folder, target)
105
+ target = posixpath.normpath(joined)
106
+ out[rel.get("Id")] = (target, external)
107
+ return out
108
+
109
+
110
+ def toggled(element) -> bool:
111
+ """A Word toggle such as <w:b/>, which w:val="0" or "false" turns off."""
112
+ return element is not None and element.get("val", "true").lower() not in (
113
+ "0",
114
+ "false",
115
+ "off",
116
+ "none",
117
+ )
118
+
119
+
120
+ def find_child(element, name):
121
+ return element.find(name) if element is not None else None
122
+
123
+
124
+ def child_val(element, name, default=None):
125
+ found = find_child(element, name)
126
+ return found.get("val", default) if found is not None else default
127
+
128
+
129
+ def letters(index: int) -> str:
130
+ """0 -> A, 25 -> Z, 26 -> AA: Excel's column names, and Word's lettered lists."""
131
+ text = ""
132
+ index += 1
133
+ while index:
134
+ index, rest = divmod(index - 1, 26)
135
+ text = chr(65 + rest) + text
136
+ return text