Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ didn't decode had no body at all (one attachment-only, one empty).

**Scoping is a safety property, not a preference.** `~/Library/Messages/chat.db`
holds every conversation on the machine — family, friends, personal logistics.
There is no code path here that reads across threads: `ChatStore.read_thread` requires a
There is no code path here that reads across threads: `ChatStore.read` requires a
chat identifier, and the CLI exits non-zero without one. A rule written in prose
depends on the reader choosing to follow it. This one does not.

Expand Down Expand Up @@ -251,7 +251,10 @@ Or as a module, if you have a clone but no install: `python3 imsgread.py
from imsgread import DEFAULT_DB, ChatStore

store = ChatStore(DEFAULT_DB) # no default path: reaching real messages is a choice
for m in store.read_thread("+15555550123", limit=20):
transcript = store.read("+15555550123", limit=20)
if transcript.note: # set when this Mac may be missing messages
print(transcript.note)
for m in transcript.messages: # newest first
print(m.date, "me" if m.from_me else "them", m.text)
```

Expand All @@ -269,7 +272,7 @@ from imsgread import ContactBook
book = ContactBook.open() # contacts.toml, found as described above
friend = book.resolve(contact="friend") # Recipient: identifier, name, standing marker
print(friend.display) # "friend" -- never the number
store.read_thread(friend.identifier, name_for=book.label) # group senders by name
store.read(friend.identifier, name_for=book.label) # group senders by name
```

Every database failure (missing file, no Full Disk Access, corrupt file) is a
Expand Down
46 changes: 28 additions & 18 deletions imsgread.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,22 @@ def staleness_note(
return None


@dataclass(frozen=True)
class Transcript:
"""One thread as read: messages newest first, and a note (or None) saying
why the result may not be the whole story."""

messages: list[Message]
note: str | None = None

def render(self, text: bool = False, oldest_first: bool = False) -> str:
"""JSON (the default, for programs) or one line per message."""
ordered = self.messages[::-1] if oldest_first else self.messages
if text:
return "\n".join(m.render() for m in ordered)
return json.dumps([asdict(m) for m in ordered], indent=2)


@dataclass(frozen=True)
class Delivery:
"""What became of a message after Messages accepted it.
Expand Down Expand Up @@ -867,14 +883,16 @@ def chat(self, chat_id: str) -> Chat:
with _connect(self.path) as conn:
return _chat(conn, chat_id)

def read_thread(
def read(
self,
chat_id: str,
limit: int = 50,
include_empty: bool = False,
name_for: Callable[[str], str] = mask_handle,
) -> list[Message]:
"""Read the most recent messages for one chat identifier, newest first.
now: datetime | None = None,
) -> "Transcript":
"""The most recent messages for one chat identifier, newest first,
with a note when they may be incomplete.

`chat_id` is required and is always bound as a parameter -- there is no
code path that reads across threads.
Expand Down Expand Up @@ -913,7 +931,7 @@ def read_thread(
),
)
)
return out
return Transcript(out, staleness_note(out, self.updated(), now))


# --------------------------------------------------------------------------
Expand Down Expand Up @@ -1403,7 +1421,7 @@ def main(argv: list[str] | None = None, terminal: Terminal | None = None) -> int
book = _open_book(args)
recipient = book.resolve(args.chat, args.contact)
store = ChatStore(args.db)
messages = store.read_thread(
transcript = store.read(
recipient.identifier,
limit=args.limit,
include_empty=args.include_empty,
Expand All @@ -1415,19 +1433,11 @@ def main(argv: list[str] | None = None, terminal: Terminal | None = None) -> int

# stderr, so JSON on stdout stays parseable and the note still reaches
# whoever reads the output.
note = staleness_note(messages, store.updated())
if note:
print(note, file=sys.stderr)

if args.oldest_first:
messages.reverse()

if args.text:
for m in messages:
print(m.render())
else:
json.dump([asdict(m) for m in messages], sys.stdout, indent=2)
sys.stdout.write("\n")
if transcript.note:
print(transcript.note, file=sys.stderr)
rendered = transcript.render(text=args.text, oldest_first=args.oldest_first)
if rendered:
print(rendered)
return 0


Expand Down
64 changes: 45 additions & 19 deletions test_imsgread.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,9 @@ def test_apple_time_of_zero_is_none():
# scoping -- the safety property
# --------------------------------------------------------------------------

def test_read_thread_refuses_empty_chat_id():
def test_read_refuses_empty_chat_id():
with pytest.raises(ScopeError):
imsgread.ChatStore(Path("/nonexistent")).read_thread("")
imsgread.ChatStore(Path("/nonexistent")).read("").messages


# --------------------------------------------------------------------------
Expand Down Expand Up @@ -208,42 +208,42 @@ def add(rowid, chat, date, from_me, text, blob, attach=0, handle_id=None):


def test_reads_only_the_requested_thread(db):
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
assert all("OTHER THREAD" != (m.text or "") for m in msgs)
assert len(msgs) == 3 # empty row dropped, attachment kept


def test_prefers_text_column_then_falls_back_to_blob(db):
msgs = {m.text for m in imsgread.ChatStore(db).read_thread("+15555550123")}
msgs = {m.text for m in imsgread.ChatStore(db).read("+15555550123").messages}
assert "plain text column wins" in msgs
assert "first from them" in msgs


def test_newest_first(db):
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
assert msgs[0].has_attachment is True # rowid 3 is newest surviving


def test_returns_both_sides_of_the_conversation(db):
"""Both directions must come back. Reading only the other side loses what
you already said -- and therefore what is still unanswered."""
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
assert any(m.from_me for m in msgs), "lost the sent side"
assert any(not m.from_me for m in msgs), "lost the received side"


def test_direction_is_not_inverted(db):
"""rowid 2 is the only is_from_me=1 row in the fixture."""
sent = [m for m in imsgread.ChatStore(db).read_thread("+15555550123") if m.from_me]
sent = [m for m in imsgread.ChatStore(db).read("+15555550123").messages if m.from_me]
assert [m.text for m in sent] == ["plain text column wins"]


def test_include_empty_keeps_bodyless_rows(db):
assert len(imsgread.ChatStore(db).read_thread("+15555550123", include_empty=True)) == 4
assert len(imsgread.ChatStore(db).read("+15555550123", include_empty=True).messages) == 4


def test_limit_is_applied(db):
assert len(imsgread.ChatStore(db).read_thread("+15555550123", limit=1)) <= 1
assert len(imsgread.ChatStore(db).read("+15555550123", limit=1).messages) <= 1


def test_render_is_readable():
Expand All @@ -254,7 +254,7 @@ def test_render_is_readable():
def test_a_group_thread_attributes_each_sender(db):
"""Collapsing a group into one word makes the transcript quotable but
misattributable, which is worse than not reading it at all."""
msgs = imsgread.ChatStore(db).read_thread("chat9001")
msgs = imsgread.ChatStore(db).read("chat9001").messages
said = {m.sender: m.text for m in msgs if not m.from_me}
assert len(said) == 2, said
assert set(said.values()) == {"from alice", "from carol"}
Expand All @@ -263,16 +263,16 @@ def test_a_group_thread_attributes_each_sender(db):

def test_a_one_to_one_thread_keeps_its_shape_and_hides_the_number(db):
"""The whole point of contacts.toml is that numbers stay out of output."""
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
assert all(m.sender is None for m in msgs)
rendered = "\n".join(m.render() for m in msgs)
assert "+15555550123" not in rendered
assert "them" in rendered


def test_group_senders_use_a_known_name_and_mask_the_rest(db):
msgs = imsgread.ChatStore(db).read_thread("chat9001",
name_for=imsgread.ContactBook({"alice": imsgread.Contact("+15555550123")}).label)
msgs = imsgread.ChatStore(db).read("chat9001",
name_for=imsgread.ContactBook({"alice": imsgread.Contact("+15555550123")}).label).messages
senders = {m.sender for m in msgs if not m.from_me}
assert "alice" in senders
assert "*1111" in senders # unnamed participant, masked
Expand All @@ -282,7 +282,7 @@ def test_group_senders_use_a_known_name_and_mask_the_rest(db):
def test_an_attachment_reports_its_type_size_and_path(db):
"""[attachment] says something arrived but not what. Type, size and path
are what make a transcript actionable."""
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
shot = next(m for m in msgs if m.has_attachment)
kept = next(a for a in shot.attachments if a.exists)

Expand All @@ -297,7 +297,7 @@ def test_an_attachment_reports_its_type_size_and_path(db):
def test_an_attachment_no_longer_on_disk_is_marked_missing(db):
"""About one in eight recent attachments is already gone; a read must
treat that as normal rather than as an error."""
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
shot = next(m for m in msgs if m.has_attachment)
gone = next(a for a in shot.attachments if not a.exists)

Expand All @@ -306,7 +306,7 @@ def test_an_attachment_no_longer_on_disk_is_marked_missing(db):


def test_a_message_without_an_attachment_is_unchanged(db):
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
plain = next(m for m in msgs if m.text == "plain text column wins")
assert plain.attachments == []
assert plain.render().endswith("plain text column wins")
Expand Down Expand Up @@ -905,7 +905,7 @@ def test_link_previews_are_not_reported_as_attachments(db):
"""Messages writes a pluginPayloadAttachment per URL. They cannot be
opened or forwarded and the link is already in the message text, so
listing them buries the real files under path noise."""
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
shot = next(m for m in msgs if m.has_attachment)

assert len(shot.attachments) == 2
Expand Down Expand Up @@ -984,10 +984,36 @@ def test_a_thread_warns_only_once_it_trails_by_more_than_a_day(hours_behind, war
# --------------------------------------------------------------------------

def test_the_store_reads_one_thread(db):
msgs = imsgread.ChatStore(db).read_thread("+15555550123")
msgs = imsgread.ChatStore(db).read("+15555550123").messages
assert {m.text for m in msgs} == {"plain text column wins", "first from them", None}


def test_a_transcript_carries_its_own_staleness_note(db):
"""A caller cannot read a thread and forget to say it may be incomplete."""
import os
days_ago = datetime(2026, 11, 10, 18, 15, tzinfo=timezone.utc).timestamp()
os.utime(db, (days_ago, days_ago))

transcript = imsgread.ChatStore(db).read("+15555550123", now=NOW)

assert {m.text for m in transcript.messages} == {"plain text column wins", "first from them", None}
assert transcript.note.startswith("note: chat.db has not been updated since 2026-11-10")


def test_a_transcript_renders_as_json_or_text_newest_or_oldest_first():
older = imsgread.Message(date="2026-11-12T09:00:00+00:00", from_me=False,
text="older", has_attachment=False)
newer = imsgread.Message(date="2026-11-12T10:00:00+00:00", from_me=True,
text="newer", has_attachment=False)
transcript = imsgread.Transcript([newer, older])

assert [m["text"] for m in json.loads(transcript.render())] == ["newer", "older"]
assert [m["text"] for m in json.loads(transcript.render(oldest_first=True))] == ["older", "newer"]
lines = transcript.render(text=True, oldest_first=True).splitlines()
assert lines == [older.render(), newer.render()]
assert transcript.messages == [newer, older] # rendering never reorders the transcript


@pytest.mark.parametrize("make", [
lambda p: None, # missing
lambda p: p.write_bytes(b"not a database"), # unreadable
Expand All @@ -997,7 +1023,7 @@ def test_every_database_failure_is_one_store_error(tmp_path, make):
path = tmp_path / "chat.db"
make(path)
with pytest.raises(imsgread.StoreError):
imsgread.ChatStore(path).read_thread("+15555550123")
imsgread.ChatStore(path).read("+15555550123").messages


@pytest.mark.parametrize("chat_id, guid, is_group", [
Expand Down
Loading