forked from CamHenlin/imessageclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
360 lines (306 loc) · 11.1 KB
/
app.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
var sqlite3 = require('sqlite3').verbose();
var fs = require("fs");
var dir = process.env.CHAT_DIR || (process.env.HOME + '/Library/Messages/');
var file = process.env.CHAT_FILE || (process.env.HOME + '/Library/Messages/chat.db');
var contacts = process.env.ADDRESS_BOOK || (process.env.HOME + '/Library/Application\ Support/AddressBook/**/AddressBook-v22.abcddb');
var blessed = require("blessed");
var exec = require('exec');
var glob = require('glob');
var imessagemodule = require("imessagemodule");
// blessed elements
var chatList;
var selectedChatBox;
var outputBox;
const OSX_EPOCH = 978307200;
var exists = fs.existsSync(file);
if (!exists) {
setTimeout(function() {
outputBox.setItems(["Looks like there was a problem opening Messages.app's SQLite database.", "Open an issue at https://github.com/CamHenlin/imessageclient/issues"]);
screen.render();
}, 250);
}
// discover if we are running an old version of OS X or not
var OLD_OSX = false;
var os = require('os');
if (os.release().split('.')[0] === "12") { // 12 is 10.8 Mountain Lion, which does not have named group chats
OLD_OSX = true;
}
// discover whether the keyboard setting "Full Keyboard Access" is set to
// "Text boxes and lists only" -- error or 1 or less
// "All controls" (takes 2 tabs instead of one switching between elements in Messages.app) -- 2 or more
var FULL_KEYBOARD_ACCESS = false; // false for text boxes and lists, true for all controls
exec('defaults read NSGlobalDomain AppleKeyboardUIMode', function(err, out, code) {
if (err instanceof Error) {
// return because we already have false set and error means text boxes and lists only
return;
}
if (parseInt(out) > 1) {
FULL_KEYBOARD_ACCESS = true;
}
});
// read the Messages.app sqlite db
var db = new sqlite3.Database(file);
// Create a screen object and name it.
var screen = blessed.screen();
screen.title = 'iMessages';
// internally used variables
var LAST_SEEN_ID = 0;
var LAST_SEEN_CHAT_ID = 0;
var ID_MISMATCH = false;
var SELECTED_CHATTER = ""; // could be phone number or email address or groupchat id
var SELECTED_CHATTER_NAME = ""; // should be a firstname and lastname if selected chatter exists in addressbook
var GROUPCHAT_SELECTED = false;
var SELECTED_GROUP = ""; // stores actual group title
var MY_APPLE_ID = "";
var ENABLE_OTHER_SERVICES = false;
var sending = false;
var chatSet = false;
// blessed code
chatList = blessed.list({
parent: screen,
width: '25%',
height: '100%',
top: '0',
right: '0',
align: 'center',
fg: 'cyan',
label: 'Conversations',
border: {
type: 'line'
},
selectedBg: 'green',
// Allow mouse support
mouse: true,
// Allow key support (arrow keys + enter)
keys: true
});
// box on right with list of open chats
selectedChatBox = blessed.box({
parent: screen,
// Possibly support:
align: 'center',
fg: 'cyan',
height: '4%',
width: '75%',
top: '0',
left: '0',
content: ""
});
// main chat box
outputBox = blessed.list({
parent: screen,
fg: 'cyan',
//height: '97%',
border: {
type: 'line'
},
width: '75%',
top: '4%',
left: '0',
// Allow mouse support
mouse: true,
// Allow key support (arrow keys + enter)
keys: true
});
// load initial chats list
getChats();
// Allow scrolling with the mousewheel (manually).
chatList.on('wheeldown', function() {
chatList.down();
});
chatList.on('wheelup', function() {
chatList.up();
});
outputBox.on('wheeldown', function() {
outputBox.down();
});
outputBox.on('wheelup', function() {
outputBox.up();
});
outputBox.focus();
// q button quits
screen.key('q', function(ch, key) {
return process.exit(0);
});
// r button enables other services
screen.key('r', function(ch, key) {
if (ENABLE_OTHER_SERVICES) {
ENABLE_OTHER_SERVICES = false;
} else {
ENABLE_OTHER_SERVICES = true;
}
getChats();
screen.render();
});
// not 100% sure why this doesnt work, should scroll up conversation
screen.key('p', function(ch, key) {
chatList.select(-1);
screen.render();
});
// not 100% sure why this doesnt work, should scroll down conversation
screen.key('n', function(ch, key) {
chatList.select(1);
screen.render();
});
screen.key('pagedown', function(ch, key) {
outputBox.select(outputBox.height);
screen.render();
});
screen.key('pageup', function(ch, key) {
outputBox.select(-outputBox.height);
screen.render();
});
// handler for when a conversation is selected
chatList.on('select', function(data) {
selectChat(data);
});
function selectChat(data) {
chatSet = true;
// we don't want to try to get the name of groupchats
if (chatList.getItem(data.index-2).content.indexOf('-chat') > -1) {
GROUPCHAT_SELECTED = true;
// so group chats can be whatever the selection was
selectedChatBox.setContent(chatList.getItem(data.index-2).content);
} else {
GROUPCHAT_SELECTED = false;
if (!isNaN(parseInt(chatList.getItem(data.index-2).content))) { // we only want numbers, this is an ok way to filter them. emails for other services or icloud accounts will break this for now
getNameFromPhone(chatList.getItem(data.index-2).content, function (name) {
if (name && name !== "Undefined ") { // "Undefined " can happen on the case of there being a contact with no first or lastname, but a phone number and some other contact info
selectedChatBox.setContent(name);
} else {
selectedChatBox.setContent(chatList.getItem(data.index-2).content);
}
screen.render();
});
} else { // so group chats can be whatever the selection was
selectedChatBox.setContent(chatList.getItem(data.index-2).content);
}
}
SELECTED_CHATTER = chatList.getItem(data.index-2).content;
// handle special case for chats:
if (SELECTED_CHATTER.indexOf('-chat') > -1) {
SELECTED_GROUP = SELECTED_CHATTER;
SELECTED_CHATTER = 'chat'+SELECTED_CHATTER.split('-chat')[1];
}
getAllMessagesInCurrentChat();
screen.render();
}
function getNameFromPhone(phone, callback) {
phone = phone.replace(/\(/g,'').replace(/\)/g,'').replace(/\-/g,'').replace(/\ /g,'').replace(/\+/g,'');
// need to make a like statement so we can get the following phone, which is now in the format
// 11231231234 into 1%123%123%1234
// NOTE: this will probably not work for other countries since I assume they store their address differently?
// fall back to phone number for that case for now
// 1%
phone = phone.substr(0, 1) + '%' + phone.substr(1);
// 1%123
phone = phone.substr(0, 5) + '%' + phone.substr(5);
// 1%123%123
phone = phone.substr(0, 9) + '%' + phone.substr(9);
// comment out if you want to debug for another locality:
// throw new Error(phone);
glob(contacts, function (er, files) {
var found = false;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var db = new sqlite3.Database(file);
db.serialize(function() {
var SQL = 'SELECT * FROM ZABCDCONTACTINDEX LEFT OUTER JOIN ZABCDPHONENUMBER ON ZABCDCONTACTINDEX.ZCONTACT = ZABCDPHONENUMBER.ZOWNER LEFT OUTER JOIN ZABCDEMAILADDRESS ON ZABCDEMAILADDRESS.ZOWNER = ZABCDCONTACTINDEX.ZCONTACT LEFT OUTER JOIN ZABCDMESSAGINGADDRESS ON ZABCDMESSAGINGADDRESS.ZOWNER = ZABCDCONTACTINDEX.ZCONTACT LEFT OUTER JOIN ZABCDRECORD ON ZABCDRECORD.Z_PK = ZABCDCONTACTINDEX.ZCONTACT WHERE ZFULLNUMBER LIKE "%'+phone+'%"';
db.all(SQL, function(err, rows) {
if (rows.length > 0) {
found = true;
callback(rows[0].ZFIRSTNAME + ' ' + ((rows[0].ZLASTNAME) ? rows[0].ZLASTNAME : ""));
}
});
});
}
setTimeout(function() {
if (found) {
return;
} else {
callback();
}
}, 250);
});
}
function getChats() {
db.serialize(function() {
var arr = [];
var SQL = "SELECT DISTINCT message.date, handle.id, chat.chat_identifier, chat.display_name FROM message LEFT OUTER JOIN chat ON chat.room_name = message.cache_roomnames LEFT OUTER JOIN handle ON handle.ROWID = message.handle_id WHERE message.is_from_me = 0 AND message.service = 'iMessage' ORDER BY message.date DESC";
if (OLD_OSX) {
SQL = "SELECT DISTINCT message.date, handle.id, chat.chat_identifier FROM message LEFT OUTER JOIN chat ON chat.room_name = message.cache_roomnames LEFT OUTER JOIN handle ON handle.ROWID = message.handle_id WHERE message.is_from_me = 0 AND message.service = 'iMessage' ORDER BY message.date DESC";
}
if (ENABLE_OTHER_SERVICES) {
SQL = SQL.replace("AND message.service = 'iMessage'", "");
}
db.all(SQL, function(err, rows) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.chat_identifier === null) {
if (arr.indexOf(row.id) < 0 && row.id !== "" && typeof(row.id) !== "undefined") {
arr.push(row.id);
}
} else if (arr.indexOf(row.chat_identifier) < 0 && arr.indexOf(row.display_name+'-'+row.chat_identifier) < 0) {
if (row.chat_identifier.indexOf('chat') > -1) {
if (row.display_name && row.display_name !== "" && typeof(row.display_name) !== "undefined" || OLD_OSX) {
arr.push(row.display_name+'-'+row.chat_identifier);
}
} else {
if (row.chat_identifier && row.chat_identifier !== "" && typeof(row.chat_identifier) !== "undefined") {
arr.push(row.chat_identifier);
}
}
}
}
chatList.setItems(arr);
screen.render();
});
});
}
function getAllMessagesInCurrentChat() {
var SQL = "";
if (GROUPCHAT_SELECTED) { // this is a group chat
SQL = "SELECT DISTINCT message.ROWID, handle.id, message.text, message.is_from_me, datetime(message.date / 1000000000 + strftime('%s', '2001-01-01 00:00:00'), 'unixepoch', 'localtime') as msgdate, message.date, message.date_delivered, message.date_read FROM message LEFT OUTER JOIN chat ON chat.room_name = message.cache_roomnames LEFT OUTER JOIN handle ON handle.ROWID = message.handle_id WHERE message.service = 'iMessage' AND chat.chat_identifier = '"+SELECTED_CHATTER+"' ORDER BY msgdate ASC";
} else { // this is one person
SQL = "SELECT DISTINCT message.ROWID, handle.id, message.text, message.is_from_me, datetime(message.date / 1000000000 + strftime('%s', '2001-01-01 00:00:00'), 'unixepoch', 'localtime') as msgdate, message.date, message.date_delivered, message.date_read FROM message LEFT OUTER JOIN chat ON chat.room_name = message.cache_roomnames LEFT OUTER JOIN handle ON handle.ROWID = message.handle_id WHERE message.service = 'iMessage' AND handle.id = '"+SELECTED_CHATTER+"' ORDER BY msgdate ASC";
}
if (ENABLE_OTHER_SERVICES) {
SQL = SQL.replace("message.service = 'iMessage' AND ", "");
}
db.serialize(function() {
var arr = [];
db.all(SQL, function(err, rows) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
LAST_SEEN_CHAT_ID = row.ROWID;
arr.push(row.msgdate + ' - ' + ((!row.is_from_me) ? row.id : "me") + ": " + row.text);
if (row.is_from_me) {
MY_APPLE_ID = row.id;
}
}
outputBox.setItems(arr.reverse());
outputBox.select(rows.length);
screen.render();
});
});
}
setInterval(function() {
// don't do anything until the user has selected a chat
if (chatSet) {
db.serialize(function() {
db.all("SELECT MAX(ROWID) AS max FROM message", function(err, rows) {
if (rows) {
var max = rows[0].max;
if (max > LAST_SEEN_ID) {
LAST_SEEN_ID = max;
var ID_MISMATCH = true;
getChats();
getAllMessagesInCurrentChat();
}
}
}.bind(this));
}.bind(this));
}
}, 250);