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
keepfold/app/exports.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""B2-b: a chat export the owner downloaded, noticed in Downloads and offered on Home.
|
|
2
|
+
|
|
3
|
+
Claude Desktop and claude.ai chats have no transcript on disk; the account's data export is
|
|
4
|
+
the complete copy. The app looks at the .zip files directly in Downloads (a stat, then the
|
|
5
|
+
zip's member NAMES only: no member is opened before the owner clicks Add chats), at most once
|
|
6
|
+
a minute, and only while `app.chat_import` is on. What was offered and answered lives in
|
|
7
|
+
~/.keepfold/desktop.json (`desktop.save_state`), keyed by path, mtime and size, so a zip
|
|
8
|
+
downloaded again under the same name counts as new.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import zipfile
|
|
19
|
+
from datetime import UTC, datetime, timedelta
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
KEY = "export_pickup" # desktop.json: {"seen": {path: [mtime, size, "added"|"dismissed"]},
|
|
23
|
+
# "later": ISO time the reminder stays hidden until, "claude": last Add}
|
|
24
|
+
SCAN_S = 60 # Home polls every 3 s: the folder is looked at once a minute at most
|
|
25
|
+
DAYS = 30
|
|
26
|
+
MAX_ZIPS = 20
|
|
27
|
+
KEEP_SEEN = 50
|
|
28
|
+
NAMES = {"claude": "claude.ai", "chatgpt": "ChatGPT", "gemini": "Google",
|
|
29
|
+
"google-activity": "Google"}
|
|
30
|
+
|
|
31
|
+
_lock = threading.Lock()
|
|
32
|
+
_cache: dict = {"at": None, "offer": None}
|
|
33
|
+
_kinds: dict = {} # (path, mtime, size) -> source or None: a zip's names are read once
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def downloads() -> Path:
|
|
37
|
+
"""The Downloads folder: KEEPFOLD_DOWNLOADS_DIR (tests), else the Windows known folder (it
|
|
38
|
+
may have been moved), else on Linux XDG_DOWNLOAD_DIR (a localized name such as ~/Загрузки),
|
|
39
|
+
else ~/Downloads."""
|
|
40
|
+
if env := os.environ.get("KEEPFOLD_DOWNLOADS_DIR"):
|
|
41
|
+
return Path(env)
|
|
42
|
+
if sys.platform == "win32":
|
|
43
|
+
try:
|
|
44
|
+
return Path(_known_downloads())
|
|
45
|
+
except (OSError, AttributeError, ValueError):
|
|
46
|
+
pass
|
|
47
|
+
elif sys.platform != "darwin" and (xdg := _xdg_downloads()) is not None:
|
|
48
|
+
return xdg
|
|
49
|
+
return Path.home() / "Downloads"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _xdg_downloads() -> Path | None:
|
|
53
|
+
"""XDG_DOWNLOAD_DIR from user-dirs.dirs (`XDG_DOWNLOAD_DIR="$HOME/Загрузки"`), or None."""
|
|
54
|
+
cfg = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "user-dirs.dirs"
|
|
55
|
+
try:
|
|
56
|
+
text = cfg.read_text(encoding="utf-8", errors="replace")
|
|
57
|
+
except OSError:
|
|
58
|
+
return None
|
|
59
|
+
m = re.search(r'^\s*XDG_DOWNLOAD_DIR\s*=\s*"([^"]*)"', text, re.M)
|
|
60
|
+
if not m:
|
|
61
|
+
return None
|
|
62
|
+
v = m[1]
|
|
63
|
+
if v == "$HOME" or v.startswith("$HOME/"):
|
|
64
|
+
return Path.home() / v[6:]
|
|
65
|
+
return Path(v) if v.startswith("/") else None # the spec allows only these two forms
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _known_downloads() -> str:
|
|
69
|
+
"""SHGetKnownFolderPath(FOLDERID_Downloads)."""
|
|
70
|
+
import ctypes
|
|
71
|
+
import uuid
|
|
72
|
+
from ctypes import wintypes
|
|
73
|
+
|
|
74
|
+
class GUID(ctypes.Structure):
|
|
75
|
+
_fields_ = [("a", wintypes.DWORD), ("b", wintypes.WORD), ("c", wintypes.WORD),
|
|
76
|
+
("d", ctypes.c_ubyte * 8)]
|
|
77
|
+
u = uuid.UUID("374DE290-123F-4565-9164-39C4925E467B")
|
|
78
|
+
g = GUID(u.fields[0], u.fields[1], u.fields[2], (ctypes.c_ubyte * 8)(*u.bytes[8:]))
|
|
79
|
+
out = ctypes.c_wchar_p()
|
|
80
|
+
if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(g), 0, None, ctypes.byref(out)):
|
|
81
|
+
raise OSError("no Downloads known folder")
|
|
82
|
+
try:
|
|
83
|
+
return out.value
|
|
84
|
+
finally:
|
|
85
|
+
ctypes.windll.ole32.CoTaskMemFree(out)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def kind_of(names: list[str]) -> str | None:
|
|
89
|
+
"""The guided-import source of an export, from its member names alone. A name-only twin
|
|
90
|
+
of `importers.detect`, which reads file heads (never done before the owner's click)."""
|
|
91
|
+
from keepfold.browse import takeout
|
|
92
|
+
low = [n.replace("\\", "/").lower() for n in names]
|
|
93
|
+
base = {n.rsplit("/", 1)[-1] for n in low}
|
|
94
|
+
if "conversations.json" in base:
|
|
95
|
+
if base & {"chat.html", "message_feedback.json"}:
|
|
96
|
+
return "chatgpt"
|
|
97
|
+
if base & {"users.json", "projects.json"}:
|
|
98
|
+
return "claude"
|
|
99
|
+
if any(n.startswith("takeout/") for n in low):
|
|
100
|
+
acts = [n for n in low if takeout.activity_file(n)]
|
|
101
|
+
if any("gemini" in n for n in acts):
|
|
102
|
+
return "gemini"
|
|
103
|
+
if any(takeout.wanted(n) for n in acts): # Search, YouTube or Chrome activity
|
|
104
|
+
return "google-activity"
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _kind(p: Path, mtime: float, size: int) -> str | None:
|
|
109
|
+
k = (str(p), mtime, size)
|
|
110
|
+
if k not in _kinds:
|
|
111
|
+
try:
|
|
112
|
+
with zipfile.ZipFile(p) as z:
|
|
113
|
+
_kinds[k] = kind_of(z.namelist())
|
|
114
|
+
except (OSError, zipfile.BadZipFile, ValueError):
|
|
115
|
+
_kinds[k] = None
|
|
116
|
+
return _kinds[k]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _state() -> dict:
|
|
120
|
+
from keepfold.app import desktop
|
|
121
|
+
s = desktop.load_state().get(KEY)
|
|
122
|
+
return s if isinstance(s, dict) else {}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _save(fn) -> None:
|
|
126
|
+
from keepfold.app import desktop
|
|
127
|
+
with _lock:
|
|
128
|
+
s = fn(_state())
|
|
129
|
+
seen = s.get("seen") or {}
|
|
130
|
+
s["seen"] = dict(list(seen.items())[-KEEP_SEEN:])
|
|
131
|
+
desktop.save_state(KEY, s)
|
|
132
|
+
forget()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def forget() -> None:
|
|
136
|
+
_cache["at"] = None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _imported_after(source: str, mtime: float) -> bool:
|
|
140
|
+
"""A chat source's folder changed after the zip landed: it was imported (the Import page
|
|
141
|
+
too, which records no path)."""
|
|
142
|
+
from keepfold import chats
|
|
143
|
+
if source not in chats.EXPORT_DIRS:
|
|
144
|
+
return False
|
|
145
|
+
d = chats.export_root() / chats.EXPORT_DIRS[source][0]
|
|
146
|
+
try:
|
|
147
|
+
return any(d.glob("*.jsonl")) and d.stat().st_mtime >= mtime
|
|
148
|
+
except OSError:
|
|
149
|
+
return False
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def candidates(now: float | None = None) -> list[dict]:
|
|
153
|
+
"""The new exports in Downloads, newest first: {path, source, mtime, size}."""
|
|
154
|
+
now = time.time() if now is None else now
|
|
155
|
+
try:
|
|
156
|
+
zips = [(p, p.stat()) for p in downloads().iterdir()
|
|
157
|
+
if p.suffix.lower() == ".zip" and p.is_file()]
|
|
158
|
+
except OSError:
|
|
159
|
+
return []
|
|
160
|
+
zips = sorted(((p, st) for p, st in zips if now - st.st_mtime <= DAYS * 86400),
|
|
161
|
+
key=lambda x: x[1].st_mtime, reverse=True)[:MAX_ZIPS]
|
|
162
|
+
seen = _state().get("seen") or {}
|
|
163
|
+
out = []
|
|
164
|
+
for p, st in zips:
|
|
165
|
+
was = seen.get(str(p))
|
|
166
|
+
if isinstance(was, list) and was[:2] == [st.st_mtime, st.st_size]:
|
|
167
|
+
continue
|
|
168
|
+
source = _kind(p, st.st_mtime, st.st_size)
|
|
169
|
+
if source and not _imported_after(source, st.st_mtime):
|
|
170
|
+
out.append({"path": str(p), "source": source, "mtime": st.st_mtime,
|
|
171
|
+
"size": st.st_size})
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _claude_recent(now: float) -> bool:
|
|
176
|
+
"""A claude.ai export was imported in the last DAYS days (its folder, or an Add here)."""
|
|
177
|
+
from keepfold import chats
|
|
178
|
+
s = _state()
|
|
179
|
+
try:
|
|
180
|
+
if now - datetime.fromisoformat(s.get("claude", "")).timestamp() <= DAYS * 86400:
|
|
181
|
+
return True
|
|
182
|
+
except (TypeError, ValueError):
|
|
183
|
+
pass
|
|
184
|
+
d = chats.export_root() / chats.EXPORT_DIRS["claude"][0]
|
|
185
|
+
try:
|
|
186
|
+
return any(d.glob("*.jsonl")) and now - d.stat().st_mtime <= DAYS * 86400
|
|
187
|
+
except OSError:
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _remind(now: float) -> bool:
|
|
192
|
+
"""The claude.ai reminder: Claude Desktop is connected, no claude.ai export came in the
|
|
193
|
+
last DAYS days, and Later was not clicked in that time."""
|
|
194
|
+
from keepfold.app import targets
|
|
195
|
+
try:
|
|
196
|
+
if datetime.fromisoformat(_state().get("later", "")).timestamp() > now:
|
|
197
|
+
return False
|
|
198
|
+
except (TypeError, ValueError):
|
|
199
|
+
pass
|
|
200
|
+
try:
|
|
201
|
+
on = targets.ClaudeDesktop().connected()
|
|
202
|
+
except (OSError, ValueError):
|
|
203
|
+
on = False
|
|
204
|
+
return on and not _claude_recent(now)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def offer() -> dict:
|
|
208
|
+
"""Home's card: {"found": the newest new export or None, "remind": bool}; the found card
|
|
209
|
+
wins. Nothing while the chat import setting is off. Cached for SCAN_S."""
|
|
210
|
+
from keepfold import chat_import
|
|
211
|
+
if not chat_import.enabled():
|
|
212
|
+
return {"found": None, "remind": False}
|
|
213
|
+
t = time.monotonic()
|
|
214
|
+
if _cache["at"] is not None and t - _cache["at"] < SCAN_S:
|
|
215
|
+
return _cache["offer"]
|
|
216
|
+
now = time.time()
|
|
217
|
+
c = candidates(now)
|
|
218
|
+
found = c[0] if c else None
|
|
219
|
+
out = {"found": found and {
|
|
220
|
+
"path": found["path"], "file": Path(found["path"]).name, "source": found["source"],
|
|
221
|
+
"name": NAMES[found["source"]],
|
|
222
|
+
"day": datetime.fromtimestamp(found["mtime"]).date().isoformat()},
|
|
223
|
+
"remind": not found and _remind(now)}
|
|
224
|
+
_cache.update(at=t, offer=out)
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def pick(path) -> dict:
|
|
229
|
+
"""The offered export at `path` (only a current candidate: never any path a page names)."""
|
|
230
|
+
from keepfold import chat_import
|
|
231
|
+
forget()
|
|
232
|
+
for c in candidates() if chat_import.enabled() else []:
|
|
233
|
+
if c["path"] == path:
|
|
234
|
+
return c
|
|
235
|
+
raise ValueError("That file is no longer offered. Import it from Settings, Add your "
|
|
236
|
+
"history.")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def mark(c: dict, was: str) -> None:
|
|
240
|
+
"""Remember the Add or Not this one answer for this path, mtime and size."""
|
|
241
|
+
stamp = datetime.now(UTC).isoformat()
|
|
242
|
+
|
|
243
|
+
def fn(s):
|
|
244
|
+
seen = {k: v for k, v in (s.get("seen") or {}).items() if k != c["path"]}
|
|
245
|
+
seen[c["path"]] = [c["mtime"], c["size"], was]
|
|
246
|
+
return {**s, "seen": seen,
|
|
247
|
+
**({"claude": stamp} if was == "added" and c["source"] == "claude" else {})}
|
|
248
|
+
_save(fn)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def later() -> None:
|
|
252
|
+
"""Hide the claude.ai reminder for DAYS days."""
|
|
253
|
+
until = (datetime.now(UTC) + timedelta(days=DAYS)).isoformat()
|
|
254
|
+
_save(lambda s: {**s, "later": until})
|
keepfold/app/hello.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The Private switch's check: Windows asks the user to verify with Windows Hello (face,
|
|
2
|
+
fingerprint or PIN), through `UserConsentVerifier` (winrt, called from the server process).
|
|
3
|
+
|
|
4
|
+
There is no Keepfold password. Without Windows Hello the switch says how to set it up: the Windows
|
|
5
|
+
password prompt (CredUI + LogonUser) is not used as a fallback, because it would hand the
|
|
6
|
+
account password to this process as an unwipeable Python string, fails for passwordless and
|
|
7
|
+
PIN-only Microsoft accounts, and its wrong tries count toward the account's lockout.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
MESSAGE = "Show private items in Keepfold"
|
|
18
|
+
SETUP = ("Set up Windows Hello (a PIN, face or fingerprint) in Settings > Accounts > Sign-in "
|
|
19
|
+
"options, then try again.")
|
|
20
|
+
HOST = "Credential Dialog Xaml Host" # the window class of Windows Hello's prompt
|
|
21
|
+
_busy = threading.Lock() # one prompt at a time
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _front(stop: threading.Event) -> None:
|
|
25
|
+
"""Bring Windows Hello's prompt in front of the app window (it can open behind it): this
|
|
26
|
+
process lets any process take the foreground, then raises the prompt once it appears."""
|
|
27
|
+
import ctypes
|
|
28
|
+
user32 = ctypes.windll.user32
|
|
29
|
+
user32.AllowSetForegroundWindow(-1) # ASFW_ANY
|
|
30
|
+
end = time.monotonic() + 5
|
|
31
|
+
while not stop.is_set() and time.monotonic() < end:
|
|
32
|
+
hwnd = user32.FindWindowW(HOST, None)
|
|
33
|
+
if hwnd:
|
|
34
|
+
user32.SetForegroundWindow(hwnd)
|
|
35
|
+
return
|
|
36
|
+
stop.wait(0.1)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def verify(message: str = MESSAGE) -> tuple[bool, str | None]:
|
|
40
|
+
"""(True, None) once Windows has verified the user; else (False, why) in words for them."""
|
|
41
|
+
if sys.platform != "win32":
|
|
42
|
+
return False, "The Private switch needs Windows Hello, which only Windows has."
|
|
43
|
+
try:
|
|
44
|
+
from winrt.windows.security.credentials.ui import (
|
|
45
|
+
UserConsentVerificationResult as Result,
|
|
46
|
+
)
|
|
47
|
+
from winrt.windows.security.credentials.ui import UserConsentVerifier as Verifier
|
|
48
|
+
from winrt.windows.security.credentials.ui import (
|
|
49
|
+
UserConsentVerifierAvailability as Availability,
|
|
50
|
+
)
|
|
51
|
+
except ImportError:
|
|
52
|
+
return False, ("This copy of Keepfold has no Windows Hello support; reinstall Keepfold "
|
|
53
|
+
"to add it.")
|
|
54
|
+
if not _busy.acquire(blocking=False):
|
|
55
|
+
return False, "Windows Hello is already asking; answer that prompt first."
|
|
56
|
+
stop = threading.Event()
|
|
57
|
+
try:
|
|
58
|
+
async def ask():
|
|
59
|
+
if await Verifier.check_availability_async() != Availability.AVAILABLE:
|
|
60
|
+
return None
|
|
61
|
+
threading.Thread(target=_front, args=(stop,), daemon=True,
|
|
62
|
+
name="keepfold-hello-front").start()
|
|
63
|
+
return await Verifier.request_verification_async(message)
|
|
64
|
+
r = asyncio.run(ask())
|
|
65
|
+
except Exception as e: # noqa: BLE001 (a winrt call failed: OSError with its HRESULT)
|
|
66
|
+
return False, f"Windows Hello did not answer ({type(e).__name__})."
|
|
67
|
+
finally:
|
|
68
|
+
stop.set()
|
|
69
|
+
_busy.release()
|
|
70
|
+
if r is None or r in (Result.NOT_CONFIGURED_FOR_USER, Result.DEVICE_NOT_PRESENT):
|
|
71
|
+
return False, SETUP
|
|
72
|
+
if r == Result.VERIFIED:
|
|
73
|
+
return True, None
|
|
74
|
+
return False, {Result.CANCELED: "Cancelled; private items stay hidden.",
|
|
75
|
+
Result.DISABLED_BY_POLICY: "Windows Hello is turned off on this computer by "
|
|
76
|
+
"its administrator.",
|
|
77
|
+
Result.DEVICE_BUSY: "Windows Hello is busy; try again in a moment.",
|
|
78
|
+
Result.RETRIES_EXHAUSTED: "Too many tries; try again later.",
|
|
79
|
+
}.get(r, "Windows did not verify you; private items stay hidden.")
|
keepfold/app/launch.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""The no-console entry points of the Windows install (gui-scripts in pyproject.toml).
|
|
2
|
+
|
|
3
|
+
The installer's shortcut runs `Keepfold.exe -m keepfold.app.launch` (installer/app_exe.py: a copy
|
|
4
|
+
of pythonw named and drawn as Keepfold, so Windows shows Keepfold, not Python); `keepfold-app` runs
|
|
5
|
+
the same, handing over to that Keepfold.exe when it sits beside its Python. It is the desktop
|
|
6
|
+
app (desktop.py: its own window and a tray icon; `--hidden`, as Start with Windows runs it,
|
|
7
|
+
starts in the tray), or, when one already runs (~/.keepfold/app.json), that app's window
|
|
8
|
+
brought up. `keepfold-receiver` is Start at login's browse receiver (the background history
|
|
9
|
+
import), as `keepfold browse serve` runs it. With no console (a GUI script's sys.stdout and
|
|
10
|
+
sys.stderr are None) their output goes to ~/.keepfold/logs/, and a failed app start says so in a
|
|
11
|
+
message box with the log's path."""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import traceback
|
|
20
|
+
import webbrowser
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
LOG_MAX = 1_000_000 # bytes; a bigger log starts over
|
|
24
|
+
APP_EXE = "Keepfold.exe" # installer/app_exe.py NAME
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def installed_app() -> Path | None:
|
|
28
|
+
"""The install's Keepfold.exe (the tool venv's app\\, installer/app_exe.py), else None (a
|
|
29
|
+
dev install)."""
|
|
30
|
+
exe = Path(sys.prefix) / "app" / APP_EXE
|
|
31
|
+
return exe if exe.is_file() else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_KEY = re.compile(r"\?t=[\w-]+")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _log_to(name: str) -> Path:
|
|
38
|
+
log = Path.home() / ".keepfold" / "logs" / name
|
|
39
|
+
if sys.stdout is None or sys.stderr is None:
|
|
40
|
+
log.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
big = log.is_file() and log.stat().st_size > LOG_MAX
|
|
42
|
+
sys.stdout = sys.stderr = open(log, "w" if big else "a", encoding="utf-8", buffering=1) # noqa: SIM115
|
|
43
|
+
return log
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _alert(text: str) -> None: # tests replace this
|
|
47
|
+
if sys.platform == "win32":
|
|
48
|
+
import ctypes
|
|
49
|
+
ctypes.windll.user32.MessageBoxW(None, text, "Keepfold", 0x10) # MB_ICONERROR
|
|
50
|
+
else:
|
|
51
|
+
print(text, file=sys.stderr)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main() -> None:
|
|
55
|
+
from keepfold import taint
|
|
56
|
+
taint.cap_blas()
|
|
57
|
+
log = None
|
|
58
|
+
hidden = "--hidden" in sys.argv[1:]
|
|
59
|
+
from keepfold import migrate # before the log: ~/.cortex moves while ~/.keepfold is missing
|
|
60
|
+
if why := migrate.launch():
|
|
61
|
+
_alert(f"Keepfold could not start yet.\n\n{why}")
|
|
62
|
+
raise SystemExit(2)
|
|
63
|
+
try:
|
|
64
|
+
log = _log_to("app.log")
|
|
65
|
+
exe = installed_app()
|
|
66
|
+
if exe and Path(sys.executable).resolve() != exe.resolve():
|
|
67
|
+
# an older shortcut or Start with Windows value: the window must belong to Keepfold.exe
|
|
68
|
+
from keepfold._proc import NO_WINDOW
|
|
69
|
+
subprocess.Popen([str(exe), "-m", "keepfold.app.launch", *sys.argv[1:]],
|
|
70
|
+
creationflags=NO_WINDOW)
|
|
71
|
+
return
|
|
72
|
+
from keepfold.app import server
|
|
73
|
+
if url := server.running_url(): # double-clicked again: the open app, not a second one
|
|
74
|
+
if hidden: # Start with Windows while it runs already
|
|
75
|
+
return
|
|
76
|
+
print("Keepfold app: already running; showing it")
|
|
77
|
+
if sys.platform == "win32": # the running app may bring its window to the front
|
|
78
|
+
import ctypes
|
|
79
|
+
ctypes.windll.user32.AllowSetForegroundWindow(-1) # ASFW_ANY
|
|
80
|
+
if not server.show_window(url): # the browser app has no window
|
|
81
|
+
webbrowser.open(url)
|
|
82
|
+
return
|
|
83
|
+
# clients.keepfold_command() finds `keepfold` on PATH for the AI-app configs; a shortcut
|
|
84
|
+
# can start before PATH has the installer's bin folder (with `keepfold.exe`), next to the
|
|
85
|
+
# keepfold-app.exe that started us in a dev install
|
|
86
|
+
from keepfold import update
|
|
87
|
+
d = update.install_dir()
|
|
88
|
+
here = str(d / "bin") if d else str(Path(sys.argv[0]).resolve().parent)
|
|
89
|
+
os.environ["PATH"] = here + os.pathsep + os.environ.get("PATH", "")
|
|
90
|
+
from keepfold.app import desktop
|
|
91
|
+
# the log keeps the address, never the key (?t=): the page holds it, the log may be shared
|
|
92
|
+
desktop.run(taint._vault_root(), hidden=hidden, echo=lambda s: print(_KEY.sub("", s)))
|
|
93
|
+
except Exception: # noqa: BLE001 (a double-click must never fail silently)
|
|
94
|
+
traceback.print_exc()
|
|
95
|
+
_alert("Keepfold could not start.\n\nWhat went wrong is written in "
|
|
96
|
+
f"{log or Path.home() / '.keepfold' / 'logs' / 'app.log'}")
|
|
97
|
+
raise SystemExit(1) from None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def receiver() -> None:
|
|
101
|
+
"""`keepfold-receiver [--vault V]`: `keepfold browse serve` (the background import) with no
|
|
102
|
+
console."""
|
|
103
|
+
from keepfold import taint
|
|
104
|
+
taint.cap_blas()
|
|
105
|
+
from keepfold import migrate
|
|
106
|
+
if migrate.launch(): # an old Cortex still holds the files: the next login tries again
|
|
107
|
+
raise SystemExit(2)
|
|
108
|
+
_log_to("receiver.log")
|
|
109
|
+
from keepfold import cli
|
|
110
|
+
cli.app(["browse", "serve", *sys.argv[1:]], prog_name="keepfold")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
if __name__ == "__main__": # Keepfold.exe -m keepfold.app.launch [--hidden]
|
|
114
|
+
main()
|
keepfold/app/news.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""What's new: the card Status shows once after an update. The text ships in
|
|
2
|
+
assets/whats_new.json (version -> {items, do}); the last version shown is `app.whats_new_seen`
|
|
3
|
+
in ~/.keepfold/config.yaml, never in the vault."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from keepfold import update
|
|
11
|
+
from keepfold.app import status
|
|
12
|
+
|
|
13
|
+
NEWS = Path(__file__).resolve().parents[1] / "assets" / "whats_new.json"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _v(s) -> tuple[int, ...] | None:
|
|
17
|
+
try:
|
|
18
|
+
return update.parse_version(s)
|
|
19
|
+
except update.UpdateError:
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _entries() -> dict:
|
|
24
|
+
return json.loads(NEWS.read_text(encoding="utf-8"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _seen() -> tuple[int, ...] | None:
|
|
28
|
+
app = status.config().get("app")
|
|
29
|
+
return _v(app.get("whats_new_seen")) if isinstance(app, dict) else None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def record(version: str | None = None) -> None:
|
|
33
|
+
"""Remember `version` (the running one by default) as shown."""
|
|
34
|
+
from keepfold import taint
|
|
35
|
+
seen = version or update.current()
|
|
36
|
+
taint.write_config(lambda cfg: {"app": {
|
|
37
|
+
**(cfg["app"] if isinstance(cfg.get("app"), dict) else {}), "whats_new_seen": seen}})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# the last version without this card: an existing user with no record updated from it or earlier
|
|
41
|
+
BEFORE_NEWS = "0.2.1"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def start() -> None:
|
|
45
|
+
"""On app start, with no readable record: a fresh install (no vault set yet) records this
|
|
46
|
+
version silently; an existing user came from BEFORE_NEWS or earlier, so sees what is new.
|
|
47
|
+
`keepfold init` calls this before it first sets a vault, so a CLI setup counts as fresh."""
|
|
48
|
+
if _seen() is None and _v(update.current()):
|
|
49
|
+
record(BEFORE_NEWS if status.config().get("vault") else None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def card(current: str | None = None) -> dict:
|
|
53
|
+
"""{"show": the entries after the last seen up to the running version, newest first,
|
|
54
|
+
"current": this version's entry or None}. Nothing remembered shows nothing."""
|
|
55
|
+
cur = current or update.current()
|
|
56
|
+
cv, seen, news = _v(cur), _seen(), _entries()
|
|
57
|
+
keyed = sorted(((_v(k), k) for k in news if _v(k)), reverse=True)
|
|
58
|
+
show = [{"version": k, **news[k]} for v, k in keyed
|
|
59
|
+
if cv and seen and update.newer(v, seen) and not update.newer(v, cv)]
|
|
60
|
+
return {"show": show, "current": {"version": cur, **news[cur]} if cur in news else None}
|