Revision 851 (by ahitrov, 2023/08/15 13:17:16) local lib path
#!/usr/bin/env perl

use strict;
use warnings "all";
use locale;

BEGIN { require './inc.pl' };

use Contenido::Globals;
use Contenido::Init;
use ErrorTee;
use PidFile;
use Data::Dumper;

# begin
Contenido::Init->init();

my $keeper_module = $state->project.'::Keeper';
$keeper = $keeper_module->new($state);
$DEBUG = 0;

#PidFile->new($keeper, compat=>1);                # db-based locking (run only on one host)
#PidFile->new($keeper, compat=>1, per_host=>1);   # db-based locking (run on whole cluster)

############################################
# please use:
#     $state->{log_dir} for logging
#     $state->{tmp_dir} for temporary files
###########################################
$keeper->t_connect() || die $keeper->error();
my $ids = $keeper->TSQL->selectall_arrayref("SELECT id FROM mailqueue WHERE status = 0 and dtime <= CURRENT_TIMESTAMP ORDER BY ctime LIMIT 5");
if ( ref $ids eq 'ARRAY' && @$ids ) {
	$keeper->TSQL->do("UPDATE mailqueue SET status = 2 WHERE ID IN (".join(',', ('?') x scalar @$ids).")", {}, map { $_->[0] } @$ids);
}
$keeper->t_finish();

my $now = Contenido::DateTime->new;
if ( @$ids ) {
	my $sendmail = Contenido::Mail->new();
	foreach my $row ( @$ids ) {
		my $mail = $keeper->get_document_by_id($row->[0], class => 'Contenido::Email');
		if ( ref $mail ) {
			my $data = {
				to	=> [split /,\s*/, $mail->name],
				subject	=> $mail->subject,
				body	=> $mail->body_html,
			};
			if ( $mail->cc ) {
				$data->{cc} = [split /\n/, $mail->cc];
			}
			if ( $mail->from ) {
				$data->{from} = $mail->from;
			}
			if ( $mail->body_text ) {
				$data->{text} = $mail->body_text;
			}
			if ( my $err = $sendmail->send({ email => $data }) ) {
				$mail->status( 3 );
				$mail->error( $err );
			} else {
				$mail->status( 1 );
				$mail->etime( $now->ymd('-').' '.$now->hms );
				$mail->error( undef );
			}
			$mail->store;
		}
	}
}