#!/usr/bin/env python3 """Экспорт заметок Apple Notes в HTML или текст.""" from __future__ import annotations import argparse import html import json import re import subprocess import sys from html.parser import HTMLParser from pathlib import Path APPLESCRIPT = """ set output to "" tell application "Notes" repeat with noteRef in notes set output to output & "@@NOTE@@" & linefeed set output to output & "TITLE:" & (name of noteRef) & linefeed set output to output & "MODIFIED:" & (modification date of noteRef as string) & linefeed set output to output & "BODY:" & (body of noteRef) & linefeed end repeat end tell return output """ class TextExtractor(HTMLParser): def __init__(self) -> None: super().__init__() self.parts: list[str] = [] def handle_data(self, data: str) -> None: self.parts.append(data) def text(self) -> str: return "".join(self.parts) def strip_html(value: str) -> str: parser = TextExtractor() parser.feed(value) text = html.unescape(parser.text()) lines = [line.rstrip() for line in text.splitlines()] return "\n".join(line for line in lines if line.strip()) def safe_name(title: str) -> str: name = re.sub(r"[^\w\-. ]+", "_", title, flags=re.UNICODE) name = re.sub(r"\s+", "_", name).strip("._-") return (name or "note")[:80] def unique_path(directory: Path, stem: str, suffix: str) -> Path: candidate = directory / f"{stem}{suffix}" if not candidate.exists(): return candidate for number in range(1, 10000): candidate = directory / f"{stem}-{number}{suffix}" if not candidate.exists(): return candidate raise RuntimeError("Не удалось подобрать имя файла") def parse_notes(output: str) -> list[dict]: notes = [] for block in output.split("@@NOTE@@"): block = block.strip("\n") if not block: continue title = "Без названия" modified = "" body = block lines = block.splitlines() if lines and lines[0].startswith("TITLE:"): title = lines[0][len("TITLE:"):].strip() or title lines = lines[1:] if lines and lines[0].startswith("MODIFIED:"): modified = lines[0][len("MODIFIED:"):].strip() lines = lines[1:] body = "\n".join(lines) if body.startswith("BODY:"): body = body[len("BODY:"):].lstrip("\n") notes.append({"title": title, "modified": modified, "body": body}) return notes def main() -> int: parser = argparse.ArgumentParser(description="Экспорт заметок Apple Notes") parser.add_argument("--output", type=Path, default=Path("notes-export")) parser.add_argument("--format", choices=("html", "txt"), default="html") parser.add_argument("--force", action="store_true", help="Перезаписывать совпадающие имена") args = parser.parse_args() result = subprocess.run( ["osascript", "-e", APPLESCRIPT], capture_output=True, text=True, check=False, ) if result.returncode != 0: print("Не удалось прочитать заметки.", file=sys.stderr) print(result.stderr.strip(), file=sys.stderr) return 2 notes = parse_notes(result.stdout) output_dir = args.output.expanduser().resolve() output_dir.mkdir(parents=True, exist_ok=True) suffix = ".html" if args.format == "html" else ".txt" saved = 0 for note in notes: stem = safe_name(note["title"]) path = output_dir / f"{stem}{suffix}" if path.exists() and not args.force: path = unique_path(output_dir, stem, suffix) if args.format == "html": content = ( "\n" "\n" f"