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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
bunko/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
bunko/access.py ADDED
@@ -0,0 +1,225 @@
1
+ """Who may use the server.
2
+
3
+ Three modes:
4
+
5
+ - open: anyone who can reach the port. The default, as with http.server.
6
+ - tailscale: only named Tailscale users. Bunko listens on loopback behind
7
+ `tailscale serve`, which strips any identity headers a client sends and adds
8
+ the real Tailscale-User-Login. This is the recommended mode.
9
+ - token: anyone holding a secret token. The token arrives once in the URL, then
10
+ lives in a cookie. Weaker: it's a shared secret, and plain HTTP exposes it to
11
+ anyone who can watch the network.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import fnmatch
17
+ import hashlib
18
+ import hmac
19
+ import ipaddress
20
+ import os
21
+ import secrets
22
+ from contextlib import suppress
23
+ from dataclasses import dataclass
24
+ from email.header import decode_header
25
+ from http.cookies import CookieError, SimpleCookie
26
+ from urllib.parse import urlencode
27
+
28
+ from .storage import config_dir, write_private
29
+
30
+ IDENTITY_HEADER = "Tailscale-User-Login"
31
+ NAME_HEADER = "Tailscale-User-Name"
32
+ COOKIE_AGE = 365 * 24 * 3600
33
+
34
+
35
+ def default_token_path() -> str:
36
+ return os.path.join(config_dir(), "token")
37
+
38
+
39
+ def is_loopback(host: str) -> bool:
40
+ if host == "localhost":
41
+ return True
42
+ try:
43
+ return ipaddress.ip_address(host).is_loopback
44
+ except ValueError:
45
+ return False
46
+
47
+
48
+ def decode_rfc2047(value: str) -> str:
49
+ """Tailscale may send non-ASCII names as =?utf-8?q?...?=."""
50
+ try:
51
+ parts = decode_header(value)
52
+ except (ValueError, LookupError):
53
+ return value
54
+ return "".join(
55
+ part.decode(charset or "utf-8", "replace") if isinstance(part, bytes) else part
56
+ for part, charset in parts
57
+ )
58
+
59
+
60
+ class TokenStore:
61
+ """The token file, re-read when it changes so rotation needs no restart."""
62
+
63
+ def __init__(self, path: str | None = None):
64
+ self.env = os.environ.get("BUNKO_TOKEN") or None
65
+ self.path = path or default_token_path()
66
+ self._seen = None
67
+ self._token = None
68
+
69
+ def describe(self) -> str:
70
+ return "the BUNKO_TOKEN environment variable" if self.env else self.path
71
+
72
+ def ensure(self) -> str:
73
+ """Return the token, creating the file on first use."""
74
+ if self.env:
75
+ return self.env
76
+ if not os.path.exists(self.path):
77
+ return self.rotate()
78
+ return self.current()
79
+
80
+ def rotate(self) -> str:
81
+ if self.env:
82
+ raise SystemExit("bunko: the token comes from BUNKO_TOKEN; change it there")
83
+ token = secrets.token_urlsafe(24)
84
+ write_private(self.path, token + "\n")
85
+ return token
86
+
87
+ def current(self) -> str | None:
88
+ if self.env:
89
+ return self.env
90
+ try:
91
+ info = os.stat(self.path)
92
+ except OSError:
93
+ return None
94
+ stamp = (info.st_mtime_ns, info.st_size)
95
+ if stamp != self._seen:
96
+ with open(self.path) as handle:
97
+ self._token = handle.read().strip() or None
98
+ self._seen = stamp
99
+ return self._token
100
+
101
+
102
+ @dataclass
103
+ class Decision:
104
+ """The answer to "may this request go ahead?", and what to send with it."""
105
+
106
+ allowed: bool
107
+ user: str | None = None # display name, shown in the app
108
+ reason: str = "" # why not, when refused
109
+ login: str | None = None # Tailscale login, which keys per-person state
110
+ cookie: str | None = None # a Set-Cookie value to send
111
+ clean_url: str | None = None # redirect here to drop ?token= from the address bar
112
+
113
+
114
+ class Access:
115
+ """The access mode in force, and the check every request goes through."""
116
+
117
+ def __init__(
118
+ self, mode: str = "open", port: int = 0, tokens: TokenStore | None = None, users=()
119
+ ):
120
+ self.mode = mode
121
+ self.port = port
122
+ self.tokens = tokens
123
+ self.users = [user.lower() for user in users]
124
+
125
+ # -- token helpers ---------------------------------------------------
126
+
127
+ @property
128
+ def cookie_name(self) -> str:
129
+ # Cookies are shared by every port on a host, so name ours by port.
130
+ return f"bunko_{self.port}"
131
+
132
+ def session_value(self, token: str) -> str:
133
+ # The cookie holds a derivative, so the raw token never sits in it.
134
+ return hmac.new(token.encode(), b"bunko-session-v1", hashlib.sha256).hexdigest()
135
+
136
+ def session_cookie(self, token: str) -> str:
137
+ value = self.session_value(token)
138
+ return f"{self.cookie_name}={value}; Path=/; Max-Age={COOKIE_AGE}; HttpOnly; SameSite=Lax"
139
+
140
+ def logout_cookie(self) -> str:
141
+ return f"{self.cookie_name}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax"
142
+
143
+ def user_allowed(self, login: str) -> bool:
144
+ login = login.lower()
145
+ return any(fnmatch.fnmatchcase(login, pattern) for pattern in self.users)
146
+
147
+ # -- the check -------------------------------------------------------
148
+
149
+ def decide(self, headers, raw_path: str, query: dict, navigating: bool) -> Decision:
150
+ """Check a request. raw_path is still percent-encoded, for use in redirects."""
151
+ if self.mode == "open":
152
+ return Decision(True)
153
+ if self.mode == "tailscale":
154
+ return self._tailscale(headers)
155
+ return self._token(headers, raw_path, query, navigating)
156
+
157
+ def _tailscale(self, headers) -> Decision:
158
+ login = headers.get(IDENTITY_HEADER)
159
+ if not login:
160
+ return Decision(False, reason="no-identity")
161
+ login = decode_rfc2047(login)
162
+ if not self.user_allowed(login):
163
+ return Decision(False, user=login, reason="not-allowed")
164
+ name = headers.get(NAME_HEADER)
165
+ return Decision(True, user=decode_rfc2047(name) if name else login, login=login.lower())
166
+
167
+ def _token(self, headers, raw_path: str, query: dict, navigating: bool) -> Decision:
168
+ token = self.tokens.current()
169
+ if not token:
170
+ return Decision(False, reason="no-token-configured")
171
+ expected = self.session_value(token)
172
+
173
+ offered = query.get("token", [None])[0]
174
+ if offered is not None:
175
+ if not hmac.compare_digest(offered.encode(), token.encode()):
176
+ return Decision(False, reason="bad-token")
177
+ decision = Decision(True, cookie=self.session_cookie(token))
178
+ if navigating:
179
+ rest = {key: values for key, values in query.items() if key != "token"}
180
+ decision.clean_url = raw_path + ("?" + urlencode(rest, doseq=True) if rest else "")
181
+ return decision
182
+
183
+ auth = headers.get("Authorization", "")
184
+ if auth.lower().startswith("bearer "):
185
+ if hmac.compare_digest(auth[7:].strip().encode(), token.encode()):
186
+ return Decision(True)
187
+ return Decision(False, reason="bad-token")
188
+
189
+ cookies = SimpleCookie()
190
+ with suppress(CookieError):
191
+ cookies.load(headers.get("Cookie", ""))
192
+ morsel = cookies.get(self.cookie_name)
193
+ if morsel and hmac.compare_digest(morsel.value.encode(), expected.encode()):
194
+ return Decision(True)
195
+ return Decision(False, reason="no-session")
196
+
197
+
198
+ # Filled in with .replace("{message}", ...) rather than %-formatting, because the CSS has % signs.
199
+ LOGIN_PAGE = """<!doctype html>
200
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
201
+ <title>Bunko · sign in</title>
202
+ <style>
203
+ :root{--bg:#fff;--text:#1e2329;--muted:#5d6670;--line:rgba(30,35,41,.16);--accent:#0e7c86;color-scheme:light}
204
+ @media (prefers-color-scheme:dark){:root{--bg:#15171a;--text:#e3e6ea;--muted:#9aa3ad;--line:rgba(227,230,234,.14);--accent:#2a8f99;color-scheme:dark}}
205
+ *{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,-apple-system,"Segoe UI",Helvetica,Arial,sans-serif;padding:16px}
206
+ main{width:min(380px,100%)}h1{font-size:22px;margin:0 0 6px}p{color:var(--muted);margin:0 0 18px}
207
+ input{width:100%;height:38px;padding:0 10px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--text);font:inherit}
208
+ input:focus{outline:2px solid var(--accent);outline-offset:-1px}button{margin-top:10px;width:100%;height:38px;border:0;border-radius:6px;background:var(--accent);color:#fff;font:inherit;cursor:pointer}
209
+ .err{color:#e5484d;margin:-6px 0 14px}
210
+ </style></head><body><main>
211
+ <h1>Bunko</h1><p>This server needs an access token. Paste it here, or open the link the server printed.</p>
212
+ {message}<form method="get" action="/"><input name="token" type="password" autocomplete="current-password" placeholder="Access token" aria-label="Access token" autofocus required><button>Open</button></form>
213
+ </main></body></html>"""
214
+
215
+ DENIED_PAGE = """<!doctype html>
216
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
217
+ <title>Bunko · no access</title>
218
+ <style>
219
+ :root{--bg:#fff;--text:#1e2329;--muted:#5d6670;color-scheme:light}
220
+ @media (prefers-color-scheme:dark){:root{--bg:#15171a;--text:#e3e6ea;--muted:#9aa3ad;color-scheme:dark}}
221
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,-apple-system,"Segoe UI",Helvetica,Arial,sans-serif;padding:16px}
222
+ main{width:min(440px,100%)}h1{font-size:22px;margin:0 0 6px}p{color:var(--muted)}
223
+ </style></head><body><main><h1>No access</h1><p>{message}</p></main></body></html>"""
224
+
225
+ PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
bunko/cli.py ADDED
@@ -0,0 +1,231 @@
1
+ """Command line: `bunko [PORT] [DIR] [options]`, plus `bunko service` and `bunko token`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import socket
8
+ import sys
9
+
10
+ from . import __version__
11
+ from .access import Access, TokenStore, is_loopback
12
+ from .contents import ContentSearch
13
+ from .index import SearchIndex
14
+ from .media import Prober, Thumbnails
15
+ from .paths import Root
16
+ from .places import Places
17
+ from .server import DEFAULT_PORT, Server, bind, make_handler
18
+
19
+ EPILOG = """examples:
20
+ bunko serve the current folder on port 8000 (or the next free one)
21
+ bunko 8099 ~/reports choose the port and folder
22
+ bunko 8100 ~/reports --allow-user you@example.com
23
+ recommended on a shared network: put `tailscale serve` in front
24
+ bunko 8100 ~/reports -b 0.0.0.0 --token
25
+ reachable from any network, with an access token
26
+
27
+ subcommands:
28
+ bunko service install|uninstall|status|logs|restart|list run as a systemd user service
29
+ bunko token [--new] [--port N] show or replace the access token
30
+
31
+ docs: https://github.com/ivanfarevalo/bunko/tree/main/docs"""
32
+
33
+
34
+ def build_parser() -> argparse.ArgumentParser:
35
+ parser = argparse.ArgumentParser(
36
+ prog="bunko",
37
+ description="Serve a folder read-only, with a browser UI that renders its files.",
38
+ epilog=EPILOG,
39
+ formatter_class=argparse.RawDescriptionHelpFormatter,
40
+ )
41
+ parser.add_argument("target", nargs="*", help="a port number and/or a directory")
42
+ parser.add_argument("-p", "--port", type=int, help=f"port (default {DEFAULT_PORT})")
43
+ parser.add_argument("-d", "--directory", help="directory to serve (default: current)")
44
+ parser.add_argument(
45
+ "-b",
46
+ "--bind",
47
+ default="127.0.0.1",
48
+ help="address to listen on (default: 127.0.0.1, this machine only; 0.0.0.0 for every network)",
49
+ )
50
+ parser.add_argument("--hidden", action="store_true", help="also show and serve dotfiles")
51
+
52
+ access = parser.add_argument_group("access control (see docs/security.md)")
53
+ access.add_argument(
54
+ "--allow-user",
55
+ action="append",
56
+ default=[],
57
+ metavar="LOGIN",
58
+ help="allow this Tailscale user; repeat for more, wildcards allowed (*@example.com). "
59
+ "Requires -b 127.0.0.1 and `tailscale serve` in front",
60
+ )
61
+ access.add_argument("--token", action="store_true", help="require an access token")
62
+ access.add_argument(
63
+ "--new-token",
64
+ action="store_true",
65
+ help="replace the token before starting (implies --token)",
66
+ )
67
+ access.add_argument(
68
+ "--token-file", metavar="PATH", help="where the token lives (default ~/.config/bunko/token)"
69
+ )
70
+
71
+ media = parser.add_argument_group("media")
72
+ media.add_argument(
73
+ "--no-thumbnails", action="store_true", help="don't generate thumbnails with ffmpeg"
74
+ )
75
+ media.add_argument(
76
+ "--cache-dir", metavar="PATH", help="thumbnail cache (default ~/.cache/bunko)"
77
+ )
78
+
79
+ parser.add_argument("-v", "--verbose", action="store_true", help="log every request")
80
+ parser.add_argument("--version", action="version", version="bunko " + __version__)
81
+ return parser
82
+
83
+
84
+ def parse_args(argv=None):
85
+ parser = build_parser()
86
+ args = parser.parse_args(argv)
87
+ for item in args.target:
88
+ if item.isdecimal() and not os.path.isdir(item):
89
+ if args.port is not None:
90
+ parser.error("more than one port given")
91
+ args.port = int(item)
92
+ elif args.directory is None:
93
+ args.directory = item
94
+ else:
95
+ parser.error("more than one directory given")
96
+ if args.new_token:
97
+ args.token = True
98
+ if args.allow_user and args.token:
99
+ parser.error("choose one of --allow-user and --token")
100
+ if args.allow_user and not is_loopback(args.bind):
101
+ parser.error(
102
+ "--allow-user trusts identity headers from `tailscale serve`, so bunko must listen "
103
+ "only on loopback. Add -b 127.0.0.1 (see docs/security.md)."
104
+ )
105
+ return args
106
+
107
+
108
+ def token_command(argv) -> None:
109
+ parser = argparse.ArgumentParser(
110
+ prog="bunko token", description="Show or replace the access token."
111
+ )
112
+ parser.add_argument(
113
+ "--new", action="store_true", help="replace it; every signed-in browser must sign in again"
114
+ )
115
+ parser.add_argument("--port", type=int, help="print a sign-in link for this port")
116
+ parser.add_argument("--host", default=socket.gethostname(), help="host name for the link")
117
+ parser.add_argument("--token-file", metavar="PATH")
118
+ args = parser.parse_args(argv)
119
+ store = TokenStore(args.token_file)
120
+ token = store.rotate() if args.new else store.ensure()
121
+ if args.new:
122
+ print(
123
+ f"New token saved to {store.describe()}. Running servers pick it up on the next request."
124
+ )
125
+ if args.port:
126
+ print(f"http://{args.host}:{args.port}/?token={token}")
127
+ else:
128
+ print(token)
129
+
130
+
131
+ def main(argv=None) -> None:
132
+ argv = list(sys.argv[1:] if argv is None else argv)
133
+ if argv[:1] == ["service"]:
134
+ from .service import main as service_main
135
+
136
+ return service_main(argv[1:])
137
+ if argv[:1] == ["token"]:
138
+ return token_command(argv[1:])
139
+
140
+ args = parse_args(argv)
141
+ server = build_server(args)
142
+ print_banner(server, args)
143
+ try:
144
+ server.serve_forever()
145
+ except KeyboardInterrupt:
146
+ pass
147
+ finally:
148
+ server.server_close()
149
+ return None
150
+
151
+
152
+ def access_mode(args) -> str:
153
+ return "tailscale" if args.allow_user else "token" if args.token else "open"
154
+
155
+
156
+ def build_server(args) -> Server:
157
+ """Set up the folder, its services, and the listening socket."""
158
+ directory = os.path.abspath(os.path.expanduser(args.directory or "."))
159
+ if not os.path.isdir(directory):
160
+ sys.exit("bunko: not a directory: " + directory)
161
+ root = Root(directory, args.hidden)
162
+ index = SearchIndex(root)
163
+ tokens = TokenStore(args.token_file) if args.token else None
164
+ if tokens and args.new_token:
165
+ tokens.rotate()
166
+ elif tokens:
167
+ tokens.ensure()
168
+ handler = make_handler(
169
+ root,
170
+ index,
171
+ contents=ContentSearch(root, index),
172
+ thumbs=Thumbnails(args.cache_dir, enabled=not args.no_thumbnails),
173
+ prober=Prober(),
174
+ places=Places(root),
175
+ )
176
+ server = bind(handler, args.bind, args.port or DEFAULT_PORT, args.port is not None)
177
+ # The cookie name includes the port, which is only known once bound.
178
+ handler.access = Access(access_mode(args), server.server_address[1], tokens, args.allow_user)
179
+ server.verbose = args.verbose
180
+ index.refresh()
181
+ return server
182
+
183
+
184
+ def print_banner(server: Server, args) -> None:
185
+ """Say what is served, where, and how it's protected."""
186
+ handler = server.RequestHandlerClass
187
+ port = server.server_address[1]
188
+ mode = handler.access.mode
189
+ notes = ["read-only"]
190
+ if args.hidden:
191
+ notes.append("dotfiles visible")
192
+ notes.append(
193
+ {
194
+ "open": "no access control",
195
+ "token": "token required",
196
+ "tailscale": "Tailscale users: " + ", ".join(args.allow_user),
197
+ }[mode]
198
+ )
199
+ print(f"bunko {__version__} serving {handler.root.real} ({'; '.join(notes)})")
200
+
201
+ exposed = args.bind in ("0.0.0.0", "::")
202
+ links = [f"http://{'localhost' if exposed else args.bind}:{port}/"]
203
+ if exposed:
204
+ links.append(f"http://{socket.gethostname()}:{port}/")
205
+ if mode == "token":
206
+ if sys.stdout.isatty():
207
+ token = handler.access.tokens.current()
208
+ links = [link + "?token=" + token for link in links]
209
+ else:
210
+ # Never write the secret into service logs.
211
+ print(f" token: run `bunko token --port {port}` to print a sign-in link")
212
+ for link in links:
213
+ print(" " + link)
214
+ if mode == "tailscale":
215
+ print(
216
+ f" put Tailscale in front: tailscale serve --bg --https={port} http://127.0.0.1:{port}"
217
+ )
218
+ if is_loopback(args.bind) and mode != "tailscale":
219
+ print(
220
+ f" only this machine can connect. From elsewhere: ssh -L {port}:localhost:{port} "
221
+ f"{socket.gethostname()}, or choose an address with -b (see docs/security.md)."
222
+ )
223
+ if mode == "open" and not is_loopback(args.bind):
224
+ print(
225
+ " warning: anyone who can reach this address can read these files. See docs/security.md."
226
+ )
227
+ sys.stdout.flush()
228
+
229
+
230
+ if __name__ == "__main__":
231
+ main()
bunko/contents.py ADDED
@@ -0,0 +1,207 @@
1
+ """Search inside files.
2
+
3
+ Uses ripgrep when installed (fast, skips binaries), else a pure-Python scan of
4
+ the name index. Either way every hit passes the same access check as a file
5
+ request, so a symlink cannot leak a dotfile's contents into results.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import threading
15
+ import time
16
+
17
+ from .index import SKIP_DIRS
18
+ from .media import IMAGE_EXTS, VIDEO_EXTS
19
+ from .paths import Blocked
20
+
21
+ LIMIT = 300 # matching lines per search
22
+ PER_FILE = 5 # matching lines per file
23
+ MAX_FILE_RG = 64 * 1024 * 1024 # as far as the viewer's jump-to-line reaches
24
+ MAX_FILE_PY = 5 * 1024 * 1024 # the Python fallback is slower, so it skips sooner
25
+ BUDGET = 12.0 # seconds before a search stops and returns what it has
26
+ SNIPPET = 220 # characters of context per line
27
+ # Skipped by the Python fallback without opening them. ripgrep detects binary files itself.
28
+ SKIP_EXTS = IMAGE_EXTS | VIDEO_EXTS | {
29
+ ".ico", ".mp3", ".wav", ".flac", ".ogg",
30
+ ".zip", ".gz", ".tgz", ".xz", ".bz2", ".7z", ".tar",
31
+ ".pdf", ".docx", ".xlsx", ".pptx",
32
+ ".pt", ".pth", ".onnx", ".bin", ".npy", ".npz", ".pkl", ".parquet", ".h5",
33
+ ".so", ".o", ".a", ".whl", ".pyc",
34
+ } # fmt: skip
35
+
36
+
37
+ def _matches(text: str, needle: str):
38
+ """(line number, line, spans) for the first PER_FILE lines containing needle."""
39
+ found = 0
40
+ for number, line in enumerate(text.split("\n"), 1):
41
+ lower = line.lower()
42
+ at = lower.find(needle)
43
+ if at < 0:
44
+ continue
45
+ spans = []
46
+ while at >= 0 and len(spans) < 10:
47
+ spans.append((at, at + len(needle)))
48
+ at = lower.find(needle, at + len(needle))
49
+ yield number, line, spans
50
+ found += 1
51
+ if found >= PER_FILE:
52
+ return
53
+
54
+
55
+ def snippet(line: str, start: int, end: int):
56
+ """Trim a long line to a window around the first match."""
57
+ line = line.rstrip("\r\n")
58
+ if len(line) <= SNIPPET:
59
+ return line, 0
60
+ left = max(0, min(start - SNIPPET // 3, len(line) - SNIPPET))
61
+ return line[left : left + SNIPPET], left
62
+
63
+
64
+ class ContentSearch:
65
+ """Case-insensitive search for a fixed string in every readable text file."""
66
+
67
+ def __init__(self, root, index, skip_dirs=SKIP_DIRS):
68
+ self.root = root
69
+ self.index = index
70
+ self.skip_dirs = skip_dirs
71
+ self.rg = shutil.which("rg")
72
+ # Searches read a lot of disk; two at a time is plenty.
73
+ self.slots = threading.BoundedSemaphore(2)
74
+
75
+ @property
76
+ def engine(self) -> str:
77
+ return "ripgrep" if self.rg else "python"
78
+
79
+ def search(self, query: str) -> dict:
80
+ query = query.strip()
81
+ if len(query) < 2:
82
+ return {"results": [], "engine": self.engine, "truncated": False, "partial": False}
83
+ started = time.monotonic()
84
+ with self.slots:
85
+ if self.rg:
86
+ hits, partial = self._ripgrep(query)
87
+ else:
88
+ hits, partial = self._python(query)
89
+ return {
90
+ "results": hits,
91
+ "engine": self.engine,
92
+ "truncated": len(hits) >= LIMIT,
93
+ "partial": partial,
94
+ "seconds": round(time.monotonic() - started, 2),
95
+ }
96
+
97
+ def _allowed(self, rel: str) -> bool:
98
+ try:
99
+ self.root.resolve(rel)
100
+ except Blocked:
101
+ return False
102
+ return True
103
+
104
+ def _hit(self, rel, number, line, spans):
105
+ if not spans:
106
+ return None
107
+ text, shift = snippet(line, spans[0][0], spans[0][1])
108
+ marks = [
109
+ [max(s - shift, 0), min(e - shift, len(text))]
110
+ for s, e in spans
111
+ if e - shift > 0 and s - shift < len(text)
112
+ ]
113
+ return {"path": rel, "line": number, "text": text, "marks": marks}
114
+
115
+ def _ripgrep(self, query: str):
116
+ command = [
117
+ self.rg,
118
+ "--json",
119
+ "--fixed-strings",
120
+ "--ignore-case",
121
+ "--follow",
122
+ "--no-ignore",
123
+ "--max-count",
124
+ str(PER_FILE),
125
+ "--max-filesize",
126
+ str(MAX_FILE_RG),
127
+ "--max-columns",
128
+ "2000",
129
+ "--max-columns-preview",
130
+ ]
131
+ if self.root.show_hidden:
132
+ command.append("--hidden")
133
+ for name in self.skip_dirs:
134
+ command += ["--glob", f"!**/{name}/**"]
135
+ command += ["--", query, "."]
136
+ hits = []
137
+ partial = False
138
+ deadline = time.monotonic() + BUDGET
139
+ process = subprocess.Popen(
140
+ command, cwd=self.root.real, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
141
+ )
142
+ try:
143
+ for raw in process.stdout:
144
+ if time.monotonic() > deadline:
145
+ partial = True
146
+ break
147
+ try:
148
+ event = json.loads(raw)
149
+ except ValueError:
150
+ continue
151
+ if event.get("type") != "match":
152
+ continue
153
+ data = event["data"]
154
+ rel = data["path"].get("text")
155
+ line = data["lines"].get("text")
156
+ if rel is None or line is None: # not valid UTF-8
157
+ continue
158
+ rel = rel[2:] if rel.startswith("./") else rel
159
+ if not self._allowed(rel):
160
+ continue
161
+ encoded = line.encode("utf-8", "surrogateescape")
162
+ spans = [
163
+ (
164
+ len(encoded[: m["start"]].decode("utf-8", "replace")),
165
+ len(encoded[: m["end"]].decode("utf-8", "replace")),
166
+ )
167
+ for m in data.get("submatches", [])
168
+ ]
169
+ hit = self._hit(rel, data.get("line_number"), line, spans)
170
+ if hit:
171
+ hits.append(hit)
172
+ if len(hits) >= LIMIT:
173
+ break
174
+ finally:
175
+ process.kill()
176
+ process.wait()
177
+ return hits, partial
178
+
179
+ def _python(self, query: str):
180
+ needle = query.lower()
181
+ hits = []
182
+ partial = False
183
+ deadline = time.monotonic() + BUDGET
184
+ for rel, _lowered in list(self.index.paths):
185
+ if rel.endswith("/") or os.path.splitext(rel)[1].lower() in SKIP_EXTS:
186
+ continue
187
+ if time.monotonic() > deadline:
188
+ partial = True
189
+ break
190
+ try:
191
+ real = self.root.resolve(rel)
192
+ if os.path.getsize(real) > MAX_FILE_PY:
193
+ continue
194
+ with open(real, "rb") as handle:
195
+ data = handle.read()
196
+ except (Blocked, OSError):
197
+ continue
198
+ if b"\0" in data[:8192]:
199
+ continue
200
+ text = data.decode("utf-8", "replace")
201
+ if needle not in text.lower():
202
+ continue
203
+ for number, line, spans in _matches(text, needle):
204
+ hits.append(self._hit(rel, number, line, spans))
205
+ if len(hits) >= LIMIT:
206
+ return hits, partial
207
+ return hits, partial