Skip to content

Latest commit

 

History

History
executable file
·
1275 lines (1084 loc) · 41.7 KB

archive_imessage.pl

File metadata and controls

executable file
·
1275 lines (1084 loc) · 41.7 KB
 
1
2
3
4
5
#!/usr/bin/perl -w
use warnings;
use strict;
Jun 21, 2016
Jun 21, 2016
6
use File::Basename;
Jun 16, 2016
Jun 16, 2016
7
use Digest::SHA1 qw(sha1_hex);
8
9
10
11
use DBI;
use Encode qw( decode_utf8 );
use POSIX;
use File::Copy;
Jun 16, 2016
Jun 16, 2016
12
13
use MIME::Base64;
use File::Slurp;
Jun 21, 2016
Jun 21, 2016
14
use Regexp::Common qw/URI/;
15
16
17
18
19
20
my $VERSION = '0.0.1';
my $gaptime = (30 * 60);
my $timezone = strftime('%Z', localtime());
my $now = time();
Jun 21, 2016
Jun 21, 2016
21
my $homedir = $ENV{'HOME'};
Jun 21, 2016
Jun 21, 2016
22
my $program_dir = dirname($0);
Jun 22, 2016
Jun 22, 2016
23
my $thumbnail_max_width = 235;
24
25
26
27
28
# Fixes unicode dumping to stdio...hopefully you have a utf-8 terminal by now.
#binmode(STDOUT, ":utf8");
#binmode(STDERR, ":utf8");
Jun 20, 2016
Jun 20, 2016
29
30
31
32
33
sub fail {
my $err = shift;
die("$err\n");
}
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
sub signal_catcher {
my $sig = shift;
fail("Caught signal ${sig}!");
}
$SIG{INT} = \&signal_catcher;
$SIG{TERM} = \&signal_catcher;
$SIG{HUP} = \&signal_catcher;
my $debug = 0;
sub dbgprint {
print @_ if $debug;
}
my $archivedir = undef;
my $imessageuser = undef;
Jun 16, 2016
Jun 16, 2016
49
my $imessageuserhost = undef;
Jun 21, 2016
Jun 21, 2016
50
51
my $imessageuserlongname = undef;
my $imessageusershortname = undef;
52
my $maildir = undef;
Jun 17, 2016
Jun 17, 2016
53
my $allow_html = 0;
Jun 20, 2016
Jun 20, 2016
54
55
my $report_progress = 0;
my $attachment_shrink_percent = undef;
Jun 20, 2016
Jun 20, 2016
56
my $allow_video_attachments = 1;
Jun 20, 2016
Jun 20, 2016
57
58
my $allow_attachments = 1;
my $allow_thumbnails = 1;
Jun 21, 2016
Jun 21, 2016
59
my $ios_archive = 0;
Oct 30, 2016
Oct 30, 2016
60
my $archive_version = 0;
Aug 17, 2016
Aug 17, 2016
61
my $mbox = 0;
Jun 17, 2016
Jun 17, 2016
62
63
sub usage {
Jun 22, 2016
Jun 22, 2016
64
print STDERR "USAGE: $0 [...options...] <messagedir> <maildir>\n";
Jun 17, 2016
Jun 17, 2016
65
print STDERR "\n";
Jun 20, 2016
Jun 20, 2016
66
67
68
69
print STDERR " --debug: Enable spammy debug logging to stdout.\n";
print STDERR " --html: Output HTML archives.\n";
print STDERR " --progress: Print progress to stdout.\n";
print STDERR " --attachments-shrink-percent=NUM: resize videos/images to NUM percent.\n";
Jun 20, 2016
Jun 20, 2016
70
print STDERR " --no-video-attachments: Don't include image/video attachments.\n";
Jun 20, 2016
Jun 20, 2016
71
72
print STDERR " --no-attachments: Don't include attachments at all.\n";
print STDERR " --no-thumbnails: Don't include thumbnails in HTML output.\n";
Jun 21, 2016
Jun 21, 2016
73
print STDERR " --gap-time=NUM: treat NUM minutes of silence as the end of a conversation.\n";
Aug 17, 2016
Aug 17, 2016
74
75
print STDERR " --mbox: email archive should be in mbox format instead of Maildir.\n";
print STDERR " --maildir: email archive should be in Maildir format instead of mbox.\n";
Jun 22, 2016
Jun 22, 2016
76
print STDERR " messagedir: Directory holding iPhone backup or Messages chat.db database.\n";
Aug 17, 2016
Aug 17, 2016
77
print STDERR " maildir: Path of Maildir/mbox where we write archives and metadata.\n";
Jun 17, 2016
Jun 17, 2016
78
79
80
81
82
83
84
85
86
print STDERR "\n";
exit(1);
}
foreach (@ARGV) {
$debug = 1, next if $_ eq '--debug';
$debug = 0, next if $_ eq '--no-debug';
$allow_html = 1, next if $_ eq '--html';
$allow_html = 0, next if $_ eq '--no-html';
Jun 20, 2016
Jun 20, 2016
87
88
$report_progress = 1, next if $_ eq '--progress';
$report_progress = 0, next if $_ eq '--no-progress';
Jun 20, 2016
Jun 20, 2016
89
90
$allow_video_attachments = 1, next if $_ eq '--video-attachments';
$allow_video_attachments = 0, next if $_ eq '--no-video-attachments';
Jun 20, 2016
Jun 20, 2016
91
92
93
94
$allow_attachments = 1, next if $_ eq '--attachments';
$allow_attachments = 0, next if $_ eq '--no-attachments';
$allow_thumbnails = 1, next if $_ eq '--thumbnails';
$allow_thumbnails = 0, next if $_ eq '--no-thumbnails';
Aug 17, 2016
Aug 17, 2016
95
96
$mbox = 1, next if $_ eq '--mbox';
$mbox = 0, next if $_ eq '--maildir';
Jun 20, 2016
Jun 20, 2016
97
$attachment_shrink_percent = int($1), next if /\A--attachments-shrink-percent=(\d+)\Z/;
Jun 21, 2016
Jun 21, 2016
98
$gaptime = int($1) * 60, next if /\A--gap-time=(\d+)\Z/;
Jun 17, 2016
Jun 17, 2016
99
100
101
102
103
104
105
$archivedir = $_, next if not defined $archivedir;
$maildir = $_, next if (not defined $maildir);
usage();
}
usage() if not defined $archivedir;
usage() if not defined $maildir;
Jun 20, 2016
Jun 20, 2016
106
107
108
109
if ((defined $attachment_shrink_percent) && ($attachment_shrink_percent == 100)) {
$attachment_shrink_percent = undef;
} elsif ((defined $attachment_shrink_percent) && (($attachment_shrink_percent < 1) || ($attachment_shrink_percent > 100))) {
fail("--attachments-shrink-percent must be between 1 and 100.");
Jun 23, 2016
Jun 23, 2016
112
113
dbgprint("\$now is $now.\n");
Jun 16, 2016
Jun 16, 2016
114
115
116
sub archive_fname {
my $domain = shift;
my $name = shift;
Jun 21, 2016
Jun 21, 2016
117
118
119
120
if ($ios_archive) {
my $combined = "$domain-$name";
my $hashed = sha1_hex($combined);
dbgprint("Hashed archived filename '$combined' to '$hashed'\n");
Oct 30, 2016
Oct 30, 2016
121
# iOS 10 (or maybe a new iTunes?) splits files into subdirs so they
Jan 1, 2017
Jan 1, 2017
122
# don't have a thousand files in one place.
Oct 30, 2016
Oct 30, 2016
123
124
125
126
127
128
if ($archive_version >= 10) {
my $hashstart = substr($hashed, 0, 2);
return "$archivedir/$hashstart/$hashed";
} else {
return "$archivedir/$hashed";
}
Jun 21, 2016
Jun 21, 2016
129
130
131
132
133
134
135
136
137
}
return "$archivedir/$name";
}
fail("ERROR: Directory '$archivedir' doesn't exist.") if (not -d $archivedir);
if (-f "$archivedir/Manifest.mbdb") {
$ios_archive = 1;
Oct 30, 2016
Oct 30, 2016
138
139
140
141
$archive_version = 9;
} elsif (-f "$archivedir/Manifest.db") {
$ios_archive = 1;
$archive_version = 10; # iOS 10 changed this filename.
Jun 21, 2016
Jun 21, 2016
142
143
144
145
} elsif (-f "$archivedir/chat.db") {
$ios_archive = 0;
} else {
fail("ERROR: '$archivedir' isn't a macOS Messages directory or an iOS backup.\n");
Jun 16, 2016
Jun 16, 2016
146
147
}
Jun 21, 2016
Jun 21, 2016
148
if ($ios_archive) {
Oct 30, 2016
Oct 30, 2016
149
dbgprint("Chat database is in an iOS $archive_version backup.\n");
Jun 21, 2016
Jun 21, 2016
150
151
152
} else {
dbgprint("Chat database is in a macOS install.\n");
}
153
154
155
156
157
158
159
160
my $startid = 0;
my %startids = ();
my $lastarchivefname = undef;
my $lastarchivetmpfname = undef;
sub flush_startid {
my ($with, $msgid) = @_;
Jun 20, 2016
Jun 20, 2016
161
162
163
164
165
166
167
168
if (defined $with and defined $msgid) {
$startids{$with} = $msgid;
dbgprint("flushing startids (global: $startid, '$with': $msgid)\n");
} else {
dbgprint("flushing startids (global: $startid)\n");
}
169
170
171
172
if (not open(LASTID,'>',$lastarchivetmpfname)) {
dbgprint("Open '$lastarchivetmpfname' for write failed: $!\n");
return 0;
}
Jun 20, 2016
Jun 20, 2016
173
print LASTID "$startid\n";
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
foreach(keys %startids) {
my $key = $_;
my $val = $startids{$key};
print LASTID "$key\n$val\n";
}
close(LASTID);
if (not move($lastarchivetmpfname, $lastarchivefname)) {
unlink($lastarchivetmpfname);
dbgprint("Rename '$lastarchivetmpfname' to '$lastarchivefname' failed: $!\n");
return 0;
}
return 1;
}
Jun 17, 2016
Jun 17, 2016
189
190
191
sub slurp_archived_file {
my ($domain, $fname, $fdataref) = @_;
my $hashedfname = archive_fname($domain, $fname);
Jun 18, 2016
Jun 18, 2016
192
193
if (not -f $hashedfname) {
Jun 21, 2016
Jun 21, 2016
194
195
196
197
198
if ($ios_archive) {
print STDERR "WARNING: Missing attachment '$hashedfname' ('$domain', '$fname')\n";
} else {
print STDERR "WARNING: Missing attachment '$hashedfname'\n";
}
Jun 18, 2016
Jun 18, 2016
199
200
201
202
$$fdataref = '[MISSING]';
return 0;
}
Jun 20, 2016
Jun 20, 2016
203
if ((not defined read_file($hashedfname, buf_ref => $fdataref, binmode => ':raw', err_mode => 'carp')) or (not defined $fdataref)) {
Jun 17, 2016
Jun 17, 2016
204
205
fail("Couldn't read attachment '$hashedfname': $!");
}
Jun 18, 2016
Jun 18, 2016
206
207
return 1;
Jun 17, 2016
Jun 17, 2016
208
209
}
Jun 21, 2016
Jun 21, 2016
210
211
sub get_image_orientation {
my $fname = shift;
Jun 21, 2016
Jun 21, 2016
212
my $cmdline = "$program_dir/exiftool/exiftool -n -Orientation '$fname' 2>/dev/null";
Jun 21, 2016
Jun 21, 2016
213
214
my $orientation = `$cmdline`;
fail("exiftool failed ('$cmdline')") if ($? != 0);
Jun 21, 2016
Jun 21, 2016
215
216
217
218
219
220
221
222
223
224
225
chomp($orientation);
$orientation =~ s/\AOrientation\s*\:\s*(\d*)\s*\Z/$1/;
dbgprint("File '$fname' has an Orientation of '$orientation'.\n");
return ($orientation eq '') ? undef : int($orientation);
}
sub set_image_orientation {
my $fname = shift;
my $orientation = shift;
my $trash = shift;
if (defined $orientation) {
Jun 22, 2016
Jun 22, 2016
226
my $cmdline = "$program_dir/exiftool/exiftool -overwrite_original_in_place -q -n -Orientation=$orientation '$fname'";
Jun 21, 2016
Jun 21, 2016
227
228
229
230
231
232
233
234
dbgprint("marking image orientation: $cmdline\n");
if (system($cmdline) != 0) {
unlink($fname) if $trash;
fail("exiftool failed ('$cmdline')")
}
}
}
Jul 20, 2019
Jul 20, 2019
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# I ran into an attachment that iOS labeled as 'image/png' but it was actually
# a legal (and not weird as far as I can tell) .jpg file. So read the first
# few bytes and see if it's a jpeg magic number. Maybe we should do this for
# other formats too?
sub check_jpegness {
my $mimetype = shift;
my $fname = shift;
return 1 if $mimetype eq 'image/jpeg'; # we'll believe them for now.
return 0 if not open my $fh, '<:raw', $fname; # oh well.
my $bytes_read = read $fh, my $bytes, 2;
close $fh;
return 0 if $bytes_read != 2;
my ($b1, $b2) = unpack 'C C', $bytes;
return $b1 == 0xFF && $b2 == 0xD8;
}
Jun 20, 2016
Jun 20, 2016
252
253
254
255
256
257
258
259
260
sub load_attachment {
my $origfname = shift;
my $hashedfname = shift;
my $fdataref = shift;
my $mimetype = shift;
my $is_image = $mimetype =~ /\Aimage\//;
my $is_video = $mimetype =~ /\Avideo\//;
if ((defined $attachment_shrink_percent) && ($is_image || $is_video)) {
Jul 20, 2019
Jul 20, 2019
261
my $is_jpeg = check_jpegness($mimetype, $hashedfname);
Jun 21, 2016
Jun 21, 2016
262
my $fmt = $is_jpeg ? '-f mjpeg' : '';
Jun 21, 2016
Jun 21, 2016
263
my $orientation = get_image_orientation($hashedfname);
Jun 20, 2016
Jun 20, 2016
264
265
266
267
my $fract = $attachment_shrink_percent / 100.0;
my $basefname = $origfname;
$basefname =~ s#.*/##;
my $outfname = "$maildir/tmp/imessage-chatlog-tmp-$$-attachment-shrink-$basefname";
Jun 21, 2016
Jun 21, 2016
268
my $cmdline = "$program_dir/ffmpeg $fmt -i '$hashedfname' -vf \"scale='trunc(iw*$fract)+mod(trunc(iw*$fract),2)':'trunc(ih*$fract)+mod(trunc(ih*$fract),2)'\" '$outfname' 2>/dev/null";
Jun 21, 2016
Jun 21, 2016
269
270
dbgprint("shrinking attachment: $cmdline\n");
die("ffmpeg failed ('$cmdline')") if (system($cmdline) != 0);
Jun 21, 2016
Jun 21, 2016
271
set_image_orientation($outfname, $orientation, 1);
Jun 20, 2016
Jun 20, 2016
272
273
274
275
276
277
278
read_file($outfname, buf_ref => $fdataref, binmode => ':raw', err_mode => 'carp');
unlink($outfname);
} else {
read_file($hashedfname, buf_ref => $fdataref, binmode => ':raw', err_mode => 'carp');
}
}
Jun 17, 2016
Jun 17, 2016
279
Jun 16, 2016
Jun 16, 2016
280
281
282
my %longnames = ();
my %shortnames = ();
Jun 21, 2016
Jun 21, 2016
283
# !!! FIXME: this should probably go in a hash or something.
Jun 16, 2016
Jun 16, 2016
284
my $outperson = undef;
285
286
287
288
my $outmsgid = undef;
my $outhandle_id = undef;
my $outid = undef;
my $outtimestamp = undef;
Jun 21, 2016
Jun 21, 2016
289
290
291
292
293
my $outhasfromme = 0;
my $outhasfromthem = 0;
my $outhasfromme_a = 0;
my $outhasfromme_sms = 0;
my $outhasfromme_sms_a = 0;
Jun 21, 2016
Jun 21, 2016
294
295
my $output_text = '';
my $output_html = '';
Jun 16, 2016
Jun 16, 2016
296
297
my @output_attachments = ();
298
sub flush_conversation {
Jun 16, 2016
Jun 16, 2016
299
300
return if (not defined $outmsgid);
301
302
my $trash = shift;
Jun 16, 2016
Jun 16, 2016
303
304
305
dbgprint("Flushing conversation! trash=$trash\n");
if ($trash) {
Jun 23, 2016
Jun 23, 2016
306
$outmsgid = undef;
Jun 21, 2016
Jun 21, 2016
307
308
$output_text = '';
$output_html = '';
Jun 16, 2016
Jun 16, 2016
309
310
311
312
313
314
315
316
317
318
319
320
321
@output_attachments = ();
return;
}
fail("message id went backwards?!") if ($startids{$outhandle_id} > $outmsgid);
$output_text =~ s/\A\n+//;
$output_text =~ s/\n+\Z//;
my $tmpemail = "$maildir/tmp/imessage-chatlog-tmp-$$.txt";
open(TMPEMAIL,'>',$tmpemail) or fail("Failed to open '$tmpemail': $!");
#binmode(TMPEMAIL, ":utf8");
Jun 16, 2016
Jun 16, 2016
322
323
324
my $emaildate = strftime('%a, %d %b %Y %H:%M %Z', localtime($outtimestamp));
my $localdate = strftime('%Y-%m-%d %H:%M:%S %Z', localtime($outtimestamp));
Jun 16, 2016
Jun 16, 2016
325
326
327
328
329
330
# !!! FIXME: make sure these don't collide.
my $mimesha1 = sha1_hex($output_text);
my $mimeboundarymixed = "mime_imessage_mixed_$mimesha1";
my $mimeboundaryalt = "mime_imessage_alt_$mimesha1";
my $has_attachments = scalar(@output_attachments) > 0;
Jun 16, 2016
Jun 16, 2016
331
my $is_mime = $allow_html || $has_attachments;
Jun 16, 2016
Jun 16, 2016
332
my $content_type_mixed = "multipart/mixed; boundary=\"$mimeboundarymixed\"";
Jun 16, 2016
Jun 16, 2016
333
my $content_type_alt = $allow_html ? "multipart/alternative; boundary=\"$mimeboundaryalt\"; charset=\"utf-8\"" : 'text/plain; charset="utf-8"';
Jun 16, 2016
Jun 16, 2016
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
my $initial_content_type = $has_attachments ? $content_type_mixed : $content_type_alt;
print TMPEMAIL <<EOF
Return-Path: <$imessageuser>
Delivered-To: $imessageuser
From: $imessageuserlongname <$imessageuser>
To: $imessageuserlongname <$imessageuser>
Date: $emaildate
Subject: Chat with $outperson at $localdate ...
MIME-Version: 1.0
Content-Type: $initial_content_type
Content-Transfer-Encoding: binary
X-Mailer: archive_imessage.pl $VERSION
EOF
;
Jun 16, 2016
Jun 16, 2016
351
352
353
354
355
356
if ($is_mime) {
print TMPEMAIL "This is a multipart message in MIME format.\n\n";
}
if (@output_attachments) {
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
357
358
359
360
361
362
--$mimeboundarymixed
Content-Type: $content_type_alt
Content-Transfer-Encoding: binary
EOF
;
Jun 16, 2016
Jun 16, 2016
363
}
Jun 16, 2016
Jun 16, 2016
364
Jun 16, 2016
Jun 16, 2016
365
366
367
368
if (not $allow_html) {
print TMPEMAIL "$output_text";
print TMPEMAIL "\n\n";
} else {
Jun 21, 2016
Jun 21, 2016
369
370
# This <style> section is largely based on:
# https://codepen.io/samuelkraft/pen/Farhl/
Jun 16, 2016
Jun 16, 2016
371
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
372
373
374
375
376
--$mimeboundaryalt
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: binary
$output_text
Jun 16, 2016
Jun 16, 2016
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
--$mimeboundaryalt
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: binary
<html><head><title>Chat with $outperson at $localdate ...</title><style>
body {
font-family: "Helvetica Neue";
font-size: 20px;
font-weight: normal;
}
section {
max-width: 450px;
margin: 50px auto;
}
section div {
max-width: 255px;
word-wrap: break-word;
margin-bottom: 10px;
line-height: 24px;
}
.clear {
clear: both;
}
Jun 21, 2016
Jun 21, 2016
401
402
EOF
;
Jun 16, 2016
Jun 16, 2016
403
Jun 21, 2016
Jun 21, 2016
404
405
406
# Don't output parts of the CSS we don't need to save a little space.
if ($outhasfromme) {
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
.from-me {
position: relative;
padding: 10px 20px;
color: white;
background: #0B93F6;
border-radius: 25px;
float: right;
}
.from-me:before {
content: "";
position: absolute;
z-index: -1;
bottom: -2px;
right: -7px;
height: 20px;
border-right: 20px solid #0B93F6;
border-bottom-left-radius: 16px 14px;
transform: translate(0, -2px);
}
.from-me:after {
content: "";
position: absolute;
z-index: 1;
bottom: -2px;
right: -56px;
width: 26px;
height: 20px;
background: white;
border-bottom-left-radius: 10px;
transform: translate(-30px, -2px);
}
Jun 21, 2016
Jun 21, 2016
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
EOF
;
}
if ($outhasfromme_a) {
print TMPEMAIL <<EOF
.from-me a {
color: white;
background: #0B93F6;
}
EOF
;
}
if ($outhasfromme_sms) {
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
454
455
456
457
458
459
.sms {
background: #04D74A;
}
.sms:before {
border-right: 20px solid #04D74A;
}
Jun 21, 2016
Jun 21, 2016
460
461
462
463
464
465
EOF
;
}
if ($outhasfromme_sms_a) {
print TMPEMAIL <<EOF
Jun 21, 2016
Jun 21, 2016
466
467
468
469
.sms a {
color: white;
background: #04D74A;
}
Jun 21, 2016
Jun 21, 2016
470
471
472
473
474
475
EOF
;
}
if ($outhasfromthem) {
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
.from-them {
position: relative;
padding: 10px 20px;
background: #E5E5EA;
border-radius: 25px;
color: black;
float: left;
}
.from-them:before {
content: "";
position: absolute;
z-index: 2;
bottom: -2px;
left: -7px;
height: 20px;
border-left: 20px solid #E5E5EA;
border-bottom-right-radius: 16px 14px;
transform: translate(0, -2px);
}
.from-them:after {
content: "";
position: absolute;
z-index: 3;
bottom: -2px;
left: 4px;
width: 26px;
height: 20px;
background: white;
border-bottom-right-radius: 10px;
transform: translate(-30px, -2px);
}
Jun 21, 2016
Jun 21, 2016
507
508
509
510
511
EOF
;
}
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
512
513
514
515
516
517
518
519
</style></head><body><section>
$output_html</section></body></html>
--$mimeboundaryalt--
EOF
;
Jun 16, 2016
Jun 16, 2016
520
521
}
Jun 16, 2016
Jun 16, 2016
522
523
524
525
526
if (@output_attachments) {
my %used_fnames = ();
while (@output_attachments) {
my $fname = shift @output_attachments;
my $mimetype = shift @output_attachments;
Jun 20, 2016
Jun 20, 2016
527
my $domain = 'MediaDomain';
Jun 16, 2016
Jun 16, 2016
528
Aug 17, 2016
Aug 17, 2016
529
530
$fname =~ s#\A\~/Library/Messages/## if (!$ios_archive);
$fname =~ s#\A\~/##;
Jun 21, 2016
Jun 21, 2016
531
$fname =~ s#\A/var/mobile/## if ($ios_archive);
Jun 20, 2016
Jun 20, 2016
532
533
534
535
my $hashedfname = archive_fname($domain, $fname);
my $fdata = undef;
if (not -f $hashedfname) {
Jun 21, 2016
Jun 21, 2016
536
537
538
539
540
if ($ios_archive) {
print STDERR "WARNING: Missing attachment '$hashedfname' ('$domain', '$fname')\n";
} else {
print STDERR "WARNING: Missing attachment '$hashedfname'\n";
}
Jun 20, 2016
Jun 20, 2016
541
542
} else {
load_attachment($fname, $hashedfname, \$fdata, $mimetype);
Jun 21, 2016
Jun 21, 2016
543
544
545
546
547
if ($ios_archive) {
print STDERR "WARNING: Failed to load '$hashedfname' ('$domain', '$fname')\n" if (not defined $fdata);
} else {
print STDERR "WARNING: Failed to load '$hashedfname'\n" if (not defined $fdata);
}
Jun 20, 2016
Jun 20, 2016
548
}
Jun 16, 2016
Jun 16, 2016
549
550
551
552
553
554
555
556
557
558
559
$fname =~ s#\A.*/##;
my $tmpfname = $fname;
my $counter = 0;
while (defined $used_fnames{$tmpfname}) {
$counter++;
$tmpfname = "$counter-$fname";
}
$fname = $tmpfname;
$used_fnames{$fname} = 1;
Jun 20, 2016
Jun 20, 2016
560
if (not defined $fdata) {
Jun 18, 2016
Jun 18, 2016
561
562
563
564
565
566
567
568
569
570
571
572
573
print TMPEMAIL <<EOF
--$mimeboundarymixed
Content-Disposition: attachment; filename="$fname"
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: binary
This file was missing in the iPhone backup (or there was a bug) when this
archive was produced. Sorry!
EOF
;
} else {
print TMPEMAIL <<EOF
Jun 16, 2016
Jun 16, 2016
574
575
576
577
578
579
580
581
--$mimeboundarymixed
Content-Disposition: attachment; filename="$fname"
Content-Type: $mimetype
Content-Transfer-Encoding: base64
EOF
;
Jun 18, 2016
Jun 18, 2016
582
583
584
585
print TMPEMAIL encode_base64($fdata);
print TMPEMAIL "\n";
$fdata = undef;
}
Jun 16, 2016
Jun 16, 2016
587
588
589
590
591
592
print TMPEMAIL "--$mimeboundarymixed--\n\n";
}
close(TMPEMAIL);
Jun 21, 2016
Jun 21, 2016
593
594
$output_text = '';
$output_html = '';
Jun 16, 2016
Jun 16, 2016
595
596
597
598
599
@output_attachments = ();
my $size = (stat($tmpemail))[7];
my $t = $outtimestamp;
my $outfile = "$t.$outid.imessage-chatlog.$imessageuser,S=$size";
Aug 17, 2016
Aug 17, 2016
600
601
602
603
604
605
606
607
608
609
610
if ($mbox) {
my $mboxtime = asctime(localtime($outtimestamp));
chomp($mboxtime);
print MBOX "From $imessageuser $mboxtime\n";
open(TMPEMAIL,'<',$tmpemail) or fail("Failed to open '$tmpemail': $!");
while (<TMPEMAIL>) {
s/\A(\>*From )/>$1/;
print MBOX $_;
}
close(TMPEMAIL);
unlink($tmpemail);
Jun 16, 2016
Jun 16, 2016
611
} else {
Aug 17, 2016
Aug 17, 2016
612
613
614
615
616
617
618
619
620
621
$outfile =~ s#/#_#g;
$outfile = "$maildir/new/$outfile";
if (move($tmpemail, $outfile)) {
utime $t, $t, $outfile; # force it to collection creation time.
dbgprint "archived '$outfile'\n";
system("cat $outfile") if ($debug);
} else {
unlink($outfile);
fail("Rename '$tmpemail' to '$outfile' failed: $!");
}
Jun 16, 2016
Jun 16, 2016
622
623
624
625
}
# !!! FIXME: this may cause duplicates if there's a power failure RIGHT HERE.
if (not flush_startid($outhandle_id, $outmsgid)) {
Aug 17, 2016
Aug 17, 2016
626
unlink($outfile) if (not $mbox);
Jun 16, 2016
Jun 16, 2016
627
fail("didn't flush startids");
628
629
630
631
632
}
}
sub split_date_time {
my $timestamp = shift;
Jun 16, 2016
Jun 16, 2016
633
634
my $date = strftime('%Y-%m-%d', localtime($timestamp));
my $time = strftime('%H:%M', localtime($timestamp));
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
dbgprint("split $timestamp => '$date', '$time'\n");
return ($date, $time);
}
# don't care if these fail.
mkdir("$maildir", 0700);
mkdir("$maildir/tmp", 0700);
mkdir("$maildir/cur", 0700);
mkdir("$maildir/new", 0700);
$lastarchivetmpfname = "$maildir/tmp_imessage_last_archive_msgids.txt";
unlink($lastarchivetmpfname);
$lastarchivefname = "$maildir/imessage_last_archive_msgids.txt";
if (open(LASTID,'<',$lastarchivefname)) {
my $globalid = <LASTID>;
chomp($globalid);
$startid = $globalid if ($globalid =~ /\A\d+\Z/);
dbgprint("startid (global) == $globalid\n");
while (not eof(LASTID)) {
my $user = <LASTID>;
chomp($user);
my $id = <LASTID>;
chomp($id);
if ($id =~ /\A\d+\Z/) {
$startids{$user} = $id;
dbgprint("startid '$user' == $id\n");
}
}
close(LASTID);
}
Jun 21, 2016
Jun 21, 2016
668
669
670
my $stmt;
my $dbname = archive_fname('HomeDomain', $ios_archive ? 'Library/SMS/sms.db' : 'chat.db');
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
dbgprint("message database is '$dbname'\n");
my $db = DBI->connect("DBI:SQLite:dbname=$dbname", '', '', { RaiseError => 0 })
or fail("Couldn't open message database at '$archivedir/$dbname': " . $DBI::errstr);
dbgprint("Sorting out real names...\n");
sub parse_addressbook_name {
my @lookuprow = @_;
my $address = shift @lookuprow;
my $nickname = shift @lookuprow;
my $firstname = $lookuprow[0];
my $proper = undef;
dbgprint("ADDRESSBOOK NICKNAME: $nickname\n") if defined $nickname;
foreach (@lookuprow) {
next if not defined $_;
dbgprint("ADDRESSBOOK ROW: $_\n");
$proper .= ' ' if defined $proper;
$proper .= $_;
}
if (defined $nickname) {
if (not defined $proper) {
$proper = $nickname;
} else {
$proper .= " (\"$nickname\")";
}
}
if (not defined $proper) {
dbgprint("WARNING: No proper name in the address book for '$address'\n");
$proper = $address;
}
my $longname = $proper;
my $shortname;
if (defined $nickname) {
$shortname = $nickname;
} elsif (defined $firstname) {
$shortname = $firstname;
} else {
$shortname = $proper;
}
return ($longname, $shortname);
}
Jun 21, 2016
Jun 21, 2016
718
719
720
721
722
723
724
725
726
727
my $addressbookdbname = undef; # only used on iOS archives right now.
my $addressbookdb = undef; # only used on iOS archives right now.
my $lookupstmt = undef; # only used on iOS archives right now.
if ($ios_archive) {
$addressbookdbname = archive_fname('HomeDomain', 'Library/AddressBook/AddressBook.sqlitedb');
dbgprint("address book database is '$addressbookdbname'\n");
$addressbookdb = DBI->connect("DBI:SQLite:dbname=$addressbookdbname", '', '', { RaiseError => 0 })
or fail("Couldn't open addressbook database at '$archivedir/$addressbookdbname': " . $DBI::errstr);
Jan 1, 2017
Jan 1, 2017
728
729
730
731
732
$lookupstmt = $addressbookdb->prepare('select c15Phone, c16Email, c11Nickname, c0First, c2Middle, c1Last from ABPersonFullTextSearch_content where ((c15Phone LIKE ?) or (c15Phone LIKE ?) or (c15Phone LIKE ?) or (c16Email LIKE ?) or (c16Email LIKE ?) or (c16Email LIKE ?)) limit 1;');
if (not $lookupstmt) { # this changed in iOS 10.2
$lookupstmt = $addressbookdb->prepare('select c16Phone, c17Email, c12Nickname, c0First, c2Middle, c1Last from ABPersonFullTextSearch_content where ((c16Phone LIKE ?) or (c16Phone LIKE ?) or (c16Phone LIKE ?) or (c17Email LIKE ?) or (c17Email LIKE ?) or (c17Email LIKE ?)) limit 1;')
or fail("Couldn't prepare name lookup SELECT statement: " . $DBI::errstr);
}
Jun 21, 2016
Jun 21, 2016
733
}
Jun 21, 2016
Jun 21, 2016
735
736
sub lookup_ios_address {
my $address = shift;
Jun 22, 2016
Jun 22, 2016
737
738
739
my $like1 = "$address %";
my $like2 = "% $address %";
my $like3 = "% $address";
Jun 22, 2016
Jun 22, 2016
741
$lookupstmt->execute($like1, $like2, $like3, $like1, $like2, $like3) or fail("Couldn't execute name lookup SELECT statement: " . $DBI::errstr);
742
743
744
745
746
747
748
749
750
751
my @lookuprow = $lookupstmt->fetchrow_array();
if (@lookuprow) {
my $phone = shift @lookuprow;
my $email = shift @lookuprow;
dbgprint("EMAIL: $email\n") if defined $email;
dbgprint("PHONE: $phone\n") if defined $phone;
} else {
@lookuprow = (undef, undef, undef, undef);
}
Jun 21, 2016
Jun 21, 2016
752
753
return @lookuprow;
}
Jun 21, 2016
Jun 21, 2016
755
756
757
758
my %mac_addressbook = ();
if (not $ios_archive) {
%mac_addressbook = ();
Aug 17, 2016
Aug 17, 2016
759
open(HELPERIO, '-|', "$program_dir/dump_mac_addressbook") or die("Can't run $program_dir/dump_mac_addressbook: $!\n");
Jun 21, 2016
Jun 21, 2016
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
my @lines = ();
while (<HELPERIO>) {
chomp;
dbgprint("dump_mac_addressbook line: '$_'\n");
push @lines, $_;
}
close(HELPERIO);
my @person = ();
while (@lines) {
for (my $i = 0; $i < 4; $i++ ) {
my $x = shift @lines;
last if not defined $x;
push @person, $x eq '' ? undef : $x;
}
if (scalar(@person) != 4) {
dbgprint("incomplete record from dump_mac_addressbook!\n");
last;
} elsif ($debug) {
my ($a, $b, $c, $d) = @person;
$a = '' if not defined $a;
$b = '' if not defined $b;
$c = '' if not defined $c;
$d = '' if not defined $d;
dbgprint("Person from dump_mac_addressbook: [$a] [$b] [$c] [$d]\n");
}
# Phone numbers...flatten them down.
while (@lines) {
my $x = shift @lines;
last if (not defined $x) || ($x eq '');
$x =~ s/[^0-9]//g; # flatten.
Jun 22, 2016
Jun 22, 2016
794
$x =~ s/\A1//; # take out US country code
Jun 21, 2016
Jun 21, 2016
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
$mac_addressbook{$x} = [ @person ];
dbgprint("Person phone: [$x]\n");
}
# Emails...lowercase them.
while (@lines) {
my $x = shift @lines;
last if (not defined $x) || ($x eq '');
$mac_addressbook{lc($x)} = [ @person ];
dbgprint("Person email: [$x]\n");
}
@person = ();
}
dbgprint("Done pulling in Mac address book.\n");
}
sub lookup_macos_address {
my $address = shift;
# !!! FIXME: this all sucks.
my $phone = $address;
$phone =~ s/[^0-9]//g; # flatten.
Jun 22, 2016
Jun 22, 2016
819
$phone =~ s/\A1//; # remove US country code
Jun 21, 2016
Jun 21, 2016
820
821
822
823
my $email = lc($address);
my @lookuprow = ();
foreach (keys(%mac_addressbook)) {
Jun 22, 2016
Jun 22, 2016
824
if ( ($_ eq $email) || ($_ eq $phone) ) {
Jun 21, 2016
Jun 21, 2016
825
826
827
828
829
830
831
832
833
834
835
836
837
my $person = $mac_addressbook{$_};
@lookuprow = @$person;
last;
}
}
while (scalar(@lookuprow) < 4) {
push @lookuprow, undef;
}
return @lookuprow;
}
Jun 21, 2016
Jun 21, 2016
838
839
sub lookup_address {
my ($handleid, $address) = @_;
Jun 21, 2016
Jun 21, 2016
840
841
dbgprint("looking for $address...\n");
my @lookuprow = $ios_archive ? lookup_ios_address($address) : lookup_macos_address($address);
842
843
844
845
846
($longnames{$handleid}, $shortnames{$handleid}) = parse_addressbook_name($address, @lookuprow);
dbgprint("longname for $address ($handleid) == " . $longnames{$handleid} . "\n");
dbgprint("shortname for $address ($handleid) == " . $shortnames{$handleid} . "\n");
}
Jun 21, 2016
Jun 21, 2016
847
848
849
$stmt = $db->prepare('select m.handle_id, h.id from handle as h inner join (select distinct handle_id from message) m on m.handle_id=h.ROWID;')
or fail("Couldn't prepare distinct address SELECT statement: " . $DBI::errstr);
$stmt->execute() or fail("Couldn't execute distinct address SELECT statement: " . $DBI::errstr);
Jun 21, 2016
Jun 21, 2016
851
852
while (my @row = $stmt->fetchrow_array()) {
lookup_address(@row);
Jun 21, 2016
Jun 21, 2016
855
856
857
$stmt = $db->prepare('select distinct account from message;')
or fail("Couldn't prepare distinct account SELECT statement: " . $DBI::errstr);
$stmt->execute() or fail("Couldn't execute distinct address SELECT statement: " . $DBI::errstr);
Jun 16, 2016
Jun 16, 2016
858
Jun 21, 2016
Jun 21, 2016
859
my $default_account = undef;
Jun 21, 2016
Jun 21, 2016
860
861
while (my @row = $stmt->fetchrow_array()) {
my $account = shift @row;
Jun 21, 2016
Jun 21, 2016
862
next if not defined $account;
Jun 21, 2016
Jun 21, 2016
863
864
my $address = $account;
$address =~ s/\A[ep]\://i or fail("Unexpected account format '$account'");
Jun 21, 2016
Jun 21, 2016
865
next if $address eq '';
Jun 21, 2016
Jun 21, 2016
866
867
dbgprint("distinct account: '$account' -> '$address'\n");
lookup_address($account, $address);
Jun 21, 2016
Jun 21, 2016
868
869
870
871
872
873
874
875
$default_account = $account if not defined $default_account; # oh well.
}
if (not defined $default_account) {
dbgprint("Ugh, forcing a default account.\n");
$default_account = 'e:donotreply@icloud.com'; # oh well.
$longnames{$default_account} = 'Unknown User';
$shortnames{$default_account} = 'Unknown';
Jun 21, 2016
Jun 21, 2016
876
}
Jun 21, 2016
Jun 21, 2016
878
879
%mac_addressbook = (); # dump all this, we're done with it.
880
$lookupstmt = undef;
Jun 21, 2016
Jun 21, 2016
881
$addressbookdb->disconnect() if (defined $addressbookdb);
882
883
$addressbookdb = undef;
Aug 17, 2016
Aug 17, 2016
884
885
886
887
if ($mbox) {
my $mboxfname = "$maildir/imessage_archive.mbox";
open(MBOX, '>>', $mboxfname) or fail("Couldn't open '$mboxfname' for append: $!");
}
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
dbgprint("Parsing messages...\n");
sub talk_gap {
my ($a, $b) = @_;
my $time1 = ($a < $b) ? $a : $b;
my $time2 = ($a < $b) ? $b : $a;
return (($time2 - $time1) >= $gaptime);
}
my $lastspeaker = '';
my $lastdate = 0;
my $lastday = '';
my $lasthandle_id = 0;
my $alias = undef;
Jun 21, 2016
Jun 21, 2016
903
my $thisimessageuseralias = undef;
904
905
906
my $startmsgid = undef;
my $newestmsgid = 0;
Jun 20, 2016
Jun 20, 2016
907
908
909
my $donerows = 0;
my $totalrows = undef;
my $percentdone = -1;
Jun 20, 2016
Jun 20, 2016
910
911
912
913
914
915
916
917
$stmt = $db->prepare('select ROWID from message order by ROWID desc limit 1;') or fail("Couldn't prepare row count SELECT statement: " . $DBI::errstr);
$stmt->execute() or fail("Couldn't execute row count SELECT statement: " . $DBI::errstr);
my $ending_startid = $startid;
if (my @row = $stmt->fetchrow_array()) {
$ending_startid = $row[0];
}
Jun 20, 2016
Jun 20, 2016
918
919
920
921
922
923
924
if ($report_progress) {
$stmt = $db->prepare('select count(*) from message where (ROWID > ?)') or fail("Couldn't prepare message count SELECT statement: " . $DBI::errstr);
$stmt->execute($startid) or fail("Couldn't execute message count SELECT statement: " . $DBI::errstr);
my @row = $stmt->fetchrow_array();
$totalrows = $row[0];
}
Jun 21, 2016
Jun 21, 2016
925
926
# We filter to iMessage and SMS, in case some other iChat service landed in here too.
$stmt = $db->prepare("select h.id, m.ROWID, m.text, m.service, m.account, m.handle_id, m.subject, m.date, m.is_emote, m.is_from_me, m.was_downgraded, m.is_audio_message, m.cache_has_attachments from message as m inner join handle as h on m.handle_id=h.ROWID where (m.ROWID > ?) and (m.service='iMessage' or m.service='SMS') order by m.handle_id, m.ROWID;")
927
928
929
930
931
or fail("Couldn't prepare message SELECT statement: " . $DBI::errstr);
my $attachmentstmt = $db->prepare('select filename, mime_type from attachment as a inner join (select rowid,attachment_id from message_attachment_join where message_id=?) as j where a.ROWID=j.attachment_id order by j.ROWID;')
or fail("Couldn't prepare attachment lookup SELECT statement: " . $DBI::errstr);
Jun 18, 2016
Jun 18, 2016
932
933
$stmt->execute($startid) or fail("Couldn't execute message SELECT statement: " . $DBI::errstr);
934
935
936
937
938
939
940
941
while (my @row = $stmt->fetchrow_array()) {
if ($debug) {
dbgprint("New row:\n");
foreach(@row) {
dbgprint(defined $_ ? " $_\n" : " [undef]\n");
}
}
Jun 20, 2016
Jun 20, 2016
942
943
944
945
946
947
948
949
950
if ($report_progress) {
my $newpct = int(($donerows / $totalrows) * 100.0);
if ($newpct != $percentdone) {
$percentdone = $newpct;
print("Processed $donerows messages of $totalrows ($percentdone%)\n");
}
}
$donerows++;
Jun 16, 2016
Jun 16, 2016
951
my ($idname, $msgid, $text, $service, $account, $handle_id, $subject, $date, $is_emote, $is_from_me, $was_downgraded, $is_audio_message, $cache_has_attachments) = @row;
952
953
next if not defined $text;
Jul 20, 2019
Jul 20, 2019
954
955
956
957
958
959
# This is probably from after Apple moved from seconds to nanoseconds
# (High Sierra and equivalent iOS releases).
if ($date > 99999999999) {
$date /= 1000000000;
}
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
# Convert from Cocoa epoch to Unix epoch (2001 -> 1970).
$date += 978307200;
$startmsgid = $msgid if (not defined $startmsgid);
if (not defined $startids{$handle_id}) {
my $with = $longnames{$handle_id};
dbgprint("Flushing new per-user startid for $idname ('$with')\n");
if (not flush_startid($handle_id, 0)) {
fail("didn't flush new startid for $idname ('$with')");
}
}
if (($now - $date) < $gaptime) {
dbgprint("timestamp '$date' is less than $gaptime seconds old.\n");
Jun 20, 2016
Jun 20, 2016
975
if ($msgid < $ending_startid) {
Jun 23, 2016
Jun 23, 2016
976
$ending_startid = $startmsgid - 1;
Jun 20, 2016
Jun 20, 2016
977
dbgprint("forcing global startid to $ending_startid\n");
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
}
# trash this conversation, it might still be ongoing.
flush_conversation(1) if ($handle_id == $lasthandle_id);
next;
}
$newestmsgid = $msgid if ($msgid > $newestmsgid);
# this happens if we had a conversation that was still ongoing when a
# newer conversation got archived. Next run, the newer conversation
# gets pulled from the database again so we can recheck the older
# conversation.
if ($msgid <= $startids{$handle_id}) {
dbgprint("msgid $msgid is already archived.\n");
next;
}
# Try to merge collections that appear to be the same conversation...
if (($handle_id != $lasthandle_id) or (talk_gap($lastdate, $date))) {
Jun 23, 2016
Jun 23, 2016
997
998
999
dbgprint("This appears to be a new conversation.\n");
flush_conversation(0); # dump whatever might be pending.