fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonMerge PR #421575790441

master
13.0 KiB378 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6  inherit (pkgs.stdenv.hostPlatform) isDarwin;
7
8  cfg = config.programs.thunderbird;
9
10  enabledAccounts = attrValues
11    (filterAttrs (_: a: a.thunderbird.enable) config.accounts.email.accounts);
12
13  enabledAccountsWithId =
14    map (a: a // { id = builtins.hashString "sha256" a.name; }) enabledAccounts;
15
16  thunderbirdConfigPath =
17    if isDarwin then "Library/Thunderbird" else ".thunderbird";
18
19  thunderbirdProfilesPath = if isDarwin then
20    "${thunderbirdConfigPath}/Profiles"
21  else
22    thunderbirdConfigPath;
23
24  profilesWithId =
25    imap0 (i: v: v // { id = toString i; }) (attrValues cfg.profiles);
26
27  profilesIni = foldl recursiveUpdate {
28    General = {
29      StartWithLastProfile = 1;
30      Version = 2;
31    };
32  } (flip map profilesWithId (profile: {
33    "Profile${profile.id}" = {
34      Name = profile.name;
35      Path = if isDarwin then "Profiles/${profile.name}" else profile.name;
36      IsRelative = 1;
37      Default = if profile.isDefault then 1 else 0;
38    };
39  }));
40
41  toThunderbirdIdentity = account: address:
42    # For backwards compatibility, the primary address reuses the account ID.
43    let
44      id = if address == account.address then
45        account.id
46      else
47        builtins.hashString "sha256" address;
48    in {
49      "mail.identity.id_${id}.fullName" = account.realName;
50      "mail.identity.id_${id}.useremail" = address;
51      "mail.identity.id_${id}.valid" = true;
52    } // optionalAttrs (account.gpg != null) {
53      "mail.identity.id_${id}.attachPgpKey" = false;
54      "mail.identity.id_${id}.autoEncryptDrafts" = true;
55      "mail.identity.id_${id}.e2etechpref" = 0;
56      "mail.identity.id_${id}.encryptionpolicy" =
57        if account.gpg.encryptByDefault then 2 else 0;
58      "mail.identity.id_${id}.is_gnupg_key_id" = true;
59      "mail.identity.id_${id}.last_entered_external_gnupg_key_id" =
60        account.gpg.key;
61      "mail.identity.id_${id}.openpgp_key_id" = account.gpg.key;
62      "mail.identity.id_${id}.protectSubject" = true;
63      "mail.identity.id_${id}.sign_mail" = account.gpg.signByDefault;
64    } // account.thunderbird.perIdentitySettings id;
65
66  toThunderbirdAccount = account: profile:
67    let
68      id = account.id;
69      addresses = [ account.address ] ++ account.aliases;
70    in {
71      "mail.account.account_${id}.identities" = concatStringsSep ","
72        ([ "id_${id}" ]
73          ++ map (address: "id_${builtins.hashString "sha256" address}")
74          account.aliases);
75      "mail.account.account_${id}.server" = "server_${id}";
76    } // optionalAttrs account.primary {
77      "mail.accountmanager.defaultaccount" = "account_${id}";
78    } // optionalAttrs (account.imap != null) {
79      "mail.server.server_${id}.directory" =
80        "${thunderbirdProfilesPath}/${profile.name}/ImapMail/${id}";
81      "mail.server.server_${id}.directory-rel" = "[ProfD]ImapMail/${id}";
82      "mail.server.server_${id}.hostname" = account.imap.host;
83      "mail.server.server_${id}.login_at_startup" = true;
84      "mail.server.server_${id}.name" = account.name;
85      "mail.server.server_${id}.port" =
86        if (account.imap.port != null) then account.imap.port else 143;
87      "mail.server.server_${id}.socketType" = if !account.imap.tls.enable then
88        0
89      else if account.imap.tls.useStartTls then
90        2
91      else
92        3;
93      "mail.server.server_${id}.type" = "imap";
94      "mail.server.server_${id}.userName" = account.userName;
95    } // optionalAttrs (account.smtp != null) {
96      "mail.identity.id_${id}.smtpServer" = "smtp_${id}";
97      "mail.smtpserver.smtp_${id}.authMethod" = 3;
98      "mail.smtpserver.smtp_${id}.hostname" = account.smtp.host;
99      "mail.smtpserver.smtp_${id}.port" =
100        if (account.smtp.port != null) then account.smtp.port else 587;
101      "mail.smtpserver.smtp_${id}.try_ssl" = if !account.smtp.tls.enable then
102        0
103      else if account.smtp.tls.useStartTls then
104        2
105      else
106        3;
107      "mail.smtpserver.smtp_${id}.username" = account.userName;
108    } // optionalAttrs (account.smtp != null && account.primary) {
109      "mail.smtp.defaultserver" = "smtp_${id}";
110    } // builtins.foldl' (a: b: a // b) { }
111    (builtins.map (address: toThunderbirdIdentity account address) addresses)
112    // account.thunderbird.settings id;
113
114  mkUserJs = prefs: extraPrefs: ''
115    // Generated by Home Manager.
116
117    ${concatStrings (mapAttrsToList (name: value: ''
118      user_pref("${name}", ${builtins.toJSON value});
119    '') prefs)}
120    ${extraPrefs}
121  '';
122in {
123  meta.maintainers = with hm.maintainers; [ d-dervishi jkarlson ];
124
125  options = {
126    programs.thunderbird = {
127      enable = mkEnableOption "Thunderbird";
128
129      package = mkOption {
130        type = types.package;
131        default = pkgs.thunderbird;
132        defaultText = literalExpression "pkgs.thunderbird";
133        example = literalExpression "pkgs.thunderbird-91";
134        description = "The Thunderbird package to use.";
135      };
136
137      profiles = mkOption {
138        type = with types;
139          attrsOf (submodule ({ config, name, ... }: {
140            options = {
141              name = mkOption {
142                type = types.str;
143                default = name;
144                readOnly = true;
145                description = "This profile's name.";
146              };
147
148              isDefault = mkOption {
149                type = types.bool;
150                default = false;
151                example = true;
152                description = ''
153                  Whether this is a default profile. There must be exactly one
154                  default profile.
155                '';
156              };
157
158              settings = mkOption {
159                type = with types; attrsOf (oneOf [ bool int str ]);
160                default = { };
161                example = literalExpression ''
162                  {
163                    "mail.spellcheck.inline" = false;
164                  }
165                '';
166                description = ''
167                  Preferences to add to this profile's
168                  {file}`user.js`.
169                '';
170              };
171
172              withExternalGnupg = mkOption {
173                type = types.bool;
174                default = false;
175                example = true;
176                description = "Allow using external GPG keys with GPGME.";
177              };
178
179              userChrome = mkOption {
180                type = types.lines;
181                default = "";
182                description = "Custom Thunderbird user chrome CSS.";
183                example = ''
184                  /* Hide tab bar in Thunderbird */
185                  #tabs-toolbar {
186                    visibility: collapse !important;
187                  }
188                '';
189              };
190
191              userContent = mkOption {
192                type = types.lines;
193                default = "";
194                description = "Custom Thunderbird user content CSS.";
195                example = ''
196                  /* Hide scrollbar on Thunderbird pages */
197                  *{scrollbar-width:none !important}
198                '';
199              };
200
201              extraConfig = mkOption {
202                type = types.lines;
203                default = "";
204                description = ''
205                  Extra preferences to add to {file}`user.js`.
206                '';
207              };
208            };
209          }));
210        description = "Attribute set of Thunderbird profiles.";
211      };
212
213      settings = mkOption {
214        type = with types; attrsOf (oneOf [ bool int str ]);
215        default = { };
216        example = literalExpression ''
217          {
218            "general.useragent.override" = "";
219            "privacy.donottrackheader.enabled" = true;
220          }
221        '';
222        description = ''
223          Attribute set of Thunderbird preferences to be added to
224          all profiles.
225        '';
226      };
227
228      darwinSetupWarning = mkOption {
229        type = types.bool;
230        default = true;
231        example = false;
232        visible = isDarwin;
233        readOnly = !isDarwin;
234        description = ''
235          Warn to set environment variables before using this module. Only
236          relevant on Darwin.
237        '';
238      };
239    };
240
241    accounts.email.accounts = mkOption {
242      type = with types;
243        attrsOf (submodule {
244          options.thunderbird = {
245            enable =
246              mkEnableOption "the Thunderbird mail client for this account";
247
248            profiles = mkOption {
249              type = with types; listOf str;
250              default = [ ];
251              example = literalExpression ''
252                [ "profile1" "profile2" ]
253              '';
254              description = ''
255                List of Thunderbird profiles for which this account should be
256                enabled. If this list is empty (the default), this account will
257                be enabled for all declared profiles.
258              '';
259            };
260
261            settings = mkOption {
262              type = with types; functionTo (attrsOf (oneOf [ bool int str ]));
263              default = _: { };
264              defaultText = literalExpression "_: { }";
265              example = literalExpression ''
266                id: {
267                  "mail.server.server_''${id}.check_new_mail" = false;
268                };
269              '';
270              description = ''
271                Extra settings to add to this Thunderbird account configuration.
272                The {var}`id` given as argument is an automatically
273                generated account identifier.
274              '';
275            };
276
277            perIdentitySettings = mkOption {
278              type = with types; functionTo (attrsOf (oneOf [ bool int str ]));
279              default = _: { };
280              defaultText = literalExpression "_: { }";
281              example = literalExpression ''
282                id: {
283                  "mail.identity.id_''${id}.protectSubject" = false;
284                  "mail.identity.id_''${id}.autoEncryptDrafts" = false;
285                };
286              '';
287              description = ''
288                Extra settings to add to each identity of this Thunderbird
289                account configuration. The {var}`id` given as
290                argument is an automatically generated identifier.
291              '';
292            };
293          };
294        });
295    };
296  };
297
298  config = mkIf cfg.enable {
299    assertions = [
300      (let defaults = catAttrs "name" (filter (a: a.isDefault) profilesWithId);
301      in {
302        assertion = cfg.profiles == { } || length defaults == 1;
303        message = "Must have exactly one default Thunderbird profile but found "
304          + toString (length defaults) + optionalString (length defaults > 1)
305          (", namely " + concatStringsSep "," defaults);
306      })
307
308      (let
309        profiles = catAttrs "name" profilesWithId;
310        selectedProfiles =
311          concatMap (a: a.thunderbird.profiles) enabledAccounts;
312      in {
313        assertion = (intersectLists profiles selectedProfiles)
314          == selectedProfiles;
315        message = "Cannot enable an account for a non-declared profile. "
316          + "The declared profiles are " + (concatStringsSep "," profiles)
317          + ", but the used profiles are "
318          + (concatStringsSep "," selectedProfiles);
319      })
320    ];
321
322    warnings = optional (isDarwin && cfg.darwinSetupWarning) ''
323      Thunderbird packages are not yet supported on Darwin. You can still use
324      this module to manage your accounts and profiles by setting
325      'programs.thunderbird.package' to a dummy value, for example using
326      'pkgs.runCommand'.
327
328      Note that this module requires you to set the following environment
329      variables when using an installation of Thunderbird that is not provided
330      by Nix:
331
332          export MOZ_LEGACY_PROFILES=1
333          export MOZ_ALLOW_DOWNGRADE=1
334    '';
335
336    home.packages = [ cfg.package ]
337      ++ optional (any (p: p.withExternalGnupg) (attrValues cfg.profiles))
338      pkgs.gpgme;
339
340    home.file = mkMerge ([{
341      "${thunderbirdConfigPath}/profiles.ini" =
342        mkIf (cfg.profiles != { }) { text = generators.toINI { } profilesIni; };
343    }] ++ flip mapAttrsToList cfg.profiles (name: profile: {
344      "${thunderbirdProfilesPath}/${name}/chrome/userChrome.css" =
345        mkIf (profile.userChrome != "") { text = profile.userChrome; };
346
347      "${thunderbirdProfilesPath}/${name}/chrome/userContent.css" =
348        mkIf (profile.userContent != "") { text = profile.userContent; };
349
350      "${thunderbirdProfilesPath}/${name}/user.js" = let
351        accounts = filter (a:
352          a.thunderbird.profiles == [ ]
353          || any (p: p == name) a.thunderbird.profiles) enabledAccountsWithId;
354
355        smtp = filter (a: a.smtp != null) accounts;
356      in {
357        text = mkUserJs (builtins.foldl' (a: b: a // b) { } ([
358          cfg.settings
359
360          (optionalAttrs (length accounts != 0) {
361            "mail.accountmanager.accounts" =
362              concatStringsSep "," (map (a: "account_${a.id}") accounts);
363          })
364
365          (optionalAttrs (length smtp != 0) {
366            "mail.smtpservers" =
367              concatStringsSep "," (map (a: "smtp_${a.id}") smtp);
368          })
369
370          { "mail.openpgp.allow_external_gnupg" = profile.withExternalGnupg; }
371
372          profile.settings
373        ] ++ (map (a: toThunderbirdAccount a profile) accounts)))
374          profile.extraConfig;
375      };
376    }));
377  };
378}