aboutsummaryrefslogtreecommitdiff
path: root/modules/email.home/mailbox-sync.module.nix
blob: bb7ee9d240cea7d544661ee6b9df647fe2684ed0 (plain) (blame)
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
{ config, pkgs, lib, ... }:
with lib;
let
  cfg = config.services.mailbox-sync;

  notmuch = "${pkgs.notmuch}/bin/notmuch";
  gmi = "${pkgs.lieer}/bin/gmi";
  notify-send = "${pkgs.libnotify}/bin/notify-send";
  jq = "${pkgs.jq}/bin/jq";

  notify-script = ''
    emails=$(${notmuch} search --format=json '${cfg.notify.filter}' \
      | ${jq} -r '.[0:5] | map("— " + .subject + "\n" + .authors + "\n(tag: " + (.tags | join(" ")) + ")") | join("\n\n")');

    # Notify
    ${notify-send} --app-name=notmuch "Read your mail dumbass ($new_mail_count)" "\n$emails";
  '';

  sync-script = ''
    #!${pkgs.bash}/bin/bash
    set -eu -o pipefail;

    ${gmi} sync;

    new_mail_count=$(${notmuch} count '${cfg.notify.filter}');
    if [ $new_mail_count = 0 ]; then
      echo "No new mail";
    else
      ${if cfg.notify.enable then notify-script else ""}
    fi

    ${notmuch} tag -new -- tag:new;
  '';

  service-unit = {
    Unit.ConditionPathExists = "${cfg.maildir}/.gmailieer.json";
    Service = {
      Type = "oneshot";
      ExecStart = "${pkgs.writeScript "mailbox-sync-script" sync-script}";
      WorkingDirectory = cfg.maildir;
      Environment = "NOTMUCH_CONFIG=${config.xdg.configHome}/notmuch/default/config";
    };
  };

  timer-unit = {
    Timer = {
      OnCalendar = cfg.sync.frequency;
      RandomizedDelaySec = 30;
    };
    Install.WantedBy = [ "timers.target" ];
  };
in {
  options.services.mailbox-sync = {
    enable = mkEnableOption "mailbox sync";
    name = mkOption { type = types.str; default = "default"; };
    maildir = mkOption { type = types.str; };
    sync.frequency = mkOption { type = types.str; default = "*:0/5"; };
    notify.enable = mkEnableOption "notify on new mail";
    notify.filter = mkOption {
      type = types.str;
      default = "tag:inbox and tag:unread and tag:new";
    };
  };

  config = mkIf cfg.enable {
    programs.lieer.enable = true;
    systemd.user.services."mailbox-sync-${cfg.name}" = service-unit;
    systemd.user.timers."mailbox-sync-${cfg.name}" = timer-unit;
  };
}