diff options
author | Luke Smith <luke@lukesmith.xyz> | 2021-01-07 18:31:42 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-07 18:31:42 -0500 |
commit | 4742f9d6b0f5c27f9bef2d916266960b0cbc214e (patch) | |
tree | 09ddfd1fd5bfe4a2defe3eafe87141c9fea34732 /bin | |
parent | 44c70edd8175acb1a0d717c32e4048265c65cb8a (diff) | |
parent | 8b9f8c1c384c3e148cdd832047156d2bedda517e (diff) |
Merge branch 'master' into patch-1
Diffstat (limited to 'bin')
-rwxr-xr-x | bin/mailsync | 94 | ||||
-rwxr-xr-x | bin/mw | 173 |
2 files changed, 187 insertions, 80 deletions
diff --git a/bin/mailsync b/bin/mailsync new file mode 100755 index 0000000..3fac7c5 --- /dev/null +++ b/bin/mailsync @@ -0,0 +1,94 @@ +#!/bin/sh + +# - Syncs mail for all accounts, or a single account given as an argument. +# - Displays a notification showing the number of new mails. +# - Displays a notification for each new mail with its subject displayed. +# - Runs notmuch to index new mail. +# - This script can be set up as a cron job for automated mail syncing. + +# There are many arbitrary and ugly features in this script because it is +# inherently difficult to pass environmental variables to cronjobs and other +# issues. It also should at least be compatible with Linux (and maybe BSD) with +# Xorg and MacOS as well. + +# Run only if user logged in (prevent cron errors) +pgrep -u "${USER:=$LOGNAME}" >/dev/null || { echo "$USER not logged in; sync will not run."; exit ;} +# Run only if not already running in other instance +pgrep -x mbsync >/dev/null && { echo "mbsync is already running." ; exit ;} + +# First, we have to get the right variables for the mbsync file, the pass +# archive, notmuch and the GPG home. This is done by searching common profile +# files for variable assignments. This is ugly, but there are few options that +# will work on the maximum number of machines. +eval "$(grep -h -- \ + "^\s*\(export \)\?\(MBSYNCRC\|PASSWORD_STORE_DIR\|NOTMUCH_CONFIG\|GNUPGHOME\)=" \ + "$HOME/.profile" "$HOME/.bash_profile" "$HOME/.zprofile" "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.pam_environment" 2>/dev/null)" +# One alternative to this kind of command would be marking the script for +# /bin/sh -l. That might cause other problems on other particular setups that +# do more complicated things on login, or those people who assign environmental +# variables in shell rc files. + +case "$(readlink -f /sbin/init)" in + *systemd*) export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus ;; +esac +export GPG_TTY=$TTY + +[ -n "$MBSYNCRC" ] && alias mbsync="mbsync -c $MBSYNCRC" || MBSYNCRC="$HOME/.mbsyncrc" + +# Settings are different for MacOS (Darwin) systems. +case "$(uname)" in + Darwin) + notify() { osascript -e "display notification \"$2 in $1\" with title \"You've got Mail\" subtitle \"Account: $account\"" && sleep 2 ;} + messageinfo() { osascript -e "display notification with title \"📧 $from\" subtitle \"$subject\"" ;} + ;; + *) + displays="$(ps axo user,cmd | grep "^$USER\s\+.*Xorg" | grep -wo "[0-9]*:[0-9]\+")" + notify() { for x in $displays; do + export DISPLAY=$x + notify-send --app-name="mutt-wizard" "mutt-wizard" "📬 $2 new mail(s) in \`$1\` account." + done ;} + messageinfo() { for x in $displays; do + export DISPLAY=$x + notify-send --app-name="mutt-wizard" "📧$from:" "$subject" + done ;} + ;; +esac + +# Check account for new mail. Notify if there is new content. +syncandnotify() { + acc="$(echo "$account" | sed "s/.*\///")" + if [ -z "$opts" ]; then mbsync "$acc"; else mbsync "$opts" "$acc"; fi + new=$(find "$HOME/.local/share/mail/$acc/INBOX/new/" "$HOME/.local/share/mail/$acc/Inbox/new/" "$HOME/.local/share/mail/$acc/inbox/new/" -type f -newer "$HOME/.config/mutt/.mailsynclastrun" 2> /dev/null) + newcount=$(echo "$new" | sed '/^\s*$/d' | wc -l) + if [ "$newcount" -gt "0" ]; then + notify "$acc" "$newcount" & + for file in $new; do + # Extract subject and sender from mail. + from=$(awk '/^From: / && ++n ==1,/^\<.*\>:/' "$file" | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | awk '{ $1=""; if (NF>=3)$NF=""; print $0 }' | sed 's/^[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//') + subject=$(awk '/^Subject: / && ++n == 1,/^\<.*\>: / && ++i == 2' "$file" | head -n 1 | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | sed 's/^Subject: //' | sed 's/^{[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//' | tr -d '\n') + messageinfo & + done + fi +} + +# Sync accounts passed as argument or all. +if [ "$#" -eq "0" ]; then + accounts="$(awk '/^Channel/ {print $2}' "$MBSYNCRC")" +else + for arg in "$@"; do + [ "${arg%${arg#?}}" = '-' ] && opts="${opts:+${opts} }${arg}" && shift 1 + done + accounts=$* +fi + +# Parallelize multiple accounts +for account in $accounts; do + syncandnotify & +done + +wait + +notmuch new 2>/dev/null + +#Create a touch file that indicates the time of the last run of mailsync +touch "$HOME/.config/mutt/.mailsynclastrun" @@ -1,13 +1,5 @@ #!/bin/sh -command -V gpg >/dev/null 2>&1 && GPG="gpg" || GPG="gpg2" -[ -z ${PASSWORD_STORE_DIR+x} ] && PASSWORD_STORE_DIR="$HOME/.password-store" -[ -r "$PASSWORD_STORE_DIR/.gpg-id" ] && - "$GPG" --list-secret-keys $(cat "$PASSWORD_STORE_DIR/.gpg-id") >/dev/null 2>&1 || { - printf "\`pass\` must be installed and initialized to encrypt passwords.\\nBe sure it is installed and run \`pass init <yourgpgemail>\`.\\nIf you don't have a GPG public private key pair, run \`%s --full-gen-key\` first.\\n" "$GPG" - exit - } - prefix="/usr/local" pass_prefix="mw-" muttdir="${XDG_CONFIG_HOME:-$HOME/.config}/mutt" # Main mutt config location @@ -21,20 +13,31 @@ cachedir="${XDG_CACHE_HOME:-$HOME/.cache}/mutt-wizard" muttrc="$muttdir/muttrc" msmtprc="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/config" msmtplog="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/msmtp.log" -MARKER="# mw-autogenerated" +marker="# mw-autogenerated" alias mbsync='mbsync -c "$mbsyncrc"' -for x in "/etc/ssl/certs/ca-certificates.crt" "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/ca-bundle.pem" "/etc/pki/tls/cacert.pem" "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" "/etc/ssl/cert.pem" "/usr/local/share/ca-certificates/" -do +for x in "/etc/ssl/certs/ca-certificates.crt" "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/ca-bundle.pem" "/etc/pki/tls/cacert.pem" "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" "/etc/ssl/cert.pem" "/usr/local/share/ca-certificates/"; do [ -f "$x" ] && sslcert="$x" && break done || { echo "CA Certificate not found. Please install one or link it to /etc/ssl/certs/ca-certificates.crt" && exit 1 ;} +checkbasics() { command -V gpg >/dev/null 2>&1 && GPG="gpg" || GPG="gpg2" + PASSWORD_STORE_DIR="${PASSWORD_STORE_DIR:-$HOME/.password-store}" + [ -r "$PASSWORD_STORE_DIR/.gpg-id" ] && + "$GPG" --list-secret-keys "$(cat "$PASSWORD_STORE_DIR/.gpg-id")" >/dev/null 2>&1 || { + echo "First run \`pass init <yourgpgemail>\` to set up a password archive." + echo "(If you don't already have a GPG key pair, first run \`$GPG --fullgenkey\`.)" + exit 1 ;} ;} + getaccounts() { accounts="$(find -L "$accdir" -type f | grep -o "[0-9]-.*.muttrc" | sed "s/-/: /;s/\.muttrc$//" | sort -n)" ;} list() { getaccounts && [ -n "$accounts" ] && echo "$accounts" ;} getprofiles() { \ unset msmtp_header msmtp_profile mutt_profile mbsync_profile + case "$iport" in + 1143) imapssl=None ;; + 143) imapssl=STARTTLS ;; + esac msmtp_header="defaults auth on tls on @@ -55,7 +58,7 @@ Port ${iport:-993} User $login PassCmd \"pass $pass_prefix$fulladdr\" AuthMechs LOGIN -SSLType ${ssltype:-IMAPS} +SSLType ${imapssl:-IMAPS} CertificateFile $sslcert MaildirStore $fulladdr-local @@ -95,6 +98,7 @@ bind index,pager C noop bind index gg first-entry macro index o \"<shell-escape>mw -y $fulladdr<enter>\" \"run mbsync to sync $fulladdr\" unmailboxes * +unalternates * " else mutt_profile="# vim: filetype=neomuttrc @@ -150,11 +154,17 @@ delete() { if [ -z "${fulladdr+x}" ]; then [ -z "$fulladdr" ] && echo "Invalid account name given." && return 1 - sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" ; rm -rf "$mbsyncrc"bu + sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" ; rm -f "$mbsyncrc"bu rm -rf "${cachedir:?}/${fulladdr:?}" "$accdir/"[1-9]"-$fulladdr.muttrc" sed -ibu "/[0-9]-$fulladdr.muttrc/d" "$muttrc" ; rm -f "$muttrc"bu sed -ibu "/account $fulladdr/,/^\(\s*$\|account\)/d" "$msmtprc"; rm -f "$msmtprc"bu pass rm -f "$pass_prefix$fulladdr" >/dev/null 2>&1 + + # Get rid of those multiple newlines because I don't know awk well enough to do it by default lol. + for file in "$msmtprc" "$mbsyncrc"; do + tr '\n' '|' < "$file" | sed "s/||\+/||/g" | tr '|' '\n' >> "$file"bu + mv -f "$file"bu "$file" + done } askinfo() { \ @@ -164,14 +174,15 @@ askinfo() { \ echo "\`$fulladdr\` is not a valid email address. Please retype the address:" read -r fulladdr done + grep -q "Channel\s*$fulladdr$" "$mbsyncrc" && + { echo "$fulladdr has already been added" && exit 1 ;} { [ -z "$imap" ] || [ -z "$smtp" ] ;} && parsedomains [ -z "$imap" ] && echo "Give your email server's IMAP address (excluding the port number):" && read -r imap [ -z "$smtp" ] && echo "Give your email server's SMTP address (excluding the port number):" && read -r smtp [ "$sport" = 465 ] && tlsline="tls_starttls off" - [ -z "$realname" ] && echo "Give the name you would like to be identified by on the email account:" && - read -r realname + [ -z "$realname" ] && realname="${fulladdr%%@*}" login="${login:-$fulladdr}" if [ -n "${password+x}" ]; then createpass @@ -195,16 +206,15 @@ writeinfo() { mkdir -p "$muttdir" "$accdir" "$cachedir/$fulladdr/bodies" "${XDG_ # On Ubuntu/Debian, a link is needed since they use an older version. command -V apt-get >/dev/null 2>&1 && ln -s "$msmtprc" "$HOME/.msmtprc" 2>/dev/null - # Create the mbsync config file. - mkdir -p "${mbsyncrc%/*}" - echo "$mbsync_profile" >> "$mbsyncrc" + # Create the mbsync config file if local account. + [ -z "${online+x}" ] && mkdir -p "${mbsyncrc%/*}" && echo "$mbsync_profile" >> "$mbsyncrc" # Create a muttrc for viewing mail. echo "$mutt_profile" > "$accdir/$idnum-$fulladdr.muttrc" [ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc" - ! grep -q "^source.*mutt-wizard.muttrc" "$muttrc" && echo "source $mwconfig $MARKER" >> "$muttrc" - ! grep "^source.*.muttrc" "$muttrc" | grep -qv "$mwconfig" && echo "source $accdir/$idnum-$fulladdr.muttrc $MARKER" >> "$muttrc" - echo "macro index,pager i$idnum '<sync-mailbox><enter-command>source $accdir/$idnum-$fulladdr.muttrc<enter><change-folder>!<enter>;<check-stats>' \"switch to $fulladdr\" $MARKER" >> "$muttrc" + ! grep -q "^source.*mutt-wizard.muttrc" "$muttrc" && echo "source $mwconfig $marker" >> "$muttrc" + ! grep "^source.*.muttrc" "$muttrc" | grep -qv "$mwconfig" && echo "source $accdir/$idnum-$fulladdr.muttrc $marker" >> "$muttrc" + echo "macro index,pager i$idnum '<sync-mailbox><enter-command>source $accdir/$idnum-$fulladdr.muttrc<enter><change-folder>!<enter>;<check-stats>' \"switch to $fulladdr\" $marker" >> "$muttrc" notmuchauto # Create a notmuch config file if not present already. } @@ -213,12 +223,12 @@ getpass() { while : ; do pass rm -f "$pass_prefix$fulladdr" >/dev/null 2>&1 pass insert "$pass_prefix$fulladdr" && break; done ;} formatShortcut() { toappend="$toappend -macro index,pager g$1 \"<change-folder>=$3<enter>\" \"go to $2\" $MARKER -macro index,pager M$1 \";<save-message>=$3<enter>\" \"move mail to $2\" $MARKER -macro index,pager C$1 \";<copy-message>=$3<enter>\" \"copy mail to $2\" $MARKER" >> "$accdir/$idnum-$fulladdr.muttrc" ;} +macro index,pager g$1 \"<change-folder>=$3<enter>\" \"go to $2\" $marker +macro index,pager M$1 \";<save-message>=$3<enter>\" \"move mail to $2\" $marker +macro index,pager C$1 \";<copy-message>=$3<enter>\" \"copy mail to $2\" $marker" >> "$accdir/$idnum-$fulladdr.muttrc" ;} setBox() { toappend="$toappend -set $1 = \"+$2\" $MARKER" ;} +set $1 = \"+$2\" $marker" ;} getboxes() { [ -n "${force+x}" ] && mailboxes="INBOX Drafts @@ -226,40 +236,30 @@ Junk Trash Sent Archive" && return 0 - if mailboxes="$(mbsync -l "$fulladdr" | sed 's/\//./')" >/dev/null 2>&1 && [ -n "$mailboxes" ]; then - [ -n "${online+x}" ] && sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" ; rm -f "$mbsyncrc"bu - return 0 - else - echo "$mailboxes" - printf "\033[31m\033[31mLog-on not successful.\033[0m\\nIt seems that either you inputted the wrong password or server settings, or there are other requirements for your account out of the control of mutt-wizard.\\n" - return 1 - fi ;} + info="$(curl --location-trusted -s -m 5 --user "$login:$(pass $pass_prefix$fulladdr)" --url "${protocol:-imaps}://$imap")" + [ -z "$info" ] && echo "Log-on not successful." && return 1 + mailboxes="$(echo "$info" | sed "s/.*\" //" | tr -d '
')" +} finalize() { echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$fulladdr/{}/cur" "$maildir/$fulladdr/{}/tmp" "$maildir/$fulladdr/{}/new" - sed -ibu "/$MARKER/d" "$accdir/$idnum-$fulladdr.muttrc" ; rm -f "$accdir/$idnum-$fulladdr.muttrcbu" - toappend="mailboxes $(echo "$mailboxes" | sed "s/^/\"=/;s/$/\"/" | paste -sd ' ' )" + sed -ibu "/$marker/d" "$accdir/$idnum-$fulladdr.muttrc" ; rm -f "$accdir/$idnum-$fulladdr.muttrcbu" + toappend="mailboxes $(echo "$mailboxes" | sed "s/^/\"=/;s/$/\"/" | paste -sd ' ' - )" for x in $mailboxes; do - case $x in - *[Ii][Nn][Bb][Oo][Xx]*) formatShortcut i inbox "$x"; setBox spoolfile "$x" ;; + case "$x" in *[Ss][Ee][Nn][Tt]*) setBox record "$x"; formatShortcut s sent "$x" ;; *[Dd][Rr][Aa][Ff][Tt][Ss]*) setBox postponed "$x"; formatShortcut d drafts "$x" ;; *[Tt][Rr][Aa][Ss][Hh]*) formatShortcut t trash "$x"; setBox trash "$x" ;; *[Jj][Uu][Nn][Kk]*) formatShortcut j junk "$x" ;; *[Aa][Rr][Cc][Hh][Ii][Vv][Ee]*) formatShortcut a archive "$x" ;; *[Ss][Pp][Aa][Mm]*) formatShortcut S spam "$x" ;; + *[Ii][Nn][Bb][Oo][Xx]*) formatShortcut i inbox "$x"; setBox spoolfile "$x" ;; esac done echo "$toappend" >> "$accdir/$idnum-$fulladdr.muttrc" - [ -z "${online+x}" ] && printf "\033[33mYou should now be able to run \`\033[32mmw -y %s\033[33m\` to begin to download your mail.\033[0m\\n" "$fulladdr" + [ -z "${online+x}" ] && echo "$fulladdr (account #$idnum) added successfully." command -V urlview >/dev/null 2>&1 && [ ! -f "$HOME/.urlview" ] && echo "COMMAND \$BROWSER" > "$HOME/.urlview" return 0 ;} -syncwrapper() { mbsync "${1:--a}" & - ( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null - wait - ( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null - notmuch new ;} - notmuchauto() { \ [ -z "$NOTMUCH_CONFIG" ] && NOTMUCH_CONFIG="$HOME/.notmuch-config" [ -f "$NOTMUCH_CONFIG" ] && return 0 @@ -279,6 +279,17 @@ synchronize_flags=true gpg_path=$GPG" echo "$nmbasic" > "$NOTMUCH_CONFIG" ;} +togglecron() { cron="$(mktemp)" + crontab -l > "$cron" + if grep -q mailsync "$cron"; then + echo "Removing automatic mailsync..." + sed -ibu /mailsync/d "$cron"; rm -f "$cron"bu + else + echo "Adding automatic mailsync every ${cronmin:-10} minutes..." + echo "*/${cronmin-10} * * * * $prefix/bin/mailsync" >> "$cron" + fi && + crontab "$cron"; rm -f "$cron" ;} + setact() { if [ -n "${action+x}" ] && [ "$action" != "$1" ]; then echo "Running $1 with $action..." echo "Incompatible options given. Only one action may be specified per run." @@ -287,35 +298,7 @@ setact() { if [ -n "${action+x}" ] && [ "$action" != "$1" ]; then action="$1" fi; } -trap 'echo -e "\033[0m\n"; exit' INT ABRT - -while getopts "fplhodYD:y:i:I:s:S:u:a:n:x:m:" o; do case "${o}" in - l) setact list || exit 1 ;; - d) setact delete || exit 1 ;; - D) setact delete || exit 1 ; fulladdr="$OPTARG" ;; - y) setact sync || exit 1 ; fulladdr="$OPTARG" ;; - Y) setact sync || exit 1 ;; - a) setact add || exit 1 ; fulladdr="$OPTARG" ;; - i) setact add || exit 1 ; imap="$OPTARG" ;; - I) setact add || exit 1 ; iport="$OPTARG" ;; - s) setact add || exit 1 ; smtp="$OPTARG" ;; - S) setact add || exit 1 ; sport="$OPTARG" ;; - u) setact add || exit 1 ; login="$OPTARG" ;; - n) setact add || exit 1 ; realname="$OPTARG" ;; - m) setact add || exit 1 ; maxmes="$OPTARG" ;; - o) setact add || exit 1 ; online=True ;; - f) setact add || exit 1 ; force=True ;; - x) setact add || exit 1 ; password="$OPTARG" ;; - p) echo "NOTE: Protonmail users must install and configure Protonmail Bridge first for the first sync to work." - imap="127.0.0.1" - iport="1143" - smtp="127.0.0.1" - sport="1025" - ssltype="None" - tlsline="tls_fingerprint $(msmtp --serverinfo --host=$smtp --port=$sport --tls --tls-certcheck=off | awk '/SHA256:/ {print $2}')" - setact add || exit 1 - ;; - *) cat << EOF +mwinfo() { cat << EOF mw: mutt-wizard, auto-configure email accounts for mutt including downloadable mail with \`isync\`. @@ -326,6 +309,8 @@ Main actions: -D your@email.com Force remove account without confirmation -y your@email.com Sync mail for account by name -Y Sync mail for all accounts + -t number Toggle automatic mailsync every <number> minutes + -T Toggle automatic mailsync Options allowed with -a: -u Account login name if not full address @@ -344,15 +329,43 @@ NOTE: Once at least one account is added, you can run To change an account's password, run \`pass edit ${pass_prefix}your@email.com\`. EOF -exit 1 -;; -esac done +} -! command -v mbsync >/dev/null && [ -z "${force+x}" ] && printf "\`mbsync (isync package)\` must be installed to run mutt-wizard.\\n" && exit +while getopts "fplhodTYD:y:i:I:s:S:u:a:n:x:m:t:" o; do case "${o}" in + l) setact list || exit 1 ;; + d) setact delete || exit 1 ;; + D) setact delete || exit 1 ; fulladdr="$OPTARG" ;; + y) setact sync || exit 1 ; fulladdr="$OPTARG" ;; + Y) setact sync || exit 1 ;; + a) setact add || exit 1 ; fulladdr="$OPTARG" ;; + i) setact add || exit 1 ; imap="$OPTARG" ;; + I) setact add || exit 1 ; iport="$OPTARG" ;; + s) setact add || exit 1 ; smtp="$OPTARG" ;; + S) setact add || exit 1 ; sport="$OPTARG" ;; + u) setact add || exit 1 ; login="$OPTARG" ;; + n) setact add || exit 1 ; realname="$OPTARG" ;; + m) setact add || exit 1 ; maxmes="$OPTARG" ;; + o) setact add || exit 1 ; online=True ;; + f) setact add || exit 1 ; force=True ;; + x) setact add || exit 1 ; password="$OPTARG" ;; + t) setact toggle || exit 1 ; cronmin="$OPTARG" ;; + T) setact toggle || exit 1 ;; + p) echo "NOTE: Protonmail users must install and configure Protonmail Bridge first for the first sync to work." + imap="127.0.0.1" + iport="1143" + smtp="127.0.0.1" + sport="1025" + tlsline="tls_fingerprint $(msmtp --serverinfo --host=$smtp --port=$sport --tls --tls-certcheck=off | awk '/SHA256:/ {print $2}')" + setact add || exit 1 + ;; + *) mwinfo; exit 1 ;; +esac done case "$action" in list) list ;; - add) askinfo && getprofiles && writeinfo && getboxes && finalize || { delete ; exit 1 ;} ;; - delete) delete $fulladdr ;; - sync) syncwrapper $fulladdr ;; + add) checkbasics && askinfo && getprofiles && writeinfo && getboxes && finalize || { delete ; exit 1 ;} ;; + delete) delete ;; + sync) mailsync $fulladdr ;; + toggle) togglecron ;; + *) mwinfo; exit 1 ;; esac |