This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
forked from Rolstenhouse/py-iMessage
-
Notifications
You must be signed in to change notification settings - Fork 1
/
db_conn.py
67 lines (52 loc) · 1.51 KB
/
db_conn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# db.py
# Connect to
import sqlite3
import os
import datetime
import math
import pytz
# Works for mac Catalina
home = os.environ['HOME']
db_path = f'{home}/Library/Messages/chat.db'
db = None
def open():
global db
if db:
return db
# Read only mode
db = sqlite3.connect(db_path, uri=True)
def clean_up():
if db:
db.close()
DATE_OFFSET = 978307200
def apple_time_now():
return math.floor(datetime.datetime.now() / 1000) - DATE_OFFSET
def from_apple_time(ts):
if ts==0:
return None
if unpack_time(ts) != 0:
ts = unpack_time(ts)
return datetime.datetime.fromtimestamp((ts + DATE_OFFSET), tz=pytz.timezone('US/Pacific'))
def unpack_time(ts):
return math.floor(ts / (10**9))
def pack_time_conditionally(ts):
return ts * 10**9
def get_most_recently_sent_text():
return db.execute("""SELECT guid, id as handle, text, date, date_read, date_delivered
FROM message
LEFT OUTER JOIN handle ON message.handle_id=handle.ROWID
WHERE is_from_me = 1
ORDER BY date DESC
LIMIT 1""").fetchone()[0]
def get_message(guid):
message = db.execute(f"""SELECT guid, date, date_read, date_delivered
FROM message
LEFT OUTER JOIN handle ON message.handle_id=handle.ROWID
WHERE is_from_me = 1 and guid="{guid}"
LIMIT 1""").fetchone()
return {
'guid': message[0],
'date': from_apple_time(message[1]),
'date_read': from_apple_time(message[2]),
'date_delivered': from_apple_time(message[3])
}