elelem-macos 0.1.0
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.
- checksums.yaml +7 -0
- data/LICENSE.txt +675 -0
- data/ext/elelem/macos/imessage/crate/Cargo.lock +825 -0
- data/ext/elelem/macos/imessage/crate/Cargo.toml +21 -0
- data/ext/elelem/macos/imessage/crate/src/lib.rs +369 -0
- data/ext/elelem/macos/imessage/extconf.rb +41 -0
- data/lib/elelem/macos/contacts/database.rb +72 -0
- data/lib/elelem/macos/contacts.rb +19 -0
- data/lib/elelem/macos/imessage/database.rb +58 -0
- data/lib/elelem/macos/imessage/native.rb +38 -0
- data/lib/elelem/macos/imessage.rb +21 -0
- data/lib/elelem/macos/notes/body.rb +63 -0
- data/lib/elelem/macos/notes/database.rb +86 -0
- data/lib/elelem/macos/notes.rb +21 -0
- data/lib/elelem/macos/sqlite.rb +28 -0
- data/lib/elelem/macos/version.rb +7 -0
- data/lib/elelem/macos.rb +6 -0
- metadata +109 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "elelem-imessage-native"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
license = "GPL-3.0-or-later"
|
|
6
|
+
publish = false
|
|
7
|
+
|
|
8
|
+
[lib]
|
|
9
|
+
crate-type = ["cdylib"]
|
|
10
|
+
|
|
11
|
+
[dependencies]
|
|
12
|
+
anyhow = "1"
|
|
13
|
+
chrono = "0.4"
|
|
14
|
+
imessage-database = "4.2.0"
|
|
15
|
+
rusqlite = { version = "0.40", features = ["bundled"] }
|
|
16
|
+
serde = { version = "1", features = ["derive"] }
|
|
17
|
+
serde_json = "1"
|
|
18
|
+
unicode-normalization = "0.1"
|
|
19
|
+
|
|
20
|
+
[profile.release]
|
|
21
|
+
panic = "unwind"
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
use std::collections::{BTreeSet, HashMap, HashSet};
|
|
2
|
+
use std::ffi::{CStr, CString};
|
|
3
|
+
use std::os::raw::c_char;
|
|
4
|
+
use std::path::PathBuf;
|
|
5
|
+
|
|
6
|
+
use anyhow::{Context, Result};
|
|
7
|
+
use chrono::{DateTime, Local};
|
|
8
|
+
use imessage_database::{
|
|
9
|
+
message_types::variants::{Tapback, TapbackAction, Variant},
|
|
10
|
+
tables::{
|
|
11
|
+
capabilities::Capabilities,
|
|
12
|
+
chat_handle::ChatToHandle,
|
|
13
|
+
handle::Handle,
|
|
14
|
+
messages::Message,
|
|
15
|
+
table::{get_connection, Cacheable, Table},
|
|
16
|
+
},
|
|
17
|
+
util::{dates::{get_local_time, get_offset}, query_context::QueryContext},
|
|
18
|
+
};
|
|
19
|
+
use rusqlite::Connection;
|
|
20
|
+
use serde::Serialize;
|
|
21
|
+
use unicode_normalization::UnicodeNormalization;
|
|
22
|
+
|
|
23
|
+
const SOURCE: &str = "imessage";
|
|
24
|
+
const ME: &str = "me";
|
|
25
|
+
const ATTACHMENT_PLACEHOLDER: char = '\u{fffc}';
|
|
26
|
+
|
|
27
|
+
#[derive(Serialize)]
|
|
28
|
+
struct Record {
|
|
29
|
+
id: String,
|
|
30
|
+
thread_id: String,
|
|
31
|
+
sent_at: String,
|
|
32
|
+
from: String,
|
|
33
|
+
to: Vec<String>,
|
|
34
|
+
body: String,
|
|
35
|
+
#[serde(skip_serializing_if = "Vec::is_empty")]
|
|
36
|
+
relates_to: Vec<Relation>,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
#[derive(Serialize)]
|
|
40
|
+
#[serde(tag = "rel_type", rename_all = "lowercase")]
|
|
41
|
+
enum Relation {
|
|
42
|
+
Reply { target_id: String },
|
|
43
|
+
Reaction { target_id: String, emoji: String },
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
fn extract(db_file: &str) -> Result<Vec<Record>> {
|
|
47
|
+
let db_path = expand_tilde(db_file);
|
|
48
|
+
let db = get_connection(&db_path).with_context(|| format!("cannot open {}", db_path.display()))?;
|
|
49
|
+
|
|
50
|
+
let owners = owner_handles(&db)?;
|
|
51
|
+
let handles = Handle::cache(&db).context("cannot cache handles")?;
|
|
52
|
+
let participants = ChatToHandle::cache(&db).context("cannot cache participants")?;
|
|
53
|
+
let standing = standing_tapbacks(&db)?;
|
|
54
|
+
let offset = get_offset();
|
|
55
|
+
|
|
56
|
+
let context = QueryContext::default();
|
|
57
|
+
let capabilities = Capabilities::determine(&db).context("cannot determine db capabilities")?;
|
|
58
|
+
let mut statement = Message::stream_rows(&db, &capabilities, &context).context("cannot query messages")?;
|
|
59
|
+
let rows = Message::rows(&mut statement, []).context("cannot read messages")?;
|
|
60
|
+
|
|
61
|
+
let mut records = Vec::new();
|
|
62
|
+
for row in rows {
|
|
63
|
+
let mut message = match row {
|
|
64
|
+
Ok(message) => message,
|
|
65
|
+
Err(_) => continue,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
if message.is_tapback() {
|
|
69
|
+
if !standing.contains(&message.guid) {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
let owner = owner_for(&owners, &message);
|
|
73
|
+
if let Some(record) = reaction_record(&message, owner, offset, &handles, &participants) {
|
|
74
|
+
records.push(record);
|
|
75
|
+
}
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if let Ok(body) = message.parse_body(&db) {
|
|
80
|
+
message.apply_body(body);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let owner = owner_for(&owners, &message);
|
|
84
|
+
records.push(message_record(&message, owner, offset, &handles, &participants));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
Ok(records)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
fn message_record(
|
|
91
|
+
message: &Message,
|
|
92
|
+
owner: &str,
|
|
93
|
+
offset: i64,
|
|
94
|
+
handles: &HashMap<i32, String>,
|
|
95
|
+
participants: &HashMap<i32, BTreeSet<i32>>,
|
|
96
|
+
) -> Record {
|
|
97
|
+
let from = sender(message, owner, handles);
|
|
98
|
+
let to = recipients(message.chat_id, &from, owner, handles, participants);
|
|
99
|
+
let relates_to = message
|
|
100
|
+
.thread_originator_guid
|
|
101
|
+
.as_ref()
|
|
102
|
+
.map(|parent| vec![Relation::Reply { target_id: message_id(parent) }])
|
|
103
|
+
.unwrap_or_default();
|
|
104
|
+
|
|
105
|
+
Record {
|
|
106
|
+
id: message_id(&message.guid),
|
|
107
|
+
thread_id: thread_id(message.chat_id),
|
|
108
|
+
sent_at: timestamp(message.date, offset),
|
|
109
|
+
from,
|
|
110
|
+
to,
|
|
111
|
+
body: body_text(message),
|
|
112
|
+
relates_to,
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
fn reaction_record(
|
|
117
|
+
message: &Message,
|
|
118
|
+
owner: &str,
|
|
119
|
+
offset: i64,
|
|
120
|
+
handles: &HashMap<i32, String>,
|
|
121
|
+
participants: &HashMap<i32, BTreeSet<i32>>,
|
|
122
|
+
) -> Option<Record> {
|
|
123
|
+
let Variant::Tapback(_, _, kind) = message.variant() else {
|
|
124
|
+
return None;
|
|
125
|
+
};
|
|
126
|
+
let emoji = emoji_token(&kind)?;
|
|
127
|
+
let (_, target_guid) = message.clean_associated_guid()?;
|
|
128
|
+
|
|
129
|
+
let from = sender(message, owner, handles);
|
|
130
|
+
let to = recipients(message.chat_id, &from, owner, handles, participants);
|
|
131
|
+
|
|
132
|
+
Some(Record {
|
|
133
|
+
id: message_id(&message.guid),
|
|
134
|
+
thread_id: thread_id(message.chat_id),
|
|
135
|
+
sent_at: timestamp(message.date, offset),
|
|
136
|
+
from,
|
|
137
|
+
to,
|
|
138
|
+
body: String::new(),
|
|
139
|
+
relates_to: vec![Relation::Reaction { target_id: message_id(target_guid), emoji }],
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
fn sender(message: &Message, owner: &str, handles: &HashMap<i32, String>) -> String {
|
|
144
|
+
if message.is_from_me {
|
|
145
|
+
return owner.to_string();
|
|
146
|
+
}
|
|
147
|
+
match message.handle_id.and_then(|id| handles.get(&id)) {
|
|
148
|
+
Some(address) => handle(address),
|
|
149
|
+
None => ME.to_string(),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
fn recipients(
|
|
154
|
+
chat_id: Option<i32>,
|
|
155
|
+
sender: &str,
|
|
156
|
+
owner: &str,
|
|
157
|
+
handles: &HashMap<i32, String>,
|
|
158
|
+
participants: &HashMap<i32, BTreeSet<i32>>,
|
|
159
|
+
) -> Vec<String> {
|
|
160
|
+
let mut roster = vec![owner.to_string()];
|
|
161
|
+
|
|
162
|
+
if let Some(chat_id) = chat_id {
|
|
163
|
+
if let Some(members) = participants.get(&chat_id) {
|
|
164
|
+
for member in members {
|
|
165
|
+
if let Some(address) = handles.get(member) {
|
|
166
|
+
roster.push(handle(address));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
finalize_roster(roster, sender)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
fn standing_tapbacks(db: &Connection) -> Result<HashSet<String>> {
|
|
176
|
+
let tapbacks = Message::cache(db).context("cannot cache tapbacks")?;
|
|
177
|
+
let mut standing = HashSet::new();
|
|
178
|
+
|
|
179
|
+
for by_component in tapbacks.values() {
|
|
180
|
+
let mut all: Vec<&Message> = by_component.values().flatten().collect();
|
|
181
|
+
all.sort_by_key(|tapback| tapback.date);
|
|
182
|
+
|
|
183
|
+
let mut live: HashMap<(bool, Option<i32>, String), String> = HashMap::new();
|
|
184
|
+
for tapback in all {
|
|
185
|
+
let Variant::Tapback(_, action, kind) = tapback.variant() else {
|
|
186
|
+
continue;
|
|
187
|
+
};
|
|
188
|
+
let Some(emoji) = emoji_token(&kind) else {
|
|
189
|
+
continue;
|
|
190
|
+
};
|
|
191
|
+
let key = (tapback.is_from_me, tapback.handle_id, emoji);
|
|
192
|
+
match action {
|
|
193
|
+
TapbackAction::Added => {
|
|
194
|
+
live.insert(key, tapback.guid.clone());
|
|
195
|
+
}
|
|
196
|
+
TapbackAction::Removed => {
|
|
197
|
+
live.remove(&key);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
standing.extend(live.into_values());
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
Ok(standing)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
fn owner_handles(db: &Connection) -> Result<HashMap<i32, String>> {
|
|
209
|
+
let mut statement = db
|
|
210
|
+
.prepare("SELECT ROWID, destination_caller_id, account FROM message")
|
|
211
|
+
.context("cannot prepare owner query")?;
|
|
212
|
+
|
|
213
|
+
let rows = statement
|
|
214
|
+
.query_map([], |row| {
|
|
215
|
+
let rowid: i32 = row.get(0)?;
|
|
216
|
+
let caller: Option<String> = row.get(1)?;
|
|
217
|
+
let account: Option<String> = row.get(2)?;
|
|
218
|
+
Ok((rowid, caller, account))
|
|
219
|
+
})
|
|
220
|
+
.context("cannot read owner columns")?;
|
|
221
|
+
|
|
222
|
+
let mut owners = HashMap::new();
|
|
223
|
+
for row in rows {
|
|
224
|
+
let (rowid, caller, account) = row.context("cannot read owner row")?;
|
|
225
|
+
if let Some(handle) = owner_handle(caller.as_deref(), account.as_deref()) {
|
|
226
|
+
owners.insert(rowid, handle);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
Ok(owners)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
fn owner_for<'a>(owners: &'a HashMap<i32, String>, message: &Message) -> &'a str {
|
|
234
|
+
owners.get(&message.rowid).map(|owner| owner.as_str()).unwrap_or(ME)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
fn owner_handle(caller_id: Option<&str>, account: Option<&str>) -> Option<String> {
|
|
238
|
+
if let Some(handle) = caller_id.and_then(handle_from_caller) {
|
|
239
|
+
return Some(handle);
|
|
240
|
+
}
|
|
241
|
+
account.and_then(handle_from_account)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
fn handle_from_caller(raw: &str) -> Option<String> {
|
|
245
|
+
let raw = raw.trim().trim_start_matches("tel:").trim();
|
|
246
|
+
if raw.is_empty() {
|
|
247
|
+
return None;
|
|
248
|
+
}
|
|
249
|
+
if raw.contains('@') {
|
|
250
|
+
Some(format!("email:{}", raw.to_lowercase()))
|
|
251
|
+
} else {
|
|
252
|
+
Some(phone_handle(raw))
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
fn handle_from_account(raw: &str) -> Option<String> {
|
|
257
|
+
let raw = raw.trim();
|
|
258
|
+
if let Some(email) = raw.strip_prefix("E:") {
|
|
259
|
+
let email = email.trim();
|
|
260
|
+
(!email.is_empty()).then(|| format!("email:{}", email.to_lowercase()))
|
|
261
|
+
} else if let Some(phone) = raw.strip_prefix("P:") {
|
|
262
|
+
let phone = phone.trim();
|
|
263
|
+
(!phone.is_empty()).then(|| phone_handle(phone))
|
|
264
|
+
} else {
|
|
265
|
+
None
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
fn handle(raw: &str) -> String {
|
|
270
|
+
let raw = raw.trim();
|
|
271
|
+
if raw.contains('@') {
|
|
272
|
+
format!("email:{}", raw.to_lowercase())
|
|
273
|
+
} else {
|
|
274
|
+
format!("phone:{raw}")
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
fn phone_handle(raw: &str) -> String {
|
|
279
|
+
let digits: String = raw.chars().filter(|c| c.is_ascii_digit()).collect();
|
|
280
|
+
format!("phone:+{digits}")
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
fn body_text(message: &Message) -> String {
|
|
284
|
+
match message.text.as_deref() {
|
|
285
|
+
Some(text) => normalize_body(text),
|
|
286
|
+
None => String::new(),
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
fn emoji_token(tapback: &Tapback) -> Option<String> {
|
|
291
|
+
let token = match tapback {
|
|
292
|
+
Tapback::Loved => "love",
|
|
293
|
+
Tapback::Liked => "like",
|
|
294
|
+
Tapback::Disliked => "dislike",
|
|
295
|
+
Tapback::Laughed => "laugh",
|
|
296
|
+
Tapback::Emphasized => "emphasize",
|
|
297
|
+
Tapback::Questioned => "question",
|
|
298
|
+
Tapback::Emoji(Some(emoji)) => return Some(emoji.nfc().collect()),
|
|
299
|
+
Tapback::Emoji(None) | Tapback::Sticker => return None,
|
|
300
|
+
};
|
|
301
|
+
Some(token.to_string())
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
fn message_id(guid: &str) -> String {
|
|
305
|
+
format!("{SOURCE}:{guid}")
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
fn thread_id(chat_id: Option<i32>) -> String {
|
|
309
|
+
match chat_id {
|
|
310
|
+
Some(id) => format!("{SOURCE}:chat{id}"),
|
|
311
|
+
None => format!("{SOURCE}:chat-none"),
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
fn timestamp(date: i64, offset: i64) -> String {
|
|
316
|
+
get_local_time(date, offset).map(format_local).unwrap_or_default()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
fn finalize_roster(mut roster: Vec<String>, sender: &str) -> Vec<String> {
|
|
320
|
+
roster.sort();
|
|
321
|
+
roster.dedup();
|
|
322
|
+
roster.retain(|who| who != sender);
|
|
323
|
+
roster
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
fn normalize_body(text: &str) -> String {
|
|
327
|
+
text.replace(ATTACHMENT_PLACEHOLDER, "").nfc().collect()
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
fn format_local(date: DateTime<Local>) -> String {
|
|
331
|
+
date.format("%Y-%m-%dT%H:%M:%S%.3f%:z").to_string()
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
fn expand_tilde(path: &str) -> PathBuf {
|
|
335
|
+
match path.strip_prefix("~/") {
|
|
336
|
+
Some(rest) => match std::env::var_os("HOME") {
|
|
337
|
+
Some(home) => PathBuf::from(home).join(rest),
|
|
338
|
+
None => PathBuf::from(path),
|
|
339
|
+
},
|
|
340
|
+
None => PathBuf::from(path),
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
fn error_json(msg: &str) -> String {
|
|
345
|
+
serde_json::json!({ "error": msg }).to_string()
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/// # Safety
|
|
349
|
+
/// `db_file` must be a valid, NUL-terminated C string pointer that outlives this call.
|
|
350
|
+
/// The returned pointer must be freed with `el_imessage_free`.
|
|
351
|
+
#[no_mangle]
|
|
352
|
+
pub unsafe extern "C" fn el_imessage_extract(db_file: *const c_char) -> *mut c_char {
|
|
353
|
+
let db_file = CStr::from_ptr(db_file).to_string_lossy().into_owned();
|
|
354
|
+
let json = match extract(&db_file) {
|
|
355
|
+
Ok(records) => serde_json::to_string(&records).unwrap_or_else(|e| error_json(&e.to_string())),
|
|
356
|
+
Err(e) => error_json(&format!("{e:#}")),
|
|
357
|
+
};
|
|
358
|
+
CString::new(json).unwrap_or_else(|_| CString::new("{\"error\":\"invalid utf8\"}").unwrap()).into_raw()
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/// # Safety
|
|
362
|
+
/// `ptr` must be a pointer previously returned by `el_imessage_extract`, or null.
|
|
363
|
+
#[no_mangle]
|
|
364
|
+
pub unsafe extern "C" fn el_imessage_free(ptr: *mut c_char) {
|
|
365
|
+
if ptr.is_null() {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
drop(CString::from_raw(ptr));
|
|
369
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
|
|
5
|
+
EXT_DIR = __dir__
|
|
6
|
+
CRATE = File.join(EXT_DIR, "crate")
|
|
7
|
+
NATIVE = File.join(EXT_DIR, "native")
|
|
8
|
+
DARWIN = RbConfig::CONFIG["host_os"] =~ /darwin/
|
|
9
|
+
|
|
10
|
+
class BuildError < StandardError; end
|
|
11
|
+
|
|
12
|
+
def run(*cmd)
|
|
13
|
+
warn "elelem: + #{cmd.join(" ")}"
|
|
14
|
+
system(*cmd) || raise(BuildError, "build step failed: #{cmd.join(" ")}")
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def which(cmd)
|
|
18
|
+
ENV["PATH"].to_s.split(File::PATH_SEPARATOR).any? do |dir|
|
|
19
|
+
path = File.join(dir, cmd)
|
|
20
|
+
File.executable?(path) && !File.directory?(path)
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
abort "elelem: cargo not found. Install Rust: https://rustup.rs" unless which("cargo")
|
|
25
|
+
|
|
26
|
+
ext = DARWIN ? "dylib" : "so"
|
|
27
|
+
lib_name = "libelelem_imessage_native.#{ext}"
|
|
28
|
+
|
|
29
|
+
run("cargo", "build", "--release", "--manifest-path", File.join(CRATE, "Cargo.toml"))
|
|
30
|
+
|
|
31
|
+
FileUtils.mkdir_p(NATIVE)
|
|
32
|
+
FileUtils.cp(File.join(CRATE, "target", "release", lib_name), File.join(NATIVE, lib_name))
|
|
33
|
+
|
|
34
|
+
File.write(File.join(EXT_DIR, "Makefile"), <<~MAKE)
|
|
35
|
+
all:
|
|
36
|
+
clean:
|
|
37
|
+
install:
|
|
38
|
+
.PHONY: all clean install
|
|
39
|
+
MAKE
|
|
40
|
+
|
|
41
|
+
warn "elelem: built iMessage native ext into #{NATIVE}"
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../sqlite"
|
|
4
|
+
|
|
5
|
+
module Elelem
|
|
6
|
+
module Macos
|
|
7
|
+
module Contacts
|
|
8
|
+
class Database
|
|
9
|
+
DEFAULT_LIMIT = 50
|
|
10
|
+
MAX_LIMIT = 200
|
|
11
|
+
DEFAULT_GLOB = "~/Library/Application Support/AddressBook/Sources/*/AddressBook-v22.abcddb"
|
|
12
|
+
PERSON_ENTITY = 22
|
|
13
|
+
|
|
14
|
+
CONTACTS_SQL = "SELECT Z_PK AS id, ZFIRSTNAME AS first_name, ZLASTNAME AS last_name, " \
|
|
15
|
+
"ZORGANIZATION AS organization FROM ZABCDRECORD WHERE Z_ENT = #{PERSON_ENTITY};".freeze
|
|
16
|
+
PHONES_SQL = "SELECT ZOWNER AS owner, ZFULLNUMBER AS number FROM ZABCDPHONENUMBER " \
|
|
17
|
+
"WHERE ZFULLNUMBER IS NOT NULL;"
|
|
18
|
+
EMAILS_SQL = "SELECT ZOWNER AS owner, ZADDRESS AS address FROM ZABCDEMAILADDRESS " \
|
|
19
|
+
"WHERE ZADDRESS IS NOT NULL;"
|
|
20
|
+
|
|
21
|
+
def initialize(db_glob: DEFAULT_GLOB)
|
|
22
|
+
@db_glob = db_glob
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def call(args)
|
|
26
|
+
contacts(search: args["search"], limit: args["limit"])
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def contacts(search:, limit:)
|
|
32
|
+
rows = db_files.flat_map { |db_file| contacts_in(db_file) }
|
|
33
|
+
|
|
34
|
+
if search
|
|
35
|
+
needle = search.downcase
|
|
36
|
+
rows = rows.select do |c|
|
|
37
|
+
c[:name].downcase.include?(needle) ||
|
|
38
|
+
c[:phones].any? { |p| p.include?(search) } ||
|
|
39
|
+
c[:emails].any? { |e| e.downcase.include?(needle) }
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
rows.first(bounded_limit(limit))
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def contacts_in(db_file)
|
|
47
|
+
sqlite = Sqlite.new(db_file: db_file)
|
|
48
|
+
phones = sqlite.dump(PHONES_SQL).group_by { |r| r[:owner] }
|
|
49
|
+
emails = sqlite.dump(EMAILS_SQL).group_by { |r| r[:owner] }
|
|
50
|
+
|
|
51
|
+
sqlite.dump(CONTACTS_SQL).map do |c|
|
|
52
|
+
name = [c[:first_name], c[:last_name]].compact.join(" ").strip
|
|
53
|
+
name = c[:organization].to_s if name.empty?
|
|
54
|
+
{
|
|
55
|
+
name: name,
|
|
56
|
+
phones: (phones[c[:id]] || []).map { |p| p[:number] },
|
|
57
|
+
emails: (emails[c[:id]] || []).map { |e| e[:address] }
|
|
58
|
+
}
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def bounded_limit(limit)
|
|
63
|
+
[(limit || DEFAULT_LIMIT).to_i, MAX_LIMIT].min
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def db_files
|
|
67
|
+
Dir.glob(File.expand_path(@db_glob))
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "elelem"
|
|
4
|
+
|
|
5
|
+
require_relative "contacts/database"
|
|
6
|
+
|
|
7
|
+
Elelem.configure do |config|
|
|
8
|
+
config.setup(:contacts) do |agent|
|
|
9
|
+
agent.toolbox.add("contacts",
|
|
10
|
+
description: "Query local macOS Contacts.app: name, phone numbers, and emails, " \
|
|
11
|
+
"optionally filtered by a search substring",
|
|
12
|
+
params: {
|
|
13
|
+
search: { type: "string", description: "filter by name, phone, or email substring" },
|
|
14
|
+
limit: { type: "integer", description: "max results (default 50, max 200)" }
|
|
15
|
+
}) do |args|
|
|
16
|
+
{ results: Elelem::Macos::Contacts::Database.new.call(args) }
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
require_relative "native"
|
|
6
|
+
|
|
7
|
+
module Elelem
|
|
8
|
+
module Macos
|
|
9
|
+
module Imessage
|
|
10
|
+
class Database
|
|
11
|
+
DEFAULT_LIMIT = 50
|
|
12
|
+
MAX_LIMIT = 200
|
|
13
|
+
DEFAULT_DB_FILE = "~/Library/Messages/chat.db"
|
|
14
|
+
|
|
15
|
+
def initialize(db_file: DEFAULT_DB_FILE, native: Native)
|
|
16
|
+
@db_file = db_file
|
|
17
|
+
@native = native
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def call(args)
|
|
21
|
+
messages(from: args["from"], query: args["query"], since: args["since"], limit: args["limit"])
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
private
|
|
25
|
+
|
|
26
|
+
def messages(from:, query:, since:, limit:)
|
|
27
|
+
rows = records.sort_by { |m| Time.parse(m[:sent_at]) }.reverse
|
|
28
|
+
|
|
29
|
+
if from
|
|
30
|
+
rows = rows.select do |m|
|
|
31
|
+
m[:from].to_s.downcase.include?(from.downcase) ||
|
|
32
|
+
m[:to].to_a.any? { |handle| handle.to_s.downcase.include?(from.downcase) }
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
rows = rows.select { |m| m[:body].to_s.downcase.include?(query.downcase) } if query
|
|
36
|
+
rows = rows.select { |m| Time.parse(m[:sent_at]) >= since_time(since) } if since
|
|
37
|
+
|
|
38
|
+
rows.first(bounded_limit(limit))
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def since_time(since)
|
|
42
|
+
match = since.match(/\A(\d+)([hd])\z/)
|
|
43
|
+
return Time.now - (match[1].to_i * (match[2] == "h" ? 3600 : 86_400)) if match
|
|
44
|
+
|
|
45
|
+
Time.parse(since)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def bounded_limit(limit)
|
|
49
|
+
(limit || DEFAULT_LIMIT).to_i.clamp(0, MAX_LIMIT)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def records
|
|
53
|
+
@records ||= @native.extract(File.expand_path(@db_file))
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fiddle"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module Elelem
|
|
7
|
+
module Macos
|
|
8
|
+
module Imessage
|
|
9
|
+
class Native
|
|
10
|
+
NATIVE_DIR = File.expand_path("../../../../ext/elelem/macos/imessage/native", __dir__)
|
|
11
|
+
EXT = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "dylib" : "so"
|
|
12
|
+
SHIM = File.join(NATIVE_DIR, "libelelem_imessage_native.#{EXT}")
|
|
13
|
+
V = Fiddle::TYPE_VOIDP
|
|
14
|
+
|
|
15
|
+
def self.functions
|
|
16
|
+
@functions ||= begin
|
|
17
|
+
lib = Fiddle.dlopen(SHIM)
|
|
18
|
+
{
|
|
19
|
+
extract: Fiddle::Function.new(lib["el_imessage_extract"], [V], V),
|
|
20
|
+
free: Fiddle::Function.new(lib["el_imessage_free"], [V], Fiddle::TYPE_VOID)
|
|
21
|
+
}
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def self.extract(db_file)
|
|
26
|
+
ptr = functions[:extract].call(db_file)
|
|
27
|
+
json = Fiddle::Pointer.new(ptr).to_s.dup.force_encoding(Encoding::UTF_8)
|
|
28
|
+
functions[:free].call(ptr)
|
|
29
|
+
|
|
30
|
+
result = JSON.parse(json, symbolize_names: true)
|
|
31
|
+
raise "imessage: #{result[:error]}" if result.is_a?(Hash) && result[:error]
|
|
32
|
+
|
|
33
|
+
result
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "elelem"
|
|
4
|
+
|
|
5
|
+
require_relative "imessage/database"
|
|
6
|
+
|
|
7
|
+
Elelem.configure do |config|
|
|
8
|
+
config.setup(:imessage) do |agent|
|
|
9
|
+
agent.toolbox.add("imessage",
|
|
10
|
+
description: "Query local iMessage history from chat.db: messages filtered by " \
|
|
11
|
+
"sender, text, or recency",
|
|
12
|
+
params: {
|
|
13
|
+
from: { type: "string", description: "filter by sender or recipient substring" },
|
|
14
|
+
query: { type: "string", description: "filter by body substring" },
|
|
15
|
+
since: { type: "string", description: "e.g. '7d', '24h', or an ISO8601 date" },
|
|
16
|
+
limit: { type: "integer", description: "max results, newest first (default 50, max 200)" }
|
|
17
|
+
}) do |args|
|
|
18
|
+
{ results: Elelem::Macos::Imessage::Database.new.call(args) }
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|