readceb/sql2txt.pl

86 lines
2.2 KiB
Perl

#!/usr/bin/env perl
use DBI;
use Modern::Perl '2024';
use DateTime;
my $local_time_zone = DateTime::TimeZone->new( name => 'local' );
my $dbh = DBI->connect("dbi:SQLite:dbname=$ARGV[0]","","");
my $account = $dbh->selectrow_hashref("select uuid,username,server,resource from accounts limit 1");
say "Generating logs for $account->{username} at $account->{server}...";
# Create directory
my $dirname = "$account->{username}"."@"."$account->{server}";
mkdir $dirname;
mkdir $dirname."/group";
mkdir $dirname."/1on1";
# Get conversations
my $sth_conv = $dbh->prepare("select uuid,mode,contactJid from conversations where accountUuid=?");
my $sth_msg = $dbh->prepare("select body,status,timeSent,counterpart,type from messages where conversationUuid=? order by timeSent asc");
$sth_conv->bind_param(1, $account->{uuid});
$sth_conv->execute();
# Loop through conversations
while(my $conv = $sth_conv->fetchrow_hashref) {
$sth_msg->execute($conv->{uuid});
# Conversation directory
my $is_group = $conv->{mode} == 1;
my $barejid = (split '/', $conv->{contactJid})[0];
my $convdir = $dirname.($is_group ? "/group/" : "/1on1/")."$barejid";
mkdir $convdir or die "Can't make $convdir: $!";
# Loop through messages
my $cur_date = '0';
my $FH_msg = undef;
while (my $msg = $sth_msg->fetchrow_hashref) {
# Convert to a datetime
my $msg_dt = DateTime->from_epoch(
epoch => $msg->{timeSent}/1000,
time_zone => $local_time_zone,
);
my $date = $msg_dt->ymd('-');
# Make new text file...
if ($date ne $cur_date) {
if (defined $FH_msg) {
close ($FH_msg);
}
open ($FH_msg, '>', $convdir."/".$date.".txt") or die "Can't open: $!";
$cur_date = $date;
}
# Get timestamp
my $timestamp = $msg_dt->hms(':');
print $FH_msg '[', $timestamp, '] ';
# 0 = recieved
if ($msg->{status} == 0) {
if ($is_group) {
print $FH_msg (split '/', $msg->{counterpart})[-1], ': ';
} else {
print $FH_msg $barejid, ': ';
}
} else {
if ($is_group) {
print $FH_msg (split '/', $msg->{counterpart})[-1], ' (you): ';
} else {
print $FH_msg $account->{username}, '@', $account->{server}, ': ';
}
}
# TODO: Body
print $FH_msg $msg->{body}, "\n";
}
}