bouquin 0.1.10__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.
bouquin/__init__.py ADDED
File without changes
bouquin/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .main import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
bouquin/db.py ADDED
@@ -0,0 +1,499 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import html
5
+ import json
6
+ import os
7
+
8
+ from dataclasses import dataclass
9
+ from markdownify import markdownify as md
10
+ from pathlib import Path
11
+ from sqlcipher3 import dbapi2 as sqlite
12
+ from typing import List, Sequence, Tuple
13
+
14
+ Entry = Tuple[str, str]
15
+
16
+
17
+ @dataclass
18
+ class DBConfig:
19
+ path: Path
20
+ key: str
21
+ idle_minutes: int = 15 # 0 = never lock
22
+ theme: str = "system"
23
+ move_todos: bool = False
24
+
25
+
26
+ class DBManager:
27
+ def __init__(self, cfg: DBConfig):
28
+ self.cfg = cfg
29
+ self.conn: sqlite.Connection | None = None
30
+
31
+ def connect(self) -> bool:
32
+ """
33
+ Open, decrypt and install schema on the database.
34
+ """
35
+ # Ensure parent dir exists
36
+ self.cfg.path.parent.mkdir(parents=True, exist_ok=True)
37
+ self.conn = sqlite.connect(str(self.cfg.path))
38
+ self.conn.row_factory = sqlite.Row
39
+ cur = self.conn.cursor()
40
+ cur.execute(f"PRAGMA key = '{self.cfg.key}';")
41
+ cur.execute("PRAGMA foreign_keys = ON;")
42
+ cur.execute("PRAGMA journal_mode = WAL;").fetchone()
43
+ try:
44
+ self._integrity_ok()
45
+ except Exception:
46
+ self.conn.close()
47
+ self.conn = None
48
+ return False
49
+ self._ensure_schema()
50
+ return True
51
+
52
+ def _integrity_ok(self) -> bool:
53
+ """
54
+ Runs the cipher_integrity_check PRAGMA on the database.
55
+ """
56
+ cur = self.conn.cursor()
57
+ cur.execute("PRAGMA cipher_integrity_check;")
58
+ rows = cur.fetchall()
59
+
60
+ # OK: nothing returned
61
+ if not rows:
62
+ return
63
+
64
+ # Not OK: rows of problems returned
65
+ details = "; ".join(str(r[0]) for r in rows if r and r[0] is not None)
66
+ raise sqlite.IntegrityError(
67
+ "SQLCipher integrity check failed"
68
+ + (f": {details}" if details else f" ({len(rows)} issue(s) reported)")
69
+ )
70
+
71
+ def _ensure_schema(self) -> None:
72
+ """
73
+ Install the expected schema on the database.
74
+ We also handle upgrades here.
75
+ """
76
+ cur = self.conn.cursor()
77
+ # Always keep FKs on
78
+ cur.execute("PRAGMA foreign_keys = ON;")
79
+
80
+ # Create new versioned schema if missing (< 0.1.5)
81
+ cur.executescript(
82
+ """
83
+ CREATE TABLE IF NOT EXISTS pages (
84
+ date TEXT PRIMARY KEY, -- yyyy-MM-dd
85
+ current_version_id INTEGER,
86
+ FOREIGN KEY(current_version_id) REFERENCES versions(id) ON DELETE SET NULL
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS versions (
90
+ id INTEGER PRIMARY KEY,
91
+ date TEXT NOT NULL, -- FK to pages.date
92
+ version_no INTEGER NOT NULL, -- 1,2,3… per date
93
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
94
+ note TEXT,
95
+ content TEXT NOT NULL,
96
+ FOREIGN KEY(date) REFERENCES pages(date) ON DELETE CASCADE
97
+ );
98
+
99
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_versions_date_ver ON versions(date, version_no);
100
+ CREATE INDEX IF NOT EXISTS ix_versions_date_created ON versions(date, created_at);
101
+ """
102
+ )
103
+
104
+ # If < 0.1.5 'entries' table exists and nothing has been migrated yet, try to migrate.
105
+ pre_0_1_5 = cur.execute(
106
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='entries';"
107
+ ).fetchone()
108
+ pages_empty = cur.execute("SELECT 1 FROM pages LIMIT 1;").fetchone() is None
109
+
110
+ if pre_0_1_5 and pages_empty:
111
+ # Seed pages and versions (all as version 1)
112
+ cur.execute("INSERT OR IGNORE INTO pages(date) SELECT date FROM entries;")
113
+ cur.execute(
114
+ "INSERT INTO versions(date, version_no, content) "
115
+ "SELECT date, 1, content FROM entries;"
116
+ )
117
+ # Point head to v1 for each page
118
+ cur.execute(
119
+ """
120
+ UPDATE pages
121
+ SET current_version_id = (
122
+ SELECT v.id FROM versions v
123
+ WHERE v.date = pages.date AND v.version_no = 1
124
+ );
125
+ """
126
+ )
127
+ cur.execute("DROP TABLE IF EXISTS entries;")
128
+ self.conn.commit()
129
+
130
+ def rekey(self, new_key: str) -> None:
131
+ """
132
+ Change the SQLCipher passphrase in-place, then reopen the connection
133
+ with the new key to verify.
134
+ """
135
+ if self.conn is None:
136
+ raise RuntimeError("Database is not connected")
137
+ cur = self.conn.cursor()
138
+ # Change the encryption key of the currently open database
139
+ cur.execute(f"PRAGMA rekey = '{new_key}';").fetchone()
140
+ self.conn.commit()
141
+
142
+ # Close and reopen with the new key to verify and restore PRAGMAs
143
+ self.conn.close()
144
+ self.conn = None
145
+ self.cfg.key = new_key
146
+ if not self.connect():
147
+ raise sqlite.Error("Re-open failed after rekey")
148
+
149
+ def get_entry(self, date_iso: str) -> str:
150
+ """
151
+ Get a single entry by its date.
152
+ """
153
+ cur = self.conn.cursor()
154
+ row = cur.execute(
155
+ """
156
+ SELECT v.content
157
+ FROM pages p
158
+ JOIN versions v ON v.id = p.current_version_id
159
+ WHERE p.date = ?;
160
+ """,
161
+ (date_iso,),
162
+ ).fetchone()
163
+ return row[0] if row else ""
164
+
165
+ def search_entries(self, text: str) -> list[str]:
166
+ """
167
+ Search for entries by term. This only works against the latest
168
+ version of the page.
169
+ """
170
+ cur = self.conn.cursor()
171
+ pattern = f"%{text}%"
172
+ rows = cur.execute(
173
+ """
174
+ SELECT p.date, v.content
175
+ FROM pages AS p
176
+ JOIN versions AS v
177
+ ON v.id = p.current_version_id
178
+ WHERE TRIM(v.content) <> ''
179
+ AND v.content LIKE LOWER(?) ESCAPE '\\'
180
+ ORDER BY p.date DESC;
181
+ """,
182
+ (pattern,),
183
+ ).fetchall()
184
+ return [(r[0], r[1]) for r in rows]
185
+
186
+ def dates_with_content(self) -> list[str]:
187
+ """
188
+ Find all entries and return the dates of them.
189
+ This is used to mark the calendar days in bold if they contain entries.
190
+ """
191
+ cur = self.conn.cursor()
192
+ rows = cur.execute(
193
+ """
194
+ SELECT p.date
195
+ FROM pages p
196
+ JOIN versions v ON v.id = p.current_version_id
197
+ WHERE TRIM(v.content) <> ''
198
+ ORDER BY p.date;
199
+ """
200
+ ).fetchall()
201
+ return [r[0] for r in rows]
202
+
203
+ # ------------------------- Versioning logic here ------------------------#
204
+ def save_new_version(
205
+ self,
206
+ date_iso: str,
207
+ content: str,
208
+ note: str | None = None,
209
+ set_current: bool = True,
210
+ ) -> tuple[int, int]:
211
+ """
212
+ Append a new version for this date. Returns (version_id, version_no).
213
+ If set_current=True, flips the page head to this new version.
214
+ """
215
+ if self.conn is None:
216
+ raise RuntimeError("Database is not connected")
217
+ with self.conn: # transaction
218
+ cur = self.conn.cursor()
219
+ # Ensure page row exists
220
+ cur.execute("INSERT OR IGNORE INTO pages(date) VALUES (?);", (date_iso,))
221
+ # Next version number
222
+ row = cur.execute(
223
+ "SELECT COALESCE(MAX(version_no), 0) AS maxv FROM versions WHERE date=?;",
224
+ (date_iso,),
225
+ ).fetchone()
226
+ next_ver = int(row["maxv"]) + 1
227
+ # Insert the version
228
+ cur.execute(
229
+ "INSERT INTO versions(date, version_no, content, note) "
230
+ "VALUES (?,?,?,?);",
231
+ (date_iso, next_ver, content, note),
232
+ )
233
+ ver_id = cur.lastrowid
234
+ if set_current:
235
+ cur.execute(
236
+ "UPDATE pages SET current_version_id=? WHERE date=?;",
237
+ (ver_id, date_iso),
238
+ )
239
+ return ver_id, next_ver
240
+
241
+ def list_versions(self, date_iso: str) -> list[dict]:
242
+ """
243
+ Returns history for a given date (newest first), including which one is current.
244
+ Each item: {id, version_no, created_at, note, is_current}
245
+ """
246
+ cur = self.conn.cursor()
247
+ rows = cur.execute(
248
+ """
249
+ SELECT v.id, v.version_no, v.created_at, v.note,
250
+ CASE WHEN v.id = p.current_version_id THEN 1 ELSE 0 END AS is_current
251
+ FROM versions v
252
+ LEFT JOIN pages p ON p.date = v.date
253
+ WHERE v.date = ?
254
+ ORDER BY v.version_no DESC;
255
+ """,
256
+ (date_iso,),
257
+ ).fetchall()
258
+ return [dict(r) for r in rows]
259
+
260
+ def get_version(
261
+ self,
262
+ *,
263
+ date_iso: str | None = None,
264
+ version_no: int | None = None,
265
+ version_id: int | None = None,
266
+ ) -> dict | None:
267
+ """
268
+ Fetch a specific version by (date, version_no) OR by version_id.
269
+ Returns a dict with keys: id, date, version_no, created_at, note, content.
270
+ """
271
+ cur = self.conn.cursor()
272
+ if version_id is not None:
273
+ row = cur.execute(
274
+ "SELECT id, date, version_no, created_at, note, content "
275
+ "FROM versions WHERE id=?;",
276
+ (version_id,),
277
+ ).fetchone()
278
+ else:
279
+ if date_iso is None or version_no is None:
280
+ raise ValueError(
281
+ "Provide either version_id OR (date_iso and version_no)"
282
+ )
283
+ row = cur.execute(
284
+ "SELECT id, date, version_no, created_at, note, content "
285
+ "FROM versions WHERE date=? AND version_no=?;",
286
+ (date_iso, version_no),
287
+ ).fetchone()
288
+ return dict(row) if row else None
289
+
290
+ def revert_to_version(
291
+ self,
292
+ date_iso: str,
293
+ *,
294
+ version_no: int | None = None,
295
+ version_id: int | None = None,
296
+ ) -> None:
297
+ """
298
+ Point the page head (pages.current_version_id) to an existing version.
299
+ Fast revert: no content is rewritten.
300
+ """
301
+ if self.conn is None:
302
+ raise RuntimeError("Database is not connected")
303
+ cur = self.conn.cursor()
304
+
305
+ if version_id is None:
306
+ if version_no is None:
307
+ raise ValueError("Provide version_no or version_id")
308
+ row = cur.execute(
309
+ "SELECT id FROM versions WHERE date=? AND version_no=?;",
310
+ (date_iso, version_no),
311
+ ).fetchone()
312
+ if row is None:
313
+ raise ValueError("Version not found for this date")
314
+ version_id = int(row["id"])
315
+ else:
316
+ # Ensure that version_id belongs to the given date
317
+ row = cur.execute(
318
+ "SELECT date FROM versions WHERE id=?;", (version_id,)
319
+ ).fetchone()
320
+ if row is None or row["date"] != date_iso:
321
+ raise ValueError("version_id does not belong to the given date")
322
+
323
+ with self.conn:
324
+ cur.execute(
325
+ "UPDATE pages SET current_version_id=? WHERE date=?;",
326
+ (version_id, date_iso),
327
+ )
328
+
329
+ # ------------------------- Export logic here ------------------------#
330
+ def get_all_entries(self) -> List[Entry]:
331
+ """
332
+ Get all entries. Used for exports.
333
+ """
334
+ cur = self.conn.cursor()
335
+ rows = cur.execute(
336
+ """
337
+ SELECT p.date, v.content
338
+ FROM pages p
339
+ JOIN versions v ON v.id = p.current_version_id
340
+ ORDER BY p.date;
341
+ """
342
+ ).fetchall()
343
+ return [(r[0], r[1]) for r in rows]
344
+
345
+ def export_json(
346
+ self, entries: Sequence[Entry], file_path: str, pretty: bool = True
347
+ ) -> None:
348
+ """
349
+ Export to json.
350
+ """
351
+ data = [{"date": d, "content": c} for d, c in entries]
352
+ with open(file_path, "w", encoding="utf-8") as f:
353
+ if pretty:
354
+ json.dump(data, f, ensure_ascii=False, indent=2)
355
+ else:
356
+ json.dump(data, f, ensure_ascii=False, separators=(",", ":"))
357
+
358
+ def export_csv(self, entries: Sequence[Entry], file_path: str) -> None:
359
+ # utf-8-sig adds a BOM so Excel opens as UTF-8 by default.
360
+ with open(file_path, "w", encoding="utf-8-sig", newline="") as f:
361
+ writer = csv.writer(f)
362
+ writer.writerow(["date", "content"]) # header
363
+ writer.writerows(entries)
364
+
365
+ def export_txt(
366
+ self,
367
+ entries: Sequence[Entry],
368
+ file_path: str,
369
+ separator: str = "\n\n— — — — —\n\n",
370
+ strip_html: bool = True,
371
+ ) -> None:
372
+ import re, html as _html
373
+
374
+ # Precompiled patterns
375
+ STYLE_SCRIPT_RE = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
376
+ COMMENT_RE = re.compile(r"<!--.*?-->", re.S)
377
+ BR_RE = re.compile(r"(?i)<br\\s*/?>")
378
+ BLOCK_END_RE = re.compile(r"(?i)</(p|div|section|article|li|h[1-6])\\s*>")
379
+ TAG_RE = re.compile(r"<[^>]+>")
380
+ WS_ENDS_RE = re.compile(r"[ \\t]+\\n")
381
+ MULTINEWLINE_RE = re.compile(r"\\n{3,}")
382
+
383
+ def _strip(s: str) -> str:
384
+ # 1) Remove <style> and <script> blocks *including their contents*
385
+ s = STYLE_SCRIPT_RE.sub("", s)
386
+ # 2) Remove HTML comments
387
+ s = COMMENT_RE.sub("", s)
388
+ # 3) Turn some block-ish boundaries into newlines before removing tags
389
+ s = BR_RE.sub("\n", s)
390
+ s = BLOCK_END_RE.sub("\n", s)
391
+ # 4) Drop remaining tags
392
+ s = TAG_RE.sub("", s)
393
+ # 5) Unescape entities (&nbsp; etc.)
394
+ s = _html.unescape(s)
395
+ # 6) Tidy whitespace
396
+ s = WS_ENDS_RE.sub("\n", s)
397
+ s = MULTINEWLINE_RE.sub("\n\n", s)
398
+ return s.strip()
399
+
400
+ with open(file_path, "w", encoding="utf-8") as f:
401
+ for i, (d, c) in enumerate(entries):
402
+ body = _strip(c) if strip_html else c
403
+ f.write(f"{d}\n{body}\n")
404
+ if i < len(entries) - 1:
405
+ f.write(separator)
406
+
407
+ def export_html(
408
+ self, entries: Sequence[Entry], file_path: str, title: str = "Bouquin export"
409
+ ) -> None:
410
+ parts = [
411
+ "<!doctype html>",
412
+ '<html lang="en">',
413
+ '<meta charset="utf-8">',
414
+ f"<title>{html.escape(title)}</title>",
415
+ "<style>body{font:16px/1.5 system-ui,Segoe UI,Roboto,Helvetica,Arial,sans-serif;padding:24px;max-width:900px;margin:auto;}",
416
+ "article{padding:16px 0;border-bottom:1px solid #ddd;} time{font-weight:600;color:#333;} section{margin-top:8px;}</style>",
417
+ "<body>",
418
+ f"<h1>{html.escape(title)}</h1>",
419
+ ]
420
+ for d, c in entries:
421
+ parts.append(
422
+ f"<article><header><time>{html.escape(d)}</time></header><section>{c}</section></article>"
423
+ )
424
+ parts.append("</body></html>")
425
+
426
+ with open(file_path, "w", encoding="utf-8") as f:
427
+ f.write("\n".join(parts))
428
+
429
+ def export_markdown(
430
+ self, entries: Sequence[Entry], file_path: str, title: str = "Bouquin export"
431
+ ) -> None:
432
+ parts = [
433
+ "<!doctype html>",
434
+ '<html lang="en">',
435
+ "<body>",
436
+ f"<h1>{html.escape(title)}</h1>",
437
+ ]
438
+ for d, c in entries:
439
+ parts.append(
440
+ f"<article><header><time>{html.escape(d)}</time></header><section>{c}</section></article>"
441
+ )
442
+ parts.append("</body></html>")
443
+
444
+ # Convert html to markdown
445
+ md_items = []
446
+ for item in parts:
447
+ md_items.append(md(item, heading_style="ATX"))
448
+
449
+ with open(file_path, "w", encoding="utf-8") as f:
450
+ f.write("\n".join(md_items))
451
+
452
+ def export_sql(self, file_path: str) -> None:
453
+ """
454
+ Exports the encrypted database as plaintext SQL.
455
+ """
456
+ cur = self.conn.cursor()
457
+ cur.execute(f"ATTACH DATABASE '{file_path}' AS plaintext KEY '';")
458
+ cur.execute("SELECT sqlcipher_export('plaintext')")
459
+ cur.execute("DETACH DATABASE plaintext")
460
+
461
+ def export_sqlcipher(self, file_path: str) -> None:
462
+ """
463
+ Exports the encrypted database as an encrypted database with the same key.
464
+ Intended for Bouquin-compatible backups.
465
+ """
466
+ cur = self.conn.cursor()
467
+ cur.execute(f"ATTACH DATABASE '{file_path}' AS backup KEY '{self.cfg.key}'")
468
+ cur.execute("SELECT sqlcipher_export('backup')")
469
+ cur.execute("DETACH DATABASE backup")
470
+
471
+ def export_by_extension(self, file_path: str) -> None:
472
+ entries = self.get_all_entries()
473
+ ext = os.path.splitext(file_path)[1].lower()
474
+
475
+ if ext == ".json":
476
+ self.export_json(entries, file_path)
477
+ elif ext == ".csv":
478
+ self.export_csv(entries, file_path)
479
+ elif ext == ".txt":
480
+ self.export_txt(entries, file_path)
481
+ elif ext in {".html", ".htm"}:
482
+ self.export_html(entries, file_path)
483
+ else:
484
+ raise ValueError(f"Unsupported extension: {ext}")
485
+
486
+ def compact(self) -> None:
487
+ """
488
+ Runs VACUUM on the db.
489
+ """
490
+ try:
491
+ cur = self.conn.cursor()
492
+ cur.execute("VACUUM")
493
+ except Exception as e:
494
+ print(f"Error: {e}")
495
+
496
+ def close(self) -> None:
497
+ if self.conn is not None:
498
+ self.conn.close()
499
+ self.conn = None