-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonica_reminder
executable file
·567 lines (493 loc) · 17.5 KB
/
monica_reminder
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2023 Ian2020 <https://github.com/Ian2020>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Monica reminder is a BASH script that will takeover the emailing of reminders
# for a Monica instance if you are experiencing problems.
#
# For full copyright information see the AUTHORS file at the top-level
# directory of this distribution or at
# [AUTHORS](https://github.com/Ian2020/monica_reminder/AUTHORS.md)
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <https://www.gnu.org/licenses/>.
declare -gar monthsdays=(31 28 31 30 31 30 31 31 30 31 30 31)
monicaremindersendphp=$(cat << "EOF"
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class MonicaReminderSend extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monica:monica-reminder-send
{--email= : The email address to send to}
{--subject= : The email subject}
{--body= : The email body to send}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send a monica_reminder email';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// retrieve the email from the option
$email = $this->option('email');
$subject = $this->option('subject');
$body = $this->option('body');
if (! $email) {
$email = $this->ask('What email address should I send the email to?');
}
// Validate user provided email address
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$this->error('Invalid email address: "'.$email.'".');
return -1;
}
if (! $subject) {
$subject = $this->ask('What subject should I use for the email?');
}
if (! $body) {
$body = $this->ask('What email body should I send?');
}
$this->info('Preparing and sending email to "'.$email.'"');
// immediately deliver the test email (bypassing the queue)
Mail::raw(
$body,
function ($message) use ($email, $subject) {
$message->to($email)
->subject($subject);
}
);
$this->info('Email sent!');
return 0;
}
}
EOF
)
relaunchincontainer() {
if command -v podman > /dev/null 2>&1; then conmgr=podman;
elif command -v docker > /dev/null 2>&1; then conmgr=docker;
else echo "monica_reminder: neither podman nor docker installed!";exit 1; fi
"$conmgr" cp "$0" "$CONTAINER:/usr/local/bin/monica_reminder" || {
rc=$? ; echo "monica_reminder: failed to insert ourselves into container $CONTAINER" ; exit "$rc"
}
"$conmgr" exec -e=DRYRUN -e=TODAY -e=NOSEND -e=LOGDIR -e=LOGROTATEDAY -e=DATA_HOME \
"$CONTAINER" monica_reminder || {
rc=$? ; echo "monica_reminder: failed to execute inside container $CONTAINER" ; exit "$rc"
}
exit 0
}
initdatahome() {
DATA_HOME=${DATA_HOME:-"/var/www/html/storage"}/$(basename "$0")
if [[ ! -d "$DATA_HOME" ]]; then
if ! mkdir -p "$DATA_HOME"; then
log "failed to create DATA_HOME: $DATA_HOME, running as user: $(whoami)" ; exit 1
fi
fi
if [[ ! -w "$DATA_HOME" ]]; then
log "no permission to write to DATA_HOME: $DATA_HOME, running as user: $(whoami)" ; exit 1
fi
#Don't delete state on dry runs
if [ "$DRYRUN" != "true" ]; then
# Be very specific on filenames so even less chance of deleting wrong thing
if ! find "$DATA_HOME" -type f -name "*_????-??-??_*" -mtime +500 -exec rm {} \;; then
log "failed to clean old data files. Aborting" ; exit 1
fi
fi
}
sendsmtp() {
local _email;_email="$1";shift
local _subject;_subject="$1";shift
local _body;_body="$1";shift
local _maillog;
[ "$NOSEND" == "true" ] ||
_maillog=$(php artisan monica:monica-reminder-send \
--email="$_email" \
--subject="$_subject" \
--body="$_body") || {
log "mailing failed"
log "$_maillog"
exit 1
}
}
sendmail() {
local _initialdate;_initialdate="$1";shift # initial date YYYY-MM-DD
local _email;_email="$1";shift # email address
local _emailnice;_emailnice="$1";shift # preferred name for recipient
local -i _nthday;_nthday="$1";shift # This is nth day reminder (can be 0)
local _contact;_contact="$1";shift # The contact
local _title;_title="$1";shift # Title of the reminder
local _late;_late="$1";shift # Is this reminder late? true/false
# Convert date to human-readable
_initialdate=$(date -d "$_initialdate" +"%a %-d %b")
local _bodyprefix
local _bodypostfix
local _subjectprefix=""
if [[ "$_late" = "true" ]]; then
_subjectprefix="[LATE] "
fi
if [[ "$_nthday" -eq 0 ]]; then
_subjectprefix+="It's today! Reminder"
_bodyprefix="It's today! Here's your reminder"
_bodypostfix="$_contact"
else
_subjectprefix+="$_nthday day reminder"
_bodyprefix="It's exactly $_nthday days until the anniversary of"
_bodypostfix="$_contact on $_initialdate"
fi
local _subject="$_subjectprefix regarding $_contact - $_title"
local _body="\
Dear $_emailnice,
$_bodyprefix \"$_title\" for $_bodypostfix.
You asked me to let you know. Now you know!
Monica xoxo
"
log "Send following message to: $_email"
log "Subject: $_subject"
log "$_body"
[ "$DRYRUN" == "true" ] || sendsmtp "$_email" "$_subject" "$_body"
}
leapyear() {
local -i _year;_year=$1;shift
if [ $(( _year % 4 )) -eq 0 ] &&
! { [ $(( _year % 100 )) -eq 0 ] && [ ! $(( _year % 400 )) -eq 0 ]; }; then
echo "true"; return
fi
echo "false"
}
timespan() {
# Returns timespan between two dates in the quantity specified
local _date1=$1;shift # in ISO format
local _date2=$1;shift # in ISO format
local _quanta=$1;shift # year|month|week|second
# Check the dates valid
date -d "$_date1" > /dev/null 2>&1 || return 1
date -d "$_date2" > /dev/null 2>&1 || return 1
if [[ -z "$_date1" || -z "$_date2" ]]; then
log "timespan: one of the dates was empty: _date1: $_date1, _date2: $_date2"
return 1
fi
if [[ "$_date1" > "$_date2" ]]; then
log "timespan: _date1: $_date1 was later than _date2: $_date2, \
we expect them supplied in chronological order"
return 1
fi
# 10# forces base 10 as leading zeros are otherwise seen as octal
local -i _date1_year="${_date1:0:4}"
local -i _date1_month=10#"${_date1:5:2}"
local -i _date1_day=10#"${_date1:8:2}"
local -i _date2_year="${_date2:0:4}"
local -i _date2_month=10#"${_date2:5:2}"
local -i _date2_day=10#"${_date2:8:2}"
case "$_quanta" in
"year")
local -i _addition
if [[ "$_date2_month" -gt "$_date1_month" ]]; then
_addition=0
elif [[ "$_date2_month" -eq "$_date1_month" ]]; then
_addition=-1
if [[ "$_date2_day" -ge "$_date1_day" ]]; then
_addition=0
fi
else
_addition=-1
fi
local -i _years
_years=$(( (_date2_year - _date1_year) + _addition ))
if [[ "$_years" -lt 0 ]]; then _years=0; fi
echo "$_years"
;;
"month")
_months=$(( (_date2_year - _date1_year) * 12 ))
_months=$(( _months + (_date2_month - _date1_month) ))
if [[ "$_date2_day" -lt "$_date1_day" ]] && [[ "$_months" -gt 0 ]]; then
_months=$(( _months - 1 ))
fi
echo "$_months"
;;
"week")
local -i _date1_secs; _date1_secs=$(date -d "$_date1" +%s) || return 1
local -i _date2_secs; _date2_secs=$(date -d "$_date2" +%s) || return 1
echo $(( (_date2_secs - _date1_secs) / (7*24*60*60) ))
;;
"second")
local -i _date1_secs; _date1_secs=$(date -d "$_date1" +%s) || return 1
local -i _date2_secs; _date2_secs=$(date -d "$_date2" +%s) || return 1
echo $(( _date2_secs - _date1_secs )) || return 1
;;
*)
log "timespan: invalid quanta: $_quanta"
return 1
esac
}
movedate() {
# Moves given date forward by (freq * freq_num)
local _date=$1;shift # in ISO format
local _freq=$1;shift # year|month|week
local -i _freq_num=$1 # a number, e.g. 2 to mean bi-yearly (e.g.)
# Check the date
date -d "$_date" > /dev/null 2>&1 || return 1
# Pull out components
# 10# forces base 10 as leading zeros are otherwise seen as octal
local -i _day=10#"${_date:8:2}"
local -i _month=10#"${_date:5:2}"
local -i _year="${_date:0:4}"
case "$_freq" in
"year")
# add to freq_num to year
_year=$(( _year + _freq_num ))
_date="${_year}${_date:4}"
;;
"month")
_month=$(( _month + _freq_num ))
while [[ _month -gt 12 ]]; do
_year=$(( _year + 1))
_month=$(( _month - 12))
done
# Lookup num days of this month
local -i _mymonthsdays=${monthsdays[$(( "$_month" - 1 ))]}
# If our day is past the end of the month pull it back
if [[ "$_day" -gt "$_mymonthsdays" ]]; then
_day="$_mymonthsdays"
# Check for leap year
if [[ "$_month" -eq 2 ]] && [[ $(leapyear "$_year") = "true" ]]; then
_day=29
fi
fi
_date="$_year-$(printf %02d $_month)-$(printf %02d "$_day")"
;;
"week")
# add 7*freq_num
_date=$(date -d "$_date" +%s) # convert to epoch secs
_date=$(( "$_date" + (7 * 24 * 60 * 60 * "$_freq_num") )) # add
_date=$(date -d "@$_date" -I) # convert back to ISO
;;
"*")
log "movedate: unexpected frequency: $_freq"
return 1
;;
esac
echo "$_date"
}
nearest_occurence() {
# result is also in ISO format
local _today=$1;shift # in ISO format
local _reminder=$1;shift # in ISO format
local _freq=$1;shift # year|one-time
local -i _freq_num=$1 # a number, e.g. 2 to mean bi-yearly (e.g.)
if [[ "$_freq" = "one_time" || "$_reminder" > "$_today" ]]; then
echo "$_reminder"
return
fi
local -i _gap _factor _backspan _nextspan
local _lastdate _nextdate
_gap=$(timespan "$_reminder" "$_today" "$_freq") || return 1
_factor=$(( _gap / _freq_num ))
_lastdate=$(movedate "$_reminder" "$_freq" "$(( _factor * _freq_num))") || return 1
_backspan=$(timespan "$_lastdate" "$_today" "second") || return 1
_nextdate=$(movedate "$_lastdate" "$_freq" "$_freq_num") || return 1
_nextspan=$(timespan "$_today" "$_nextdate" "second") || return 1
if [[ "$_backspan" -lt "$_nextspan" ]]; then
echo "$_lastdate"
else
echo "$_nextdate"
fi
}
initlogging() {
declare -g logrotateday=${LOGROTATEDAY:-10}
declare -g logdir=${LOGDIR:-/var/www/html/storage/logs}
declare -g logfile;logfile="$logdir/$(basename "$0")_$(date --rfc-3339=seconds)".log
# https://stackoverflow.com/a/806923
if ! [[ $logrotateday =~ ^[0-9]+$ ]]; then
echo "monica_reminder: LOGROTATEDAY was '$LOGROTATEDAY' but must be a number!" ; exit 1
fi
if [[ "$logdir" != "-" ]]; then
if [[ ! -d "$logdir" ]]; then
if ! mkdir -p "$logdir"; then
echo "monica_reminder: failed to create logdir: $logdir" ; exit 1
fi
fi
if [[ ! -w "$logdir" ]]; then
echo "monica_reminder: no permission to write to logdir: $logdir, running as user: $(whoami)" ; exit 1
fi
if ! touch "$logfile"; then
echo "monica_reminder: failed to touch new logfile: $logfile" ; exit 1
fi
if ! find "$logdir" -type f -name "$(basename "$0")_*" -mtime +"${logrotateday}" -exec rm {} \;; then
echo "monica_reminder: failed to clean old log files. Aborting" ; exit 1
fi
fi
}
log() {
if [[ ! -v logdir || "$logdir" == "-" ]]; then
echo "monica_reminder: $1"
else
echo "$1" >> "$logfile"
fi
}
preflight() {
if [[ -v TODAY ]]; then
today=$(date -d "$TODAY" -I -u) > /dev/null || {
log "TODAY was invalid date: $TODAY"
exit 1
}
else
today="$(date -I -u)"
MONICABASEDIR=${MONICABASEDIR:-.}
monicabasedircmds=$MONICABASEDIR/app/Console/Commands
if [[ ! -d "$monicabasedircmds" ]]; then
log "Could not find monica command dir at $monicabasedircmds. Check MONICABASEDIR configured correctly."
exit 1
fi
fi
# TODO: also check all the env vars we rely on are not empty
log "Configuration:"
log " monica_reminder:"
log " DRYRUN: $DRYRUN, TODAY: $TODAY, NOSEND: $NOSEND, LOGDIR: $LOGDIR, LOGROTATEDAY: $LOGROTATEDAY, DATA_HOME: $DATA_HOME, MONICABASEDIR: $MONICABASEDIR"
log " Monica DB:"
log " DB_HOST: $DB_HOST, DB_PASSWORD: ***"
if ! type php 1>/dev/null; then
log "php is not installed!" ; exit 1
fi
}
installemailcmd() {
echo "$monicaremindersendphp" > "$monicabasedircmds/MonicaReminderSend.php" || {
log "Failed to install email command at $monicabasedircmds" ; exit 1
}
}
execphpsql() {
#
# Executes sql in $1
# Results put into global var 'results'
# Logs any errors and terminates
#
local _sql;_sql=$(cat <<'EOF'
<?php
$conn = mysqli_connect(getenv('DB_HOST'), 'homestead', getenv('DB_PASSWORD'), 'monica');
if (!$conn){
die("Connection failed: " . mysqli_connect_error());
}
$sql = "
EOF
)
_sql+="$1"
_sql+=$(cat <<'EOF'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo join("\t", $row)."\n";
}
}
mysqli_close($conn);
?>
EOF
)
declare -g results
results=$(php <(echo "$_sql"))
# shellcheck disable=SC2181 #
if [[ $? -ne 0 ]]; then
log "php-wrapped sql query failed:"
log "$_sql"
log "---"
log "$results"
exit 1
fi
}
getusers() {
execphpsql "select first_name, email from users;"
declare -g users="$results"
# TODO: if there's no users log it and quit
}
getreminders() {
# TODO: cope with other types
execphpsql "select r.id, r.initial_date, r.frequency_type, r.frequency_number, r.title, c.first_name, c.last_name from reminders r join contacts c on r.contact_id = c.id where r.inactive=0"
declare -g reminders="$results"
# TODO: if there's no reminders log it and quit
}
main() {
if [[ -v CONTAINER ]]; then
relaunchincontainer
fi
initlogging
initdatahome
preflight
installemailcmd
getusers
getreminders
while IFS=$'\t' read -r id initial_date frequency_type frequency_number title first_name last_name ; do
# TODO: make cutoff configurable
_pastcutoff=2629743 # 1 month epoch seconds
log "CONSIDERING reminder id=$id, initial_date=$initial_date frequency_type=$frequency_type frequency_number=$frequency_number title=$title first_name=$first_name last_name=$last_name"
_nearestocc=$(nearest_occurence "$today" "$(date -d "$initial_date" -I)" "$frequency_type" "$frequency_number")
exit=$? ; [ "$exit" -eq 0 ] || exit 1
# TODO: get these from DB
declare -a _reminderdaysbefore=("0" "7" "30")
for _daysbefore in "${_reminderdaysbefore[@]}"; do
# TODO: could we use move date here instead?
_reminderday=$(( $(date -d "$_nearestocc" +%s) - (_daysbefore*86400) ))
_reminderday=$(date -d "@$_reminderday" -I)
while IFS=$'\t' read -r _emailnice _email ; do
# Have we already dealt with this ID, _reminderdate and email-recepient?
if [[ -f "$DATA_HOME/${id}_${_reminderday}_${_email}" ]]; then
log "skipping - we have processed this ${_daysbefore} day reminder already for ${_email}"
continue
fi
if [[ "$_reminderday" = "$today" ]]; then
sendmail "$_nearestocc" "$_email" "$_emailnice" "$_daysbefore" "$first_name $last_name" "$title" "false"
# Mark a file to say we dealt with this reminder
[ "$DRYRUN" == "true" ] || touch "$DATA_HOME/${id}_${_reminderday}_${_email}"
else
true
if [[ "$_reminderday" < "$today" ]]; then
if [[ "$_nearestocc" > "$today" ]]; then
# Event still in future
log "we should have sent a reminder $_reminderday, sorry!"
sendmail "$_nearestocc" "$_email" "$_emailnice" "$_daysbefore" "$first_name $last_name" "$title" "true"
else
# Event has past, but by how much?
_diff=$(( $(date -d "$today" +%s) - $(date -d "$_nearestocc" +%s) ))
if [[ "$_diff" -lt "$_pastcutoff" ]]; then
log "event has recently past but we should have sent a reminder $_reminderday, sorry!"
sendmail "$_nearestocc" "$_email" "$_emailnice" "$_daysbefore" "$first_name $last_name" "$title" "true"
# TODO: potentially we flag that we've now dealt with late reminders for this event
# so users only get one late reminder not one for every late reminder
else
log "event has past more than a month ago, ignore"
fi
fi
# Mark a file to say we dealt with this reminder
[ "$DRYRUN" == "true" ] || touch "$DATA_HOME/${id}_${_reminderday}_${_email}"
else
log "${_daysbefore} day reminder not yet due for ${_email}"
fi
fi
done < <(echo "$users")
done
done < <(echo "$reminders")
}
# call main if not sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi