keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""The browsers' own history files (docs/design/browse-brain.md §1): Chromium (Chrome, Edge,
|
|
2
|
+
Brave, Comet, every profile) and Firefox. Each file is copied to a temp folder (it is locked
|
|
3
|
+
while the browser runs), opened read-only and deleted again; a browser file is never written.
|
|
4
|
+
`scan` is the counts-only dry run behind `keepfold browse scan`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import sqlite3
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
import time
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import UTC, datetime, timedelta, tzinfo
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from keepfold.browse import privacy
|
|
24
|
+
from keepfold.events import local_day
|
|
25
|
+
|
|
26
|
+
CHROMIUM = {"chrome": ("Google", "Chrome"), "edge": ("Microsoft", "Edge"),
|
|
27
|
+
"brave": ("BraveSoftware", "Brave-Browser"),
|
|
28
|
+
"comet": ("Perplexity", "Comet")} # Perplexity's Chromium browser
|
|
29
|
+
# macOS (~/Library/Application Support) and Linux (~/.config): profiles sit right in the folder
|
|
30
|
+
MAC_CHROMIUM = {"chrome": ("Google", "Chrome"), "edge": ("Microsoft Edge",),
|
|
31
|
+
"brave": ("BraveSoftware", "Brave-Browser")}
|
|
32
|
+
LINUX_CHROMIUM = {"chrome": ("google-chrome",), "edge": ("microsoft-edge",),
|
|
33
|
+
"brave": ("BraveSoftware", "Brave-Browser")}
|
|
34
|
+
BROWSERS = (*CHROMIUM, "firefox")
|
|
35
|
+
EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
|
|
36
|
+
CHROME_OFFSET_US = 11_644_473_600_000_000 # 1601-01-01 to 1970-01-01
|
|
37
|
+
SUBFRAME = {3, 4} # Chromium core transitions AUTO_SUBFRAME, MANUAL_SUBFRAME: not a page
|
|
38
|
+
FF_SKIP = {4, 8} # Firefox TRANSITION_EMBED, TRANSITION_FRAMED_LINK
|
|
39
|
+
GAP_CAP = 600.0 # seconds: a visit lasts until the next one, at most this long
|
|
40
|
+
TEMP_PREFIX, STALE_SECS = "keepfold-browse-", 3600
|
|
41
|
+
CHROMIUM_SQL = """
|
|
42
|
+
SELECT v.visit_time, v.visit_duration, v.transition, u.url, u.title,
|
|
43
|
+
(SELECT k.term FROM keyword_search_terms k WHERE k.url_id = u.id LIMIT 1), v.rowid
|
|
44
|
+
FROM visits v JOIN urls u ON u.id = v.url {where} ORDER BY v.visit_time"""
|
|
45
|
+
FIREFOX_SQL = """
|
|
46
|
+
SELECT v.visit_date, v.visit_type, p.url, p.title, v.rowid
|
|
47
|
+
FROM moz_historyvisits v JOIN moz_places p ON p.id = v.place_id {where} ORDER BY v.visit_date"""
|
|
48
|
+
# rows past the cursor: a new visit id, or a time in the last GAP_CAP before the newest time
|
|
49
|
+
# read (re-read, so the last visit's time on the page is measured to the visit after it)
|
|
50
|
+
_SINCE = {"chromium": "WHERE v.rowid > ? OR v.visit_time >= ?",
|
|
51
|
+
"firefox": "WHERE v.rowid > ? OR v.visit_date >= ?"}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CopyFailed(OSError):
|
|
55
|
+
"""The History file could not be copied (the browser holds it locked, or no permission)."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def why(e: BaseException) -> str:
|
|
59
|
+
"""A source's read error as a short, text-free reason for the owner."""
|
|
60
|
+
if isinstance(e, CopyFailed):
|
|
61
|
+
return ("could not copy its history file (the browser may hold it locked: close the "
|
|
62
|
+
"browser and run again)")
|
|
63
|
+
if isinstance(e, sqlite3.DatabaseError):
|
|
64
|
+
return "its history file is not a readable database"
|
|
65
|
+
return f"not read ({type(e).__name__})"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class Source:
|
|
70
|
+
browser: str
|
|
71
|
+
profile: str
|
|
72
|
+
path: Path
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def key(self) -> str:
|
|
76
|
+
return f"{self.browser}/{self.profile}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Visit:
|
|
81
|
+
start: datetime # aware, UTC
|
|
82
|
+
url: str # raw: filtered before anything keeps it
|
|
83
|
+
title: str
|
|
84
|
+
secs: float # estimated time on the page
|
|
85
|
+
term: str | None = None # Chromium's keyword_search_terms
|
|
86
|
+
source: str = ""
|
|
87
|
+
excerpt: str = "" # from the extension's inbox only
|
|
88
|
+
channel: str = "" # a video's channel, from the extension's inbox only
|
|
89
|
+
# "<raw time>:<URL hash>": the visit's key in keepfold.browse.store, the same however the
|
|
90
|
+
# browser numbers its rows (a rebuilt History file, a reused id)
|
|
91
|
+
native: str = ""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _profiles(browser: str, folder: Path, name: str) -> list[Source]:
|
|
95
|
+
return [Source(browser, d.name, d / name) for d in sorted(folder.iterdir())
|
|
96
|
+
if (d / name).is_file()] if folder.is_dir() else []
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _discover_unix(home: Path, mac: bool) -> list[Source]:
|
|
100
|
+
"""macOS and Linux (review C14): the same browsers under ~/Library/Application Support or
|
|
101
|
+
~/.config, and Firefox under its own profile folder."""
|
|
102
|
+
base = home / "Library" / "Application Support" if mac else home / ".config"
|
|
103
|
+
out = []
|
|
104
|
+
for browser, parts in (MAC_CHROMIUM if mac else LINUX_CHROMIUM).items():
|
|
105
|
+
out += _profiles(browser, base.joinpath(*parts), "History")
|
|
106
|
+
ff = base / "Firefox" / "Profiles" if mac else home / ".mozilla" / "firefox"
|
|
107
|
+
return out + _profiles("firefox", ff, "places.sqlite")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def discover(local: Path | None = None, roaming: Path | None = None, *,
|
|
111
|
+
home: Path | None = None, platform: str | None = None) -> list[Source]:
|
|
112
|
+
"""Every Chromium profile folder holding a `History` file under `local` (default
|
|
113
|
+
%LOCALAPPDATA%) and every Firefox profile with `places.sqlite` under `roaming` (default
|
|
114
|
+
%APPDATA%). On macOS and Linux (`platform`, default sys.platform), with neither folder
|
|
115
|
+
given, the browsers' folders under `home` (default ~) instead."""
|
|
116
|
+
platform = platform or sys.platform
|
|
117
|
+
if local is None and roaming is None and not platform.startswith("win"):
|
|
118
|
+
return _discover_unix(home or Path.home(), platform == "darwin")
|
|
119
|
+
if local is None and os.environ.get("LOCALAPPDATA"):
|
|
120
|
+
local = Path(os.environ["LOCALAPPDATA"])
|
|
121
|
+
if roaming is None and os.environ.get("APPDATA"):
|
|
122
|
+
roaming = Path(os.environ["APPDATA"])
|
|
123
|
+
out = []
|
|
124
|
+
for browser, parts in CHROMIUM.items():
|
|
125
|
+
ud = local.joinpath(*parts, "User Data") if local else None
|
|
126
|
+
if ud and ud.is_dir():
|
|
127
|
+
out += [Source(browser, d.name, d / "History") for d in sorted(ud.iterdir())
|
|
128
|
+
if (d / "History").is_file()]
|
|
129
|
+
ff = roaming / "Mozilla" / "Firefox" / "Profiles" if roaming else None
|
|
130
|
+
if ff and ff.is_dir():
|
|
131
|
+
out += [Source("firefox", d.name, d / "places.sqlite") for d in sorted(ff.iterdir())
|
|
132
|
+
if (d / "places.sqlite").is_file()]
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def chosen(settings, found: list[Source] | None = None) -> list[Source]:
|
|
137
|
+
"""The sources `browse.browsers` allows (every one found when it is empty), minus the
|
|
138
|
+
profiles unticked in the app (`browse.skip_profiles`)."""
|
|
139
|
+
found = discover() if found is None else found
|
|
140
|
+
want = getattr(settings, "browsers", ())
|
|
141
|
+
skip = getattr(settings, "skip_profiles", ())
|
|
142
|
+
return [s for s in found if (not want or s.browser in want) and not (skip and s.key in skip)]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def pick(sources: list[Source], browser: str | None = None,
|
|
146
|
+
profile: str | None = None) -> list[Source]:
|
|
147
|
+
return [s for s in sources if (browser is None or s.browser == browser.lower())
|
|
148
|
+
and (profile is None or s.profile.lower() == profile.lower())]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def to_time(browser: str, raw: int) -> datetime:
|
|
152
|
+
"""A browser timestamp (Chromium: µs since 1601; Firefox: µs since 1970) as UTC."""
|
|
153
|
+
return EPOCH + timedelta(microseconds=raw - (0 if browser == "firefox" else
|
|
154
|
+
CHROME_OFFSET_US))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _rmtree(d: Path) -> None:
|
|
158
|
+
"""Delete a temp copy, retrying while Windows still holds a handle on it."""
|
|
159
|
+
for n in range(5):
|
|
160
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
161
|
+
if not d.exists():
|
|
162
|
+
return
|
|
163
|
+
time.sleep(0.1 * (n + 1))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def sweep(now: float | None = None) -> None:
|
|
167
|
+
"""Delete temp copies a crashed or locked-out earlier run left (older than STALE_SECS)."""
|
|
168
|
+
now = time.time() if now is None else now
|
|
169
|
+
for d in Path(tempfile.gettempdir()).glob(TEMP_PREFIX + "*"):
|
|
170
|
+
try:
|
|
171
|
+
if d.is_dir() and now - d.stat().st_mtime > STALE_SECS:
|
|
172
|
+
_rmtree(d)
|
|
173
|
+
except OSError:
|
|
174
|
+
pass
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@contextmanager
|
|
178
|
+
def _copy(path: Path) -> Iterator[sqlite3.Connection]:
|
|
179
|
+
"""A read-only connection to a temp copy of `path` (and its -wal), deleted afterwards."""
|
|
180
|
+
d = Path(tempfile.mkdtemp(prefix=TEMP_PREFIX))
|
|
181
|
+
try:
|
|
182
|
+
dst = d / path.name
|
|
183
|
+
try:
|
|
184
|
+
shutil.copyfile(path, dst)
|
|
185
|
+
wal = path.with_name(path.name + "-wal")
|
|
186
|
+
if wal.is_file():
|
|
187
|
+
shutil.copyfile(wal, dst.with_name(dst.name + "-wal"))
|
|
188
|
+
except OSError as e:
|
|
189
|
+
raise CopyFailed(str(e)) from e
|
|
190
|
+
con = sqlite3.connect(f"{dst.as_uri()}?mode=ro", uri=True)
|
|
191
|
+
try:
|
|
192
|
+
yield con
|
|
193
|
+
finally:
|
|
194
|
+
con.close()
|
|
195
|
+
finally:
|
|
196
|
+
_rmtree(d)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _sane(browser: str, raw, late: datetime) -> bool:
|
|
200
|
+
"""A raw visit time that is an integer and lands between 1970 and tomorrow."""
|
|
201
|
+
if not isinstance(raw, int) or isinstance(raw, bool) or raw < 0:
|
|
202
|
+
return False
|
|
203
|
+
try:
|
|
204
|
+
return EPOCH <= to_time(browser, raw) <= late
|
|
205
|
+
except OverflowError:
|
|
206
|
+
return False
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def read(src: Source) -> tuple[list[Visit], int | None]:
|
|
210
|
+
"""Every page visit of `src`, oldest first, and the newest raw timestamp (the cursor).
|
|
211
|
+
A visit lasts until the next one (at most GAP_CAP), or its recorded duration if shorter.
|
|
212
|
+
A row whose time is not an integer, negative or out of range is skipped (second review
|
|
213
|
+
L1), so one bad row never aborts the source or moves the cursor into the future."""
|
|
214
|
+
visits, top, _ = read_since(src)
|
|
215
|
+
return visits, top
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def read_since(src: Source, after_id: int | None = None, after_time: int | None = None
|
|
219
|
+
) -> tuple[list[Visit], int | None, int | None]:
|
|
220
|
+
"""The visits of `src` past a cursor, all at once (`Since` reads them in chunks): the
|
|
221
|
+
visits, oldest first, then the newest raw time and visit id read (the next cursor)."""
|
|
222
|
+
with Since(src, after_id, after_time) as rd:
|
|
223
|
+
out = [v for chunk in rd.chunks() for v in chunk]
|
|
224
|
+
return out, rd.top_time, rd.top_id
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class Since:
|
|
228
|
+
"""The visits of `src` past a cursor (`after_id`, `after_time`: the newest visit id and
|
|
229
|
+
raw time read before; None reads all), from a temp copy of its History file while open:
|
|
230
|
+
`total` rows to go through, `chunks(n)` yields them as Visits, oldest first, with their
|
|
231
|
+
`native` key, n at a time (memory stays bounded however long the history), then
|
|
232
|
+
`top_time` and `top_id` hold the next cursor (None when nothing was read). Visits of the
|
|
233
|
+
last GAP_CAP before `after_time` are read again, so their time on the page is measured to
|
|
234
|
+
the next visit. Only the rows past the cursor are fetched (the History file's indexes on
|
|
235
|
+
the visit id and time), so a run with nothing new reads next to nothing."""
|
|
236
|
+
|
|
237
|
+
def __init__(self, src: Source, after_id: int | None = None,
|
|
238
|
+
after_time: int | None = None):
|
|
239
|
+
self.src, self.total = src, 0
|
|
240
|
+
self.top_time: int | None = None
|
|
241
|
+
self.top_id: int | None = None
|
|
242
|
+
since = after_id is not None and after_time is not None
|
|
243
|
+
self._where = _SINCE["firefox" if src.browser == "firefox" else "chromium"] \
|
|
244
|
+
if since else ""
|
|
245
|
+
self._args = (after_id, after_time - int(GAP_CAP * 1e6)) if since else ()
|
|
246
|
+
|
|
247
|
+
def __enter__(self) -> Since:
|
|
248
|
+
sweep()
|
|
249
|
+
self._copy = _copy(self.src.path)
|
|
250
|
+
self._con = self._copy.__enter__()
|
|
251
|
+
try:
|
|
252
|
+
table = "moz_historyvisits" if self.src.browser == "firefox" else "visits"
|
|
253
|
+
self.total = self._con.execute(
|
|
254
|
+
f"SELECT COUNT(*) FROM {table} v {self._where}", self._args).fetchone()[0]
|
|
255
|
+
except BaseException:
|
|
256
|
+
self._copy.__exit__(None, None, None)
|
|
257
|
+
raise
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
def __exit__(self, *exc) -> None:
|
|
261
|
+
self._copy.__exit__(*exc)
|
|
262
|
+
|
|
263
|
+
def chunks(self, n: int = 1000) -> Iterator[list[Visit]]:
|
|
264
|
+
ff = self.src.browser == "firefox"
|
|
265
|
+
sql = (FIREFOX_SQL if ff else CHROMIUM_SQL).format(where=self._where)
|
|
266
|
+
late = datetime.now(UTC) + timedelta(days=1)
|
|
267
|
+
out: list[Visit] = []
|
|
268
|
+
last = None # the row before: its time on the page is measured to this one
|
|
269
|
+
for r in self._con.execute(sql, self._args):
|
|
270
|
+
if ff:
|
|
271
|
+
raw, ty, url, title, rid = r
|
|
272
|
+
dur, term, keep = 0, None, ty not in FF_SKIP
|
|
273
|
+
else:
|
|
274
|
+
raw, dur, tr, url, title, term, rid = r
|
|
275
|
+
keep = not isinstance(tr, int) or tr & 0xFF not in SUBFRAME
|
|
276
|
+
if isinstance(rid, int): # a frame moves the cursor too
|
|
277
|
+
self.top_id = rid if self.top_id is None else max(self.top_id, rid)
|
|
278
|
+
if not keep or not _sane(self.src.browser, raw, late):
|
|
279
|
+
continue
|
|
280
|
+
if last is not None:
|
|
281
|
+
out.append(self._visit(last, raw))
|
|
282
|
+
if len(out) >= n:
|
|
283
|
+
yield out
|
|
284
|
+
out = []
|
|
285
|
+
last = (raw, dur if isinstance(dur, int) else 0, url, title, term)
|
|
286
|
+
self.top_time = raw if self.top_time is None else max(self.top_time, raw)
|
|
287
|
+
if last is not None:
|
|
288
|
+
out.append(self._visit(last, None))
|
|
289
|
+
if out:
|
|
290
|
+
yield out
|
|
291
|
+
|
|
292
|
+
def _visit(self, row: tuple, after: int | None) -> Visit:
|
|
293
|
+
raw, dur, url, title, term = row
|
|
294
|
+
secs = min(max((after - raw) / 1e6, 0.0), GAP_CAP) if after is not None else GAP_CAP
|
|
295
|
+
if dur and dur > 0:
|
|
296
|
+
secs = min(secs, dur / 1e6)
|
|
297
|
+
return Visit(to_time(self.src.browser, raw), url or "", title or "", secs,
|
|
298
|
+
term or None, self.src.key,
|
|
299
|
+
native=f"{raw}:{hashlib.sha1((url or '').encode()).hexdigest()[:16]}")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def scan(sources: list[Source], settings: privacy.Settings,
|
|
303
|
+
tz: tzinfo | None = None) -> list[dict]:
|
|
304
|
+
"""Per source: visits, searches, first and last day, and how many the filter would drop,
|
|
305
|
+
keep private or keep (a "maybe" counts as its category; "keep" can still turn private on
|
|
306
|
+
import when a page sits under no topic hub). Counts only, never text."""
|
|
307
|
+
rows = []
|
|
308
|
+
for s in sources:
|
|
309
|
+
c: Counter = Counter()
|
|
310
|
+
first = last = None
|
|
311
|
+
try:
|
|
312
|
+
with Since(s) as rd:
|
|
313
|
+
for chunk in rd.chunks():
|
|
314
|
+
for v in chunk:
|
|
315
|
+
k = privacy.judge(v.url, v.title, settings=settings)
|
|
316
|
+
out = privacy.apply(k, settings=settings)
|
|
317
|
+
c["dropped" if out is None else "private" if out.private else "kept"] += 1
|
|
318
|
+
c["searches"] += bool(v.term or (k and k.search))
|
|
319
|
+
c["maybe"] += bool(k and k.maybe)
|
|
320
|
+
first = first or local_day(chunk[0].start, tz)
|
|
321
|
+
last = local_day(chunk[-1].start, tz)
|
|
322
|
+
except Exception as e: # one bad source never stops the others
|
|
323
|
+
rows.append({"source": s.key, "error": type(e).__name__, "why": why(e)})
|
|
324
|
+
continue
|
|
325
|
+
rows.append({"source": s.key, "visits": c["dropped"] + c["private"] + c["kept"],
|
|
326
|
+
"searches": c["searches"], "first": first, "last": last,
|
|
327
|
+
"dropped": c["dropped"], "private": c["private"], "kept": c["kept"],
|
|
328
|
+
"maybe": c["maybe"]})
|
|
329
|
+
return rows
|