summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/torrent/qbit-manage.nix
blob: 8e42477f2cac3977834badcab9732d1ae6ec0639 (plain)
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
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.qbit-manage;
  yaml = pkgs.formats.yaml { };
  createYAMLConfig =
    settings:
    pkgs.runCommand "config.yml" { } ''
      # Need to run sed to remove the quotes around !ENV values
      # otherwise qbit-manage will not interpret them as environment variables
      sed -E "s/'(!ENV) (.*)'/\1 \2/g" '${yaml.generate "tmp" settings}' > $out
    '';
  inherit (lib)
    concatStringsSep
    getExe
    hasPrefix
    literalExpression
    mkIf
    mkOption
    mkEnableOption
    mkPackageOption
    optional
    optionalString
    ;
  inherit (lib.types)
    str
    path
    listOf
    attrsOf
    submodule
    nullOr
    either
    port
    addCheck
    ints
    bool
    ;
in
{
  options.services.qbit-manage = {
    enable = mkEnableOption "qbit-manage";

    package = mkPackageOption pkgs "qbit-manage" { };

    user = mkOption {
      type = str;
      default = "qbit-manage";
      description = "User account under which qbit-manage runs.";
    };

    group = mkOption {
      type = str;
      default = "qbit-manage";
      description = "Group under which qbit-manage runs.";
    };

    environmentFile = mkOption {
      type = nullOr path;
      default = null;
      description = "Path to an environment file to load environment variables from.";
    };

    settings = mkOption {
      description = ''
        qbit-manage configuration. Will be translated into YAML.
        For environment variable support, use '!ENV VAR_NAME' as the value.
        See <https://github.com/StuffAnThings/qbit_manage/wiki/Config-Setup> for more information.

        Leave unset to configure without nix.
      '';
      default = null;
      type = nullOr (submodule {
        freeformType = yaml.type;
        options = {
          qbt = mkOption {
            description = "This section defines your qBittorrent instance";
            type = submodule {
              options = {
                host = mkOption {
                  type = str;
                  default = "localhost:${config.services.qbittorrent.webuiPort}";
                  defaultText = "localhost:\${config.services.qbittorrent.webuiPort}";
                  description = "IP address of your qBittorrent installation.";
                };

                user = mkOption {
                  type = nullOr str;
                  description = "The user name of your qBittorrent webUI.";
                };

                pass = mkOption {
                  type = nullOr (addCheck str (p: hasPrefix "!ENV " p));
                  description = "The password of your qBbittorrent webUI.";
                };
              };
            };
          };

          directory = mkOption {
            description = "This section defines the directories that qbit-manage will be looking into for various parts of the script.";
            default = null;
            type = nullOr (submodule {
              options = {
                root_dir = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Root downloads directory where you place all your downloads.
                    Used to check for orphaned files, hard links, and unregistered torrents.
                  '';
                };

                recycle_bin = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Path of the RecycleBin folder.
                    All files in this folder will be cleaned up based on your recycle bin settings.
                  '';
                };

                torrents_dir = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Path of the qBittorrent BT_backup directory.
                  '';
                };

                orphaned_dir = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Path of the Orphaned Directory folder.
                    All files in this folder will be cleaned up based on your orphaned data settings.
                  '';
                };
              };
            });
          };

          cat = mkOption {
            description = "A mapping of categories and their associated paths.";
            type = attrsOf str;
            example = literalExpression ''
              {
                sonarr = "/downloads/completed/sonarr";
                radaarr = "/downloads/completed/radaarr";
              }
            '';
          };

          tracker = mkOption {
            description = "Tags based upon the tracker's URL.";
            type = attrsOf (submodule {
              options = {
                tag = mkOption {
                  type = either str (listOf str);
                  description = "The tracker tag or additional list of tags.";
                };

                cat = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Set the category based on tracker URL.
                    This category option takes priority over the category defined in cat.
                  '';
                };

                notifiarr = mkOption {
                  type = nullOr str;
                  default = null;
                  description = ''
                    Set this to the notifiarr react name.
                    This is used to add indexer reactions to the notifications sent by Notifiarr.
                  '';
                };
              };
            });
          };
        };
      });
    };

    commands = mkOption {
      description = ''
        The commands that you want qbm to execute.
        See <https://github.com/StuffAnThings/qbit_manage/wiki/Commands> for more information.
      '';
      default = { };
      type = submodule {
        options = {
          schedule = mkOption {
            type = nullOr ints.positive;
            default = null;
            description = "Schedule to run every x minutes. If not set it will only run once then exit.";
          };

          startupDelay = mkOption {
            type = nullOr ints.positive;
            default = null;
            description = "Set delay in seconds on the first run of a schedule";
          };

          recheck = mkOption {
            type = bool;
            default = false;
            description = "Whether to recheck paused torrents sorted by lowest size. Resume if Completed.";
          };
          catUpdate = mkOption {
            type = bool;
            default = false;
            description = "Whether to update your categories.";
          };
          tagUpdate = mkOption {
            type = bool;
            default = false;
            description = "Whether to update your tags and/or set seed goals/limit upload speed by tag.";
          };
          remUnregistered = mkOption {
            type = bool;
            default = false;
            description = "Whether to remove unregistered torrents.";
          };
          tagTrackerError = mkOption {
            type = bool;
            default = false;
            description = "Whether to tag torrents that do not have a working tracker.";
          };
          remOrphaned = mkOption {
            type = bool;
            default = false;
            description = "Whether to remove orphaned files from your 'root_dir' directory that are not referenced by any torrents.";
          };
          tagNoHardLinks = mkOption {
            type = bool;
            default = false;
            description = "Whether to tag torrents where the largest file does not have any hardlinks associated with any of the files outside of your qbit-manage root directory.";
          };
          shareLimits = mkOption {
            type = bool;
            default = false;
            description = "Whether to control how torrent share limits are set depending on the priority of your grouping.";
          };
          skipCleanup = mkOption {
            type = bool;
            default = false;
            description = "Whether to skip emptying the recycle Bin folder and Orphaned directory.";
          };
        };
      };
    };

    webServer = mkOption {
      description = "Web server configuration.";
      default = { };
      type = submodule {
        options = {
          enable = mkEnableOption "Enable the web server.";

          port = mkOption {
            type = port;
            default = 8181;
            description = "Port number for the web server.";
          };

          host = mkOption {
            type = nullOr str;
            default = null;
            description = "Hostname for the web server.";
          };

          baseURL = mkOption {
            type = nullOr str;
            default = null;
            description = "Base URL path for the web UI (e.g., '/qbit-manage').";
          };

          openFirewall = mkEnableOption "Open the firewall for webUI.";
        };
      };
    };

    extraArgs = mkOption {
      type = listOf str;
      default = [ ];
      description = "Extra command line arguments to pass to qbit-manage.";
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      {
        assertion =
          (cfg.settings == null)
          || (
            (!cfg.commands.remOrphaned) && (!cfg.commands.tagNoHardLinks) && (!cfg.commands.remUnregistered)
          )
          || (cfg.settings.directory != null && cfg.settings.directory.root_dir != null);
        message = "services.qbit-manage.settings.directory.root_dir must be set when using remOrphaned, tagNoHardLinks or remUnregistered commands.";
      }
    ];

    networking.firewall.allowedTCPPorts = optional (
      cfg.webServer.enable && cfg.webServer.openFirewall
    ) cfg.webServer.port;

    users = {
      users = mkIf (cfg.user == "qbit-manage") {
        qbit-manage = {
          inherit (cfg) group;
          isSystemUser = true;
        };
      };

      groups = mkIf (cfg.group == "qbit-manage") { qbit-manage = { }; };
    };

    systemd = {
      services."qbit-manage" = {
        description = "Tool to manage tasks for qBittorrent";
        enable = true;
        after = [ "network.target" ];
        wantedBy = [ "multi-user.target" ];
        preStart = optionalString (cfg.settings != null) ''
          install -D -m 600 '${createYAMLConfig cfg.settings}' "$STATE_DIRECTORY/config.yml"
        '';
        serviceConfig = {
          Type = "simple";
          User = cfg.user;
          Group = cfg.group;
          StateDirectory = "qbit-manage";
          ExecStart =
            let
              webServerFlags =
                if cfg.webServer.enable then
                  [
                    "--web-server"
                    "--port ${toString cfg.webServer.port}"
                  ]
                  ++ optional (cfg.webServer.host != null) "--host ${cfg.webServer.host}"
                  ++ optional (cfg.webServer.baseURL != null) "--base-url ${cfg.webServer.baseURL}"
                else
                  [ "--web-server=False" ];

              commandFlags =
                optional (cfg.commands.startupDelay != null) "--startup-delay ${toString cfg.commands.startupDelay}"
                ++ optional (cfg.commands.schedule == null) "--run"
                ++ optional (cfg.commands.schedule != null) "--schedule ${toString cfg.commands.schedule}"
                ++ optional cfg.commands.recheck "--recheck"
                ++ optional cfg.commands.catUpdate "--cat-update"
                ++ optional cfg.commands.tagUpdate "--tag-update"
                ++ optional cfg.commands.remUnregistered "--rem-unregistered"
                ++ optional cfg.commands.tagTrackerError "--tag-tracker-error"
                ++ optional cfg.commands.remOrphaned "--rem-orphaned"
                ++ optional cfg.commands.tagNoHardLinks "--tag-nohardlinks"
                ++ optional cfg.commands.shareLimits "--share-limits"
                ++ optional cfg.commands.skipCleanup "--skip-cleanup";

              flags = [
                "--config-dir %S/qbit-manage"
              ]
              ++ webServerFlags
              ++ commandFlags
              ++ cfg.extraArgs;
            in
            "${getExe cfg.package} ${concatStringsSep " " flags}";

          EnvironmentFile = mkIf (cfg.environmentFile != null) cfg.environmentFile;

          # Hardening
          ProtectSystem = "full";
          ProtectHome = true;
          PrivateMounts = true;
          ProtectKernelTunables = true;
          ProtectKernelModules = true;
          ProtectKernelLogs = true;
          ProtectControlGroups = true;
          LockPersonality = true;
          RestrictRealtime = true;
          ProtectClock = true;
          MemoryDenyWriteExecute = true;
          RestrictAddressFamilies = [
            "AF_INET"
            "AF_INET6"
            "AF_NETLINK"
            "AF_UNIX"
          ];
          SocketBindDeny = [
            "ipv4:udp"
            "ipv6:udp"
          ];
          CapabilityBoundingSet = [
            "~CAP_BLOCK_SUSPEND"
            "~CAP_BPF"
            "~CAP_IPC_LOCK"
            "~CAP_MKNOD"
            "~CAP_NET_RAW"
            "~CAP_PERFMON"
            "~CAP_SYS_BOOT"
            "~CAP_SYS_CHROOT"
            "~CAP_SYS_MODULE"
            "~CAP_SYS_NICE"
            "~CAP_SYS_PACCT"
            "~CAP_SYS_PTRACE"
            "~CAP_SYS_TIME"
            "~CAP_SYSLOG"
            "~CAP_WAKE_ALARM"
          ];
          SystemCallFilter = [
            "~@aio:EPERM"
            "~@clock:EPERM"
            "~@cpu-emulation:EPERM"
            "~@debug:EPERM"
            "~@keyring:EPERM"
            "~@memlock:EPERM"
            "~@module:EPERM"
            "~@mount:EPERM"
            "~@obsolete:EPERM"
            "~@pkey:EPERM"
            "~@raw-io:EPERM"
            "~@reboot:EPERM"
            "~@resources:EPERM"
            "~@sandbox:EPERM"
            "~@setuid:EPERM"
            "~@swap:EPERM"
            "~@sync:EPERM"
            "~@timer:EPERM"
          ];
        };
      };
    };
  };
  meta.maintainers = with lib.maintainers; [
    flyingpeakock
  ];
}